AdSense

網頁

2024/3/21

Golang Gin 將請求參數綁定為struct

Gin可使用gin.Context.BindQuerygin.Context.ShouldBindQuery將URL查詢參數(query string)轉為struct。


範例

Struct欄位後使用form tag來對應query string。time_format tag設定轉換的時間的格式,若未設定則預設為RFC3339time_utc tag設定轉換時間是否使用UTC時間。

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
)

type QueryString struct {
    Name      string     `form:"name" binding:"required"`
    Age       int        `form:"age" binding:"required"`
    StartTime *time.Time `form:"startTime" binding:"required" time_format:"2006-01-02T15:04:05" time_utc:"1"`
    EndTime   *time.Time `form:"endTime" binding:"required" time_format:"2006-01-02T15:04:05" time_utc:"1"`
}

func (q QueryString) String() string {
    return fmt.Sprintf("{Name=%s, Age=%d, StartTime=%s, EndTime=%s}", q.Name, q.Age, q.StartTime, q.EndTime)
}

func main() {
    router := gin.Default()
    router.GET("/find", func(c *gin.Context) {
        var qs QueryString
        err := c.ShouldBindQuery(&qs)
        if err != nil {
            return
        }
        fmt.Println(qs)
        c.Status(http.StatusOK)
    })
    router.Run()
}

github


測試

啟動應用程式,在瀏覽器輸入http://localhost:8080/find?name=john&age=33&startTime=2024-03-19T09%3A00%3A00&endTime=2024-03-19T10%3A00%3A00,則在console印出以下:

{Name=john, Age=33, StartTime=2024-03-19 09:00:00 +0000 UTC, EndTime=2024-03-19 10:00:00 +0000 UTC}
[GIN] 2024/03/21 - 16:12:05 | 200 |     347.625µs |             ::1 | GET      "/find?name=john&age=33&startTime=2024-03-19T09%3A00%3A00&endTime=2024-03-19T10%3A00%3A00"


沒有留言:

AdSense