1.安装Gin框架
go get -u github.com/gin-gonic/gin
- 在代码中导入: import “github.com/gin-gonic/gin”
go get github.com/kardianos/govendor
- Govendor: 包管理工具
注意:使用gin需要Go的版本号为1.6或更高
2. 快速入门
运行这段代码并在浏览器中访问 http://localhost:22122
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.GET("/", func(context *gin.Context) {
context.String(http.StatusOK, "Hellow Word")
})
//r.Run() // listen and serve on 0.0.0.0:8080
router.Run(":22122")
}
3.获取路径参数
示例1
URL:localhost:33133/usr/kedge
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router :=gin.Default()
// 此规则能够匹配/user/john这种格式,但不能匹配/user/ 或 /user这种格式
router.GET("/usr/:name", func(context *gin.Context) {
name :=context.Param("name")
context.String(http.StatusOK, "hello %s", name)
})
router.Run(":33133")
}
示例2
URL:localhost:33133/usr/kedge/1991
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router :=gin.Default()
// 但是,这个规则既能匹配/user/john/格式也能匹配/user/john/send这种格式
// 如果没有其他路由器匹配/user/john,它将重定向到/user/john/
router.GET("/usr/:name/*age", func(context *gin.Context) {
name :=context.Param("name")
age :=context.Param("age")
message := name + " is " + age
context.String(http.StatusOK, message)
})
router.Run(":33133")
}
4. 获取 GET 参数
示例
"URL: http://localhost:44144/usr/?firstname="zhang"&lastname="kedge""
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router :=gin.Default()
// 匹配的url格式: /welcome?firstname=Jane&lastname=Doe
router.GET("/usr/", func(context *gin.Context) {
firstname := context.DefaultQuery("firstname", "Golang")
lastname := context.Query("lastname")
message := firstname + " and " + lastname
context.String(http.StatusOK, message)
//context.String(http.StatusOK, "hello %s", name)
})
router.Run(":44144")
}
5. 获取 POST 参数
示例
URL:curl -X POST http://127.0.0.1:55155/from_post -H "Content-Type:application/x-www-form-urlencoded" -d "message=hello&valuename=kedge"
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.POST("/from_post", func(c *gin.Context) {
message := c.PostForm("message")
valuename := c.DefaultPostForm("valuename", "Golang")
c.JSON(http.StatusOK, gin.H{"status": gin.H{"status_code": http.StatusOK, "status": "ok",}, "message": message, "name": valuename,})
})
router.Run(":55155")
}
在获取POST参数示例中,为什么获取值的返回顺序和代码定义顺序不一致,望大家在下面解答
PS:明天更新
- POST+GET 混合
- 单文件与多文件上传
- 部分函数基础