Home Gin框架急速入门
Post
Cancel

Gin框架急速入门

 安装go

go 1.17   ( 下载tar, 编译)

1870 tar zxvf go1.17.linux-amd64.tar.gz go
1871 mv go /usr/local/
1872 sudo mv go /usr/local/

export PATH=$PATH:/usr/local/go/bin

查看环境:  $ go env

修改代理:

export GOPROXY=https://goproxy.cn

安装gin

参考: https://github.com/gin-gonic/gin

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

vim server.go

package main
import "github.com/gin-gonic/gin"

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

运行:  $ go run server.go 

即可。

性能超好,在虚拟机上, 7000 req/s

带上参数:

package main
import "github.com/gin-gonic/gin"
import "net/http"

func main() {
  router := gin.Default()
  router.GET("/user/:name", func(c *gin.Context){
    name := c.Param("name")
    c.String(http.StatusOK, "Hihihi , %s", name)
  })

  router.GET("/book/show", func(c *gin.Context){
    name := c.Query("name")
    year := c.Query("year")
    c.String(http.StatusOK, "show me this booK: %s %s", name, year)
  })

  router.Run(":8080")
}

带上POST参数:

package main

import "github.com/gin-gonic/gin"
//import "net/http"

func main(){
  router := gin.Default()
  router.POST("/book/create", func(c *gin.Context){
    c.JSON(200, gin.H {
      "name": c.PostForm("name"),
      "author": c.PostForm("author"),     // 注意这个 , 不能省略
    })
  })
  router.Run(":8080")
}

This post is licensed under CC BY 4.0 by the author.
Contents