Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了golang gin 中间件,返回结果大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
package main

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

func response() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Next()
        if c.Writer.Written() {
            return
        }

        params := c.Keys
        if len(params) == 0 {
            return
        }
        c.JSON(http.StatusOK,params)
    }
}

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

    r.GET("/ping",func(c *gin.Context) {
        c.String(http.StatusOK,"PONG")
    })

    r.GET("/status",func(c *gin.Context) {
        c.Status(http.StatusOK)
    })

    r.GET("/Hello",func(c *gin.Context) {
        c.Set("message","Hello,world")
    })

    r.Run()
}

  

?  src  go run main.go
[GIN-debug] [WARNING] CreaTing an ENGIne instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:	export GIN_MODE=release
 - using code:	gin.SetMode(gin.ReleaseModE)

[GIN-debug] GET    /ping                     --> main.main.func1 (4 handlers)
[GIN-debug] GET    /status                   --> main.main.func2 (4 handlers)
[GIN-debug] GET    /Hello                    --> main.main.func3 (4 handlers)
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving http on :8080
[GIN] 2018/11/15 - 23:23:23 | 200 |     128.732µs |       127.0.0.1 | GET      /ping
[GIN] 2018/11/15 - 23:23:26 | 200 |       1.764µs |       127.0.0.1 | GET      /status
[GIN] 2018/11/15 - 23:23:31 | 200 |      135.48µs |       127.0.0.1 | GET      /Hello

  

?  ~  http http://127.0.0.1:8080/ping
http/1.1 200 OK
Content-Length: 4
Content-Type: text/plain; charset=utf-8
Date: Thu,15 Nov 2018 15:23:23 GMT

PONG

?  ~  http http://127.0.0.1:8080/status
http/1.1 200 OK
Content-Length: 0
Date: Thu,15 Nov 2018 15:23:26 GMT



?  ~  http http://127.0.0.1:8080/Hello
http/1.1 200 OK
Content-Length: 26
Content-Type: application/json; charset=utf-8
Date: Thu,15 Nov 2018 15:23:31 GMT

{
    "message": "Hello,world"
}

大佬总结

以上是大佬教程为你收集整理的golang gin 中间件,返回结果全部内容,希望文章能够帮你解决golang gin 中间件,返回结果所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。