golang轻量级HTTP路由器插件pure的使用
Golang轻量级HTTP路由器插件pure的使用
简介
Pure是一个基于基数树的快速HTTP路由器,它坚持使用Go原生"net/http"包的实现方式,通过使用Go 1.7的"context"包保持处理程序实现的"纯净"。
主要特点
- 坚持使用Go的原生实现,同时提供便利的辅助函数
- 快速高效 - pure使用了httprouter基数树的自定义版本,因此速度非常快且高效
安装
使用go get安装:
go get -u github.com/go-playground/pure/v5
基本使用示例
package main
import (
"net/http"
"github.com/go-playground/pure/v5"
mw "github.com/go-playground/pure/v5/_examples/middleware/logging-recovery"
)
func main() {
// 创建一个新的路由器实例
p := pure.New()
// 使用日志和恢复中间件
p.Use(mw.LoggingAndRecovery(true))
// 注册GET路由
p.Get("/", helloWorld)
// 启动HTTP服务器
http.ListenAndServe(":3007", p.Serve())
}
// 简单的处理函数
func helloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World"))
}
URL参数
p := pure.New()
// 匹配的参数将存储在上下文的params中,名称为"id"
p.Get("/user/:id", UserHandler)
// 这样提取参数
rv := pure.RequestVars(r) // 这样做是为了只需从上下文中提取一次
rv.URLParam(paramname)
// 提供静态文件服务
p.Get("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))).ServeHTTP)
路由组
// 创建路由组并继承所有之前注册的中间件
user := p.Group("/user/:userid")
user.Get("", ...)
user.Post("", ...)
user.Delete("/delete", ...)
// 创建子路由组
contactInfo := user.Group("/contact-info/:cid")
contactinfo.Delete("/delete", ...)
// 创建路由组并添加额外中间件
others := p.GroupWithMore("/others", OtherHandler)
// 创建不带中间件的路由组
admin := p.GroupWithNone("/admin")
admin.Use(SomeAdminSecurityMiddleware)
请求体解码
// 第二个参数表示是否包含URL查询参数字段
if err := pure.Decode(r, true, maxBytes, &user); err != nil {
log.Println(err)
}
其他功能
// 设置自定义404处理器
p.Register404(404Handler, middleware_like_logging)
// 是否在找不到路由时重定向到末尾斜杠,默认为true
p.SetRedirectTrailingSlash(true)
// 处理405(方法不允许),默认为false
p.RegisterMethodNotAllowed(middleware)
// 自动处理OPTIONS请求;手动配置的OPTIONS处理器优先。默认为false
p.RegisterAutomaticOPTIONS(middleware)
性能
Pure使用了httprouter基数树的自定义版本,性能非常出色。在没有SEO参数定义的情况下,它甚至比lars更快。
许可证
- MIT许可证
- BSD许可证
更多关于golang轻量级HTTP路由器插件pure的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于golang轻量级HTTP路由器插件pure的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Pure - Golang轻量级HTTP路由器插件使用指南
Pure是一个极简主义的Golang HTTP路由器,它轻量、快速且易于使用。下面我将详细介绍Pure的使用方法,并提供示例代码。
安装Pure
首先使用go get安装Pure:
go get github.com/go-playground/pure
基本使用
package main
import (
"net/http"
"github.com/go-playground/pure"
)
func main() {
// 创建路由器实例
p := pure.New()
// 注册路由
p.Get("/", indexHandler)
p.Get("/users/:id", userHandler)
p.Post("/users", createUserHandler)
// 启动服务器
http.ListenAndServe(":8080", p.Serve())
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Welcome to the homepage!"))
}
func userHandler(w http.ResponseWriter, r *http.Request) {
// 获取路由参数
id := pure.RequestVars(r).URLParam("id")
w.Write([]byte("User ID: " + id))
}
func createUserHandler(w http.ResponseWriter, r *http.Request) {
// 处理POST请求
w.Write([]byte("User created!"))
}
路由参数
Pure支持路由参数和通配符:
p := pure.New()
// 命名参数
p.Get("/users/:id", func(w http.ResponseWriter, r *http.Request) {
id := pure.RequestVars(r).URLParam("id")
w.Write([]byte("User ID: " + id))
})
// 通配符
p.Get("/files/*", func(w http.ResponseWriter, r *http.Request) {
path := pure.RequestVars(r).URLParam("*")
w.Write([]byte("File path: " + path))
})
中间件支持
Pure支持中间件,可以全局或路由级别添加:
func logger(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
println("Request:", r.Method, r.URL.Path)
next(w, r)
}
}
func main() {
p := pure.New()
// 全局中间件
p.Use(logger)
// 路由级别中间件
p.Get("/admin", adminHandler, authMiddleware)
http.ListenAndServe(":8080", p.Serve())
}
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 验证逻辑
if r.Header.Get("Authorization") == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next(w, r)
}
}
路由组
Pure支持路由分组,便于组织代码:
func main() {
p := pure.New()
// API v1 路由组
apiV1 := p.Group("/api/v1")
apiV1.Get("/users", listUsersHandler)
apiV1.Post("/users", createUserHandler)
apiV1.Get("/users/:id", getUserHandler)
// 带中间件的路由组
admin := p.Group("/admin", authMiddleware)
admin.Get("/dashboard", adminDashboardHandler)
http.ListenAndServe(":8080", p.Serve())
}
性能优化
Pure在设计上注重性能:
- 使用高效的URL匹配算法
- 零内存分配的路由匹配
- 最小化的依赖
与标准库对比
相比标准库的http.ServeMux
,Pure提供了:
- 路由参数支持
- 更灵活的路由匹配
- 中间件支持
- 路由分组
- 更好的性能
完整示例
package main
import (
"encoding/json"
"net/http"
"github.com/go-playground/pure"
)
type User struct {
ID string `json:"id"`
Name string `json:"name"`
}
var users = map[string]User{
"1": {ID: "1", Name: "Alice"},
"2": {ID: "2", Name: "Bob"},
}
func main() {
p := pure.New()
// 全局中间件
p.Use(logger)
// API路由组
api := p.Group("/api")
api.Get("/users", listUsersHandler)
api.Get("/users/:id", getUserHandler)
api.Post("/users", createUserHandler)
// 静态文件服务
p.Get("/*", http.FileServer(http.Dir("./public")))
http.ListenAndServe(":8080", p.Serve())
}
func logger(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
println(r.Method, r.URL.Path)
next(w, r)
}
}
func listUsersHandler(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(users)
}
func getUserHandler(w http.ResponseWriter, r *http.Request) {
id := pure.RequestVars(r).URLParam("id")
if user, ok := users[id]; ok {
json.NewEncoder(w).Encode(user)
return
}
http.NotFound(w, r)
}
func createUserHandler(w http.ResponseWriter, r *http.Request) {
var user User
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
users[user.ID] = user
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(user)
}
Pure是一个非常适合中小型项目的轻量级路由器,它保持了简单性同时提供了必要的功能。如果你的项目需要更复杂的功能,可以考虑Gin或Echo等更全功能的框架。