-
1.安装github.com/gin-gonic/gin
输入命令go get github.com/gin-gonic/gin 进行安装
当长时间没有反应的时候我就知道又有一些包被墙了,这次还是两个。然而一点也不慌,还是手动去github上下载缺失的包之后
运行:install $(GOPATH)\src\github.com/gin-gonic/gin 手动安装
-
2.一个简单的服务器示例
package main
import (
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
type User struct {
ID int64
Name string
Age int
CreatedTime time.Time
UpdatedTime time.Time
IsDeleted bool
}
func main() {
//初始化引擎
r := gin.Default()
//简单的Get请求
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
//GET请求通过name获取参数 /user/test
r.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
//GET请求通过正常的URL获取参数 /getuser?id=2
r.GET("/getuser", func(c *gin.Context) {
rid := c.DefaultQuery("id", "1")
id, _ := strconv.ParseInt(rid, 10, 64)
user := User{ID: id, Age: 32, CreatedTime: time.Now(), UpdatedTime: time.Now(), IsDeleted: true}
c.JSON(http.StatusOK, user)
})
//POST请求通过绑定获取对象
r.POST("/adduser", func(c *gin.Context) {
var user User
err := c.ShouldBind(&user)
if err == nil {
c.JSON(http.StatusOK, user)
} else {
c.String(http.StatusBadRequest, "请求参数错误", err)
}
})
r.Run(":9002") // listen and serve on 0.0.0.0:8080
}
-
3.curl命令测试结果如下:
D:\>curl http://localhost:9002/ping
{"message":"pong"}
D:\>curl http://localhost:9002/user/test
Hello test
D:\>curl http://localhost:9002/getuser?id=33
{"ID":33,"Name":"","Age":32,"CreatedTime":"2019-04-18T19:31:44.3296375+08:00","UpdatedTime":"2019-04-18T19:31:44.3296375+08:00","IsDeleted":true}
D:\>curl -v --form ID=222 --form Name=dylan --form Age=3 --form IsDeleted=true --form CreatedTime=2015-09-15T14:00:12-00:00 http://localhost:9002/adduser
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 9002 (#0)
> POST /adduser HTTP/1.1
> Host: localhost:9002
> User-Agent: curl/7.55.1
> Accept: */*
> Content-Length: 558
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------db63a503440e7f15
>
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Thu, 18 Apr 2019 11:31:59 GMT
< Content-Length: 124
<
{"ID":222,"Name":"dylan","Age":3,"CreatedTime":"2015-09-15T14:00:12Z","UpdatedTime":"0001-01-01T00:00:00Z","IsDeleted":true}* Connection #0 to host localhost left intact
更多gin框架细节参考github地址:https://github.com/gin-gonic/gin