关于gin:golang-web框架gin使用教程

45次阅读

共计 3474 个字符,预计需要花费 9 分钟才能阅读完成。

Installation

To install Gin package, you need to install Go and set your Go workspace first.

  1. The first need Go installed (version 1.12+ is required), then you can use the below Go command to install Gin.

$ go get -u github.com/gin-gonic/gin

  1. Import it in your code:

import “github.com/gin-gonic/gin”

  1. (Optional) Import net/http. This is required for example if using constants such as http.StatusOK.

import “net/http”

Quick start

assume the following codes in example.go file

$ cat example.go

package main

import “github.com/gin-gonic/gin”

func main() {

r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
    c.JSON(200, gin.H{"message": "pong",})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")

}

# run example.go and visit 0.0.0.0:8080/ping (for windows "localhost:8080/ping") on browser
$ go run example.go

Using GET, POST, PUT, PATCH, DELETE and OPTIONS

func main() {

// Creates a gin router with default middleware:
// logger and recovery (crash-free) middleware
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)

// By default it serves on :8080 unless a
// PORT environment variable was defined.
router.Run()
// router.Run(":3000") for a hard coded port

}

Parameters in path

func main() {

router := gin.Default()

// This handler will match /user/john but will not match /user/ or /user
router.GET("/user/:name", func(c *gin.Context) {name := c.Param("name")
    c.String(http.StatusOK, "Hello %s", name)
})

// However, this one will match /user/john/ and also /user/john/send
// If no other routers match /user/john, it will redirect to /user/john/
router.GET("/user/:name/*action", func(c *gin.Context) {name := c.Param("name")
    action := c.Param("action")
    message := name + "is" + action
    c.String(http.StatusOK, message)
})

// For each matched request Context will hold the route definition
router.POST("/user/:name/*action", func(c *gin.Context) {c.FullPath() == "/user/:name/*action" // true
})

router.Run(":8080")

}

Querystring parameters

func main() {

router := gin.Default()

// Query string parameters are parsed using the existing underlying request object.
// The request responds to a url matching:  /welcome?firstname=Jane&lastname=Doe
router.GET("/welcome", func(c *gin.Context) {firstname := c.DefaultQuery("firstname", "Guest")
    lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")

    c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})
router.Run(":8080")

}

Multipart/Urlencoded Form

func main() {

router := gin.Default()

router.POST("/form_post", func(c *gin.Context) {message := c.PostForm("message")
    nick := c.DefaultPostForm("nick", "anonymous")

    c.JSON(200, gin.H{
        "status":  "posted",
        "message": message,
        "nick":    nick,
    })
})
router.Run(":8080")

}

Another example: query + post form

POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded

name=manu&message=this_is_great 

func main() {

router := gin.Default()

router.POST("/post", func(c *gin.Context) {id := c.Query("id")
    page := c.DefaultQuery("page", "0")
    name := c.PostForm("name")
    message := c.PostForm("message")

    fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
})
router.Run(":8080")

}

id: 1234; page: 1; name: manu; message: this_is_great 

Map as querystring or postform parameters

POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1
Content-Type: application/x-www-form-urlencoded

names[first]=thinkerou&names[second]=tianou 

func main() {

router := gin.Default()

router.POST("/post", func(c *gin.Context) {ids := c.QueryMap("ids")
    names := c.PostFormMap("names")

    fmt.Printf("ids: %v; names: %v", ids, names)
})
router.Run(":8080")

}

ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou] 

更多 Gin 应用请移步:Gin 装置应用具体教程

正文完
 0