【Golang | Gin】net/http和Gin起web服务时的简单对比

引言

Gin 是一个用 Go (Golang) 编写的 Web 框架,详细介绍参考官网:https://gin-gonic.com/zh-cn/docs/introduction/

net/http

开始学习Gin之前,我们先首先回顾下使用net/http起一个简单的helloworld服务

package main

import (
	"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来注册路由信息。/是一个patterngreet是一个handler函数,意思是当客户端访问路径/时,服务端自动执行greet函数

2、handler函数需要满足func(ResponseWriter, *Request)格式,当执行handler函数时,从封装好的*Request中获取请求方法、请求body等信息,处理完后,将需要返回的信息写入ResponseWriter

3、http.ListenAndServe就是启动服务,并监听8080端口

Gin

现在我们再来看看官网的快速入门示例(https://gin-gonic.com/zh-cn/docs/quickstart/)

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() // 监听并在 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 https://pkg.go.dev/github.com/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,gin,http)