[go]gin框架

gin参考

Gin框架返回值

// 返回json

func main() {
    r := gin.Default()

    //方法一: 自己拼接json
    // gin.H is a shortcut for map[string]interface{}
    r.GET("/someJSON", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
    })
    
    //方法2: 返回结构体对象
    r.GET("/moreJSON", func(c *gin.Context) { // You also can use a struct
        var msg struct {
            Name    string `json:"user"`
            Message string
            Number  int
        }
        msg.Name = "Lena"
        msg.Message = "hey"
        msg.Number = 123
        
        // Note that msg.Name becomes "user" in the JSON
        c.JSON(http.StatusOK, msg)
    })

    // Listen and serve on 0.0.0.0:8080
    r.Run(":8080")
}
// 渲染html

router.LoadHTMLGlob("templates/*")
router.Static("/static", "./static") 

func main() {
    router := gin.Default()

    router.LoadHTMLGlob("templates/*")
    router.Static("/static", "./static") //第二个参数相对于执行路径

    //渲染静态目录
    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", nil)
    })
    router.Run(":8000")
}

Gin框架参数传递

//获取参数 querystring

/user/search?name=mm&age=22

r.GET("/user/search", func(c *gin.Context)
name := c.DefaultQuery("name", "mm") // 赋默认值
name := c.Query("name")

func main() {
    r := gin.Default()
    r.GET("/user/search", func(c *gin.Context) {
        name := c.DefaultQuery("name", "mm")
        //name := c.Query("name")
        age := c.Query("age")

        //输出json结果给调用方
        c.JSON(200, gin.H{
            "message":  "pong",
            "name": name,
            "age":  age,
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}
// 获取参数 path

/user/search/mm/22
r.GET("/user/search/:name/:age", func(c *gin.Context) 

name := c.Param("mm")

func main() {
    r := gin.Default()
    r.GET("/user/search/:name/:age", func(c *gin.Context) {
        name := c.Param("mm")
        age := c.Param("age")

        //输出json结果给调用方
        c.JSON(200, gin.H{
            "message":  "pong",
            "username": username,
            "address":  address,
        })
    })

    r.Run(":8080") // listen and serve on 0.0.0.0:8080
}
// 获取参数: form提交

r.POST("/user/search", func(c *gin.Context) {
name := c.DefaultPostForm("name", "mm")
name := c.PostForm("name")

func main() {
    r := gin.Default()
    r.POST("/user/search", func(c *gin.Context) {
        //name := c.DefaultPostForm("name", "mm")
        name := c.PostForm("name")
        age := c.PostForm("age")
        //输出json结果给调用方
        c.JSON(200, gin.H{
            "message":  "pong",
            "name": name,
            "age":  age,
        })
    })

    r.Run(":8080")
}

// Binding from JSON
type Login struct {
    User     string `form:"user" json:"user" binding:"required"`
    Password string `form:"password" json:"password" binding:"required"`
}

func main() {
    router := gin.Default()

    // Example for binding JSON ({"user": "manu", "password": "123"})
    router.POST("/loginJSON", func(c *gin.Context) {
        var login Login

        if err := c.ShouldBindJSON(&login); err == nil {
            fmt.Printf("login info:%#v\n", login)
            c.JSON(http.StatusOK, gin.H{
                "user":     login.User,
                "password": login.Password,
            })
        } else {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        }
    })

    // Example for binding a HTML form (user=manu&password=123)
    router.POST("/loginForm", func(c *gin.Context) {
        var login Login
        // This will infer what binder to use depending on the content-type header.
        if err := c.ShouldBind(&login); err == nil {
            c.JSON(http.StatusOK, gin.H{
                "user":     login.User,
                "password": login.Password,
            })
        } else {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        }
    })

    // Example for binding a HTML querystring (user=manu&password=123)
    router.GET("/loginForm", func(c *gin.Context) {
        var login Login
        // This will infer what binder to use depending on the content-type header.
        if err := c.ShouldBind(&login); err == nil {
            c.JSON(http.StatusOK, gin.H{
                "user":     login.User,
                "password": login.Password,
            })
        } else {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        }
    })

    // Listen and serve on 0.0.0.0:8080
    router.Run(":8080")
}

gin Restful

// restful风格

func main() {
    //Default返回一个默认的路由引擎
    r := gin.Default()
    r.GET("/user/info", func(c *gin.Context) {
        //输出json结果给调用方
        c.JSON(200, gin.H{
            "message": "get user info succ",
        })
    })
    r.POST("/user/info", func(c *gin.Context) {
        //输出json结果给调用方
        c.JSON(200, gin.H{
            "message": "create user info succ",
        })
    })
    r.PUT("/user/info", func(c *gin.Context) {
        //输出json结果给调用方
        c.JSON(200, gin.H{
            "message": "update user info succ",
        })
    })
    r.DELETE("/user/info", func(c *gin.Context) {
        //输出json结果给调用方
        c.JSON(200, gin.H{
            "message": "delete user info succ ",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}
// 版本管理

func login(ctx *gin.Context) {
    ctx.JSON(200, gin.H{
        "message": "success",
    })
}

func read(ctx *gin.Context) {
    ctx.JSON(200, gin.H{
        "message": "success",
    })
}

func submit(ctx *gin.Context) {
    ctx.JSON(200, gin.H{
        "message": "success",
    })
}

func main() {
    //Default返回一个默认的路由引擎
    router := gin.Default()

    // Simple group: v1
    //   /v1/login
    //   /v1/submit
    //   /v1/read
    v1 := router.Group("/v1")
    {
        v1.POST("/login", login)
        v1.POST("/submit", submit)
        v1.POST("/read", read)
    }

    // Simple group: v2
    //   /v2/login
    //   /v2/submit
    //   /v2/read
    v2 := router.Group("/v2")
    {
        v2.POST("/login", login)
        v2.POST("/submit", submit)
        v2.POST("/read", read)
    }

    router.Run(":8080")
}

Gin中间件

//计算请求耗时

func StatCost() gin.HandlerFunc {
    return func(c *gin.Context) {
        t := time.Now()

        //可以设置一些公共参数
        c.Set("example", "12345")
        //等其他中间件先执行
        c.Next()
        //获取耗时
        latency := time.Since(t)
        log.Printf("total cost time:%d us", latency/1000)
    }
}

func main() {
    //r := gin.New()
    r := gin.Default()
    r.Use(StatCost())

    r.GET("/test", func(c *gin.Context) {
        example := c.MustGet("example").(string)

        // it would print: "12345"
        log.Println(example)
        c.JSON(http.StatusOK, gin.H{
            "message": "success",
        })
    })

    // Listen and serve on 0.0.0.0:8080
    r.Run()
}
// 从第三方获取数据

func main() {
    router := gin.Default()
    router.GET("/someDataFromReader", func(c *gin.Context) {
        response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
        if err != nil || response.StatusCode != http.StatusOK {
            c.Status(http.StatusServiceUnavailable)
            return
        }

        reader := response.Body
        contentLength := response.ContentLength
        contentType := response.Header.Get("Content-Type")

        extraHeaders := map[string]string{
            "Content-Disposition": `attachment; filename="gopher.png"`,
        }

        c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
    })
    router.Run(":8080")
}

Gin写日志

//写日志到文件

func main() {
    // Disable Console Color, you don't need console color when writing the logs to file.
    gin.DisableConsoleColor()
    
    // Logging to a file.
    f, _ := os.Create("/tmp/gin.log")

    gin.DefaultWriter = io.MultiWriter(f)
    
    // Use the following code if you need to write the logs to file and console at the same time.
    // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
    //Default返回一个默认的路由引擎
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        //输出json结果给调用方
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    
    r.Run() // listen and serve on 0.0.0.0:8080
}
// 自定义日志格式

func main() {
    router := gin.New()

    // LoggerWithFormatter 中间件会将日志写入 gin.DefaultWriter
    // By default gin.DefaultWriter = os.Stdout
    router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {

        // 你的自定义格式
        return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
                param.ClientIP,
                param.TimeStamp.Format(time.RFC1123),
                param.Method,
                param.Path,
                param.Request.Proto,
                param.StatusCode,
                param.Latency,
                param.Request.UserAgent(),
                param.ErrorMessage,
        )
    }))
    router.Use(gin.Recovery())

    router.GET("/ping", func(c *gin.Context) {
        c.String(200, "pong")
    })

    router.Run(":8080")
}

猜你喜欢

转载自www.cnblogs.com/iiiiiher/p/12014263.html