本篇文章說明 gin 的部分函式和結構

gin.Default

Default returns an Engine instance with the Logger and Recovery middleware already attached.

1
router := gin.Default

gin.Engine

Engine is the framework’s instance, it contains the muxer, middleware and configuration settings. Create an instance of Engine, by using New() or Default()

gin.Engine.LoadHTMLGlob

LoadHTMLGlob loads HTML files identified by glob pattern and associates the result with HTML renderer.

1
router.LoadHTMLGlob("templates/*")

gin.Engine.Static

Static serves files from the given file system root. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router’s NotFound handler. To use the operating system’s file system implementation, use :

1
router.Static("/public", "public")

gin.Engine.GET

GET is a shortcut for router.Handle(“GET”, path, handle).

1
2
3
4
5
6
router.GET("/", homePage)

func homePage(ctx *gin.Context) {
message, _ := ctx.GetQuery("message") // Get query string
ctx.String(http.StatusOK, "Hello world")
}

gin.Engine.POST

POST is a shortcut for router.Handle(“POST”, path, handle).

1
2
3
4
5
6
router.POST("/", homePage)

func homePage(ctx *gin.Context) {
message := ctx.PostForm("message") // Get Post form data
ctx.String(http.StatusOK, "Hello world")
}

gin.Context

Context is the most important part of gin. It allows us to pass variables between middleware, manage the flow, validate the JSON of a request and render a JSON response for example.

gin.Context.GetQuery

GetQuery is like Query(), it returns the keyed url query value if it exists (value, true) (even when the value is an empty string), otherwise it returns ("", false). It is shortcut for c.Request.URL.Query().Get(key)

1
2
3
4
// GET /?name=Manu&lastname=
c.GetQuery("name") // ("Manu", true)
c.GetQuery("id") // ("", false)
c.GetQuery("lastname") // ("", true)

gin.Context.PostForm

PostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns an empty string ("").

1
message := ctx.PostForm("message")

gin.Context.Redirect

Redirect returns an HTTP redirect to the specific location.

1
ctx.Redirect(http.StatusFound, "/member")

gin.Context.HTML

HTML renders the HTTP template specified by its file name. It also updates the HTTP code and sets the Content-Type as “text/html”. See http://golang.org/doc/articles/wiki/

1
ctx.HTML(http.StatusOK, "square.html", gin.H{"num": num, "result": result})