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

相关推荐
前端.火鸡8 小时前
记录一篇HTTPS的文章
网络协议·http·https
张声录111 小时前
Windows 环境下 Golang 与 Vosk-API 语音识别开发环境搭建指南
windows·golang·语音识别
IsPrisoner15 小时前
Go 语言实现高性能 EventBus 事件总线系统(含网络通信、微服务、并发异步实战)
开发语言·微服务·golang
循环渐进Forward15 小时前
【TinyWebServer】HTTP连接处理
linux·网络·c++·网络协议·算法·http
论迹15 小时前
【JavaEE】-- HTTP
java·http·java-ee
大得36915 小时前
go全局配置redis,全局只需要连接一次,然后全局可以引用使用
开发语言·redis·golang
Cxzzzzzzzzzz17 小时前
Go语言堆内存管理
开发语言·后端·golang
何双新18 小时前
Cursor+MCP编程工具助力开发效率倍增
中间件·golang·pycharm
why1511 天前
微服务商城-商品微服务
数据库·后端·golang