admin管理员组文章数量:1516870
【Golang
引言
Gin 是一个用 Go (Golang) 编写的 Web 框架,详细介绍参考官网:/
net/http
开始学习Gin之前,我们先首先回顾下使用net/http起一个简单的helloworld服务
package mainimport ("fmt""net/http""time"
)func greet(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "Hello World! %s", time.Now())
}func main() {http.HandleFunc("/", greet)http.ListenAndServe(":8080", nil)
}
注:
1、http.HandleFunc: 使用一个默认的DefaultServeMux来注册路由信息。/是一个pattern,greet是一个handler函数,意思是当客户端访问路径/时,服务端自动执行greet函数
2、handler函数需要满足func(ResponseWriter, *Request)格式,当执行handler函数时,从封装好的*Request中获取请求方法、请求body等信息,处理完后,将需要返回的信息写入ResponseWriter
3、http.ListenAndServe就是启动服务,并监听8080端口
Gin
现在我们再来看看官网的快速入门示例(/)
package mainimport "github/gin-gonic/gin"func main() {r := gin.Default()r.GET("/ping", func(c *gin.Context) {c.JSON(200, gin.H{"message": "pong",})})r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}
先运行下,看看效果。可以看到,先是输出了一堆debug日志,最后也是在8080端口开启服务并监听
PS E:\goland-workspace\GolangLearning\gin\demo> 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 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check /github/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
下面参考net/http,我们来看看,这段Gin代码都做了些什么
1、r := gin.Default() 启动了一个默认的Engine实例,自带了一些Logger等中间件。这个Engine实例类似net/http中的DefaultServeMux,用来保存路由信息。添加的路由默认放在trees中
func New() *Engine {...engine := &Engine{...trees: make(methodTrees, 0, 9),...
2、r.GET类似net/http中的http.HandleFunc,用来注册路由信息,包括了请求方法GET、请求路径relativePath和执行函数handlers
// GET is a shortcut for router.Handle("GET", path, handle).
func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {return group.handle(http.MethodGet, relativePath, handlers)
}
3、relativePath 类似net/http中的pattern; handlers类似net/http中的handler,区别在于handlers可以对应多个执行函数
4、HandlerFunc 是一个函数类型type HandlerFunc func(*Context),入参*gin.Context相比于把net/http中的入参w http.ResponseWriter, r *http.Request做了封装,当执行handler时,从*gin.Context中获取请求信息,并将执行结果返回给*gin.Context
5、r.Run()就类似net/http中的http.ListenAndServe了,目的就是启动服务,并监听8080端口
本文标签: golang
版权声明:本文标题:【Golang 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.betaflare.com/biancheng/1700665392a319935.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。


发表评论