【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端口

相关推荐
yqcoder37 分钟前
1. http 有哪些版本,你是用的哪个版本,怎么查看
网络·网络协议·http
2501_915918415 小时前
接口漏洞怎么抓?Fiddler 中文版 + Postman + Wireshark 实战指南
websocket·网络协议·tcp/ip·http·网络安全·https·udp
不老刘5 小时前
基于LiveKit Go 实现腾讯云实时音视频功能
golang·腾讯云·实时音视频
御控工业物联网5 小时前
御控网关如何实现MQTT、MODBUS、OPCUA、SQL、HTTP之间协议转换
数据库·sql·http
Code季风6 小时前
Gin Web 层集成 Viper 配置文件和 Zap 日志文件指南(下)
前端·微服务·架构·go·gin
Code季风6 小时前
Gin Web 服务集成 Consul:从服务注册到服务发现实践指南(下)
java·前端·微服务·架构·go·gin·consul
en-route6 小时前
HTTP cookie
网络·网络协议·http
yqcoder7 小时前
2. 你可以说一下 http 版本的发展过程吗
网络·网络协议·http
会飞的鱼先生19 小时前
Node.js-http模块
网络协议·http·node.js
简佐义的博客19 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang