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

引言

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

net/http

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

go 复制代码
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/)

go 复制代码
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端口开启服务并监听

bash 复制代码
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

go 复制代码
func New() *Engine {
	...
	engine := &Engine{
	    ...
		trees:                  make(methodTrees, 0, 9),
		...

2、r.GET类似net/http中的http.HandleFunc,用来注册路由信息,包括了请求方法GET、请求路径relativePath和执行函数handlers

go 复制代码
// 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端口

相关推荐
LUCIAZZZ2 小时前
Https解决了Http的哪些问题
java·网络·网络协议·spring·http·rpc·https
Villiam_AY2 小时前
goredis常见基础命令
redis·golang
PyAIGCMaster2 小时前
50周学习go语言:第四周 函数与错误处理深度解析
开发语言·学习·golang
PyAIGCMaster2 小时前
第二周补充:Go语言中&取地址符与fmt函数详解
开发语言·后端·golang
一天八小时6 小时前
计算机网络————(一)HTTP讲解
网络协议·计算机网络·http
闲猫8 小时前
go orm GORM
开发语言·后端·golang
丁卯4049 小时前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
哑巴语天雨18 小时前
前端面试-网络协议篇
websocket·网络协议·http·面试·https
小梁不秃捏21 小时前
HTTP 常见状态码技术解析(应用层)
网络·网络协议·计算机网络·http
卑微的小鬼1 天前
rpc和http的区别,为啥golang使用grpc 不使用http?
http·rpc·golang