Golang gin框架学习记录

本文介绍如何使用Golang微框架Gin进行项目初始化及依赖管理,演示了如何通过Govendor工具来配置并运行一个简单的Gin应用。此外,还详细解释了如何处理URL中的路径参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考文档:

  1. Golang 微框架 Gin 简介 https://www.jianshu.com/p/a31e4ee25305

一、使用 Govendor

Use a vendor tool like Govendor go get govendor(安装)

$ go get github.com/kardianos/govendor

Create your project folder and cd inside(创建本地项目目录,并切到该目录下)

$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"

Vendor init your project and add gin (生成vendor文件以及vendor.json,并下载gin)

$ govendor init
$ govendor fetch github.com/gin-gonic/gin@v1.2

Copy a starting template inside your project (拷贝https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go 文件到本地,实测本地main.go为空,手动从$GOPATH/src/github.com/gin-gonic/gin/examples/basic目录下拷贝即可)

$ curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go

Run your project

$ go run main.go

二、路径参数(Parameters in path)测试

当参数在url中?前面的时候,通过 value := c.Param("key")的方式获取参数,当参数在url的?后面的时候,使用 value := c.Qury("key") 方法。如果调换,则返回空字符。 源代码如下:

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	router := gin.Default();
	router.GET("/welcome/:user/*action", func(c *gin.Context){
		user := c.Param("user")
		action := c.Param("action")

		name := c.DefaultQuery("name", "uname")
		password := c.Query("password")
		age := c.Query("age")
		c.String(http.StatusOK, "user=%s, action=%s, name=%s, password=%s, age=%s\n", user, action, name, password, age)
		})
	router.Run()
}

测试方法如下:

$ curl -X GET http://127.0.0.1:8080/welcome/Guest/findsomething?dname\=jerry\&password\=123\&age\=90
user=Guest, action=/findsomething, name=uname, password=123, age=90

转载于:https://my.oschina.net/u/3045933/blog/1862491

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值