【Golang】Web Framework - Gin 使用

Posted by 西维蜀黍 on 2020-01-12, Last Modified on 2021-09-21

路由

gin 框架中采用的路由库是 httprouter。

// 创建带有默认中间件的路由:
// 日志与恢复中间件
router := gin.Default()

router.GET("/someGet", getting)
router.POST("/somePost", posting)
router.PUT("/somePut", putting)
router.DELETE("/someDelete", deleting)
router.PATCH("/somePatch", patching)
router.HEAD("/someHead", head)
router.OPTIONS("/someOptions", options)

Controller 中获取参数

api 参数通过Context的Param方法来获取

router.GET("/string/:name", func(c *gin.Context) {
    	name := c.Param("name")
    	fmt.Println("Hello %s", name)
    })

URL 参数通过 DefaultQuery 或 Query 方法获取

// url 为 http://localhost:8080/welcome?name=ningskyer时
// 输出 Hello ningskyer
// url 为 http://localhost:8080/welcome时
// 输出 Hello Guest
router.GET("/welcome", func(c *gin.Context) {
	name := c.DefaultQuery("name", "Guest") //可设置默认值
	// 是 c.Request.URL.Query().Get("lastname") 的简写
	lastname := c.Query("lastname") 
	fmt.Println("Hello %s", name)
})

form 中的参数通过 PostForm 方法获取

//form
router.POST("/form", func(c *gin.Context) {
	type := c.DefaultPostForm("type", "alert")//可设置默认值
	msg := c.PostForm("msg")
	title := c.PostForm("title")
	fmt.Println("type is %s, msg is %s, title is %s", type, msg, title)
})

使用 Sessions

使用 Sessions 的方法

r := gin.Default()

# init the usage of sessions
store := cookie.NewStore([]byte("secret"))
r.Use(sessions.Sessions("mysession", store))

// register route
router.GET("/register", controllers.RegisterGet)
router.POST("/register", controllers.RegisterPost)
router.GET("/login", controllers.LoginGet)
router.POST("/login", controllers.LoginPost)

否则会有这个错误

2019/12/30 15:50:18 [Recovery] 2019/12/30 - 15:50:18 panic recovered:
POST /login/ HTTP/1.1
Host: 127.0.0.1:8081
Accept: */*
Accept-Encoding: gzip, deflate
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 31
Content-Type: application/x-www-form-urlencoded
Cookie: REC_T_ID=dd1b3c6e-2188-11ea-8506-acde48001122; SPC_F=6ZevBFRrReyMP8xzEWNZYhA39Zh5RJCP; SPC_IA=-1; SPC_U=-; SPC_EC=-; mysession=MTU3NzY5MjE0MXxEdi1CQkFFQ180SUFBUkFCRUFBQUpQLUNBQUVHYzNSeWFXNW5EQWNBQldobGJHeHZCbk4wY21sdVp3d0hBQVYzYjNKc1pBPT18vPPUSn81suSunkGtkAVaOFOpK1SYbhZiJMAiOLeVeRU=
Postman-Token: 06cacb8b-8550-4da9-8a8c-a727c761c45a
User-Agent: PostmanRuntime/7.21.0


Key "github.com/gin-contrib/sessions" does not exist
/Users/wei.shi/go/pkg/mod/github.com/gin-gonic/gin@v1.5.0/context.go:240 (0x15911e0)
        (*Context).MustGet: panic("Key \"" + key + "\" does not exist")
/Users/wei.shi/go/pkg/mod/github.com/gin-contrib/sessions@v0.0.3/sessions.go:139 (0x1590d1a)
        Default: return c.MustGet(DefaultKey).(Session)
/Working/EntryTask3/Gateway/Controllers/Login/loginControllers.go:51 (0x1590cc9)
        Login: session := sessions.Default(c)
/Users/wei.shi/go/pkg/mod/github.com/gin-gonic/gin@v1.5.0/context.go:147 (0x14fa46a)
        (*Context).Next: c.handlers[c.index](c)
/Users/wei.shi/go/pkg/mod/github.com/gin-gonic/gin@v1.5.0/recovery.go:83 (0x150df03)
        RecoveryWithWriter.func1: c.Next()
/Users/wei.shi/go/pkg/mod/github.com/gin-gonic/gin@v1.5.0/context.go:147 (0x14fa46a)
        (*Context).Next: c.handlers[c.index](c)
/Users/wei.shi/go/pkg/mod/github.com/gin-gonic/gin@v1.5.0/logger.go:241 (0x150d030)
        LoggerWithConfig.func1: c.Next()
/Users/wei.shi/go/pkg/mod/github.com/gin-gonic/gin@v1.5.0/context.go:147 (0x14fa46a)
        (*Context).Next: c.handlers[c.index](c)
/Users/wei.shi/go/pkg/mod/github.com/gin-gonic/gin@v1.5.0/gin.go:403 (0x1504499)
        (*Engine).handleHTTPRequest: c.Next()
/Users/wei.shi/go/pkg/mod/github.com/gin-gonic/gin@v1.5.0/gin.go:364 (0x1503b8d)
        (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/local/go/src/net/http/server.go:2802 (0x12cbfe3)
        serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/go/src/net/http/server.go:1890 (0x12c7884)
        (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/local/go/src/runtime/asm_amd64.s:1357 (0x105c0a0)
        goexit: BYTE    $0x90   // NOP

Reference