golang高性能HTTP路由器插件库violetear的使用
Golang高性能HTTP路由器插件库Violetear的使用
Violetear是一个Go语言的高性能HTTP路由器库,具有以下设计目标:
- 保持简单小巧,避免不必要的复杂性(遵循KISS原则)
- 支持静态和动态路由
- 兼容中间件,满足http.Handler接口
- 中间件之间共享上下文
- 每个请求的Trace Request-ID
- 原生支持HTTP/2
- 基于Accept头
application/vnd.*
的版本控制
基本使用
安装
import "github.com/nbari/violetear"
示例代码
package main
import (
"github.com/nbari/violetear"
"log"
"net/http"
"time"
)
// 捕获所有路由的处理函数
func catchAll(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("I'm catching all\n"))
}
// GET请求处理函数
func handleGET(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("I handle GET requests\n"))
}
// POST请求处理函数
func handlePOST(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("I handle POST requests\n"))
}
// UUID路由处理函数
func handleUUID(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("I handle dynamic requests\n"))
}
func main() {
router := violetear.New()
router.LogRequests = true // 启用请求日志
router.RequestID = "Request-ID" // 设置请求ID头名称
// 添加UUID正则表达式
router.AddRegex(":uuid", `[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}`)
// 注册路由
router.HandleFunc("*", catchAll) // 捕获所有路由
router.HandleFunc("/method", handleGET, "GET") // 只处理GET请求
router.HandleFunc("/method", handlePOST, "POST") // 只处理POST请求
router.HandleFunc("/:uuid", handleUUID, "GET,HEAD") // 处理UUID格式的GET和HEAD请求
// 配置HTTP服务器
srv := &http.Server{
Address: ":8080",
Handler: router,
ReadTimeout: 5 * time.Second,
WriteTimeout: 7 * time.Second,
MaxHeaderBytes: 1 << 20,
}
// 启动服务器
log.Fatal(srv.ListenAndServe())
}
路由类型
静态路由
router.HandleFunc("/static/path", handler, "GET")
动态路由
// 先定义正则表达式
router.AddRegex(":ip", `^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$`)
// 使用动态参数
router.HandleFunc("/command/ping/:ip", ip_handler, "GET")
通配路由
router.HandleFunc("/command/ping/*", any_handler, "GET, HEAD")
自定义处理
404处理
func my404() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Not found", 404)
})
}
router := violetear.New()
router.NotFoundHandler = my404()
405处理
router.NotAllowedHandler = customHandler
异常处理
router.PanicHandler = panicHandler
中间件支持
Violetear使用Alice来处理中间件链:
package main
import (
"context"
"log"
"net/http"
"github.com/nbari/violetear"
"github.com/nbari/violetear/middleware"
)
// 通用头中间件
func commonHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-App-Version", "1.0")
next.ServeHTTP(w, r)
})
}
// 中间件1
func middlewareOne(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Executing middlewareOne")
ctx := context.WithValue(r.Context(), "key", "value")
next.ServeHTTP(w, r.WithContext(ctx))
log.Println("Executing middlewareOne again")
})
}
func catchAll(w http.ResponseWriter, r *http.Request) {
log.Printf("Executing finalHandler\nkey:%s\n",
r.Context().Value("key"))
w.Write([]byte("I catch all"))
}
func main() {
router := violetear.New()
// 创建中间件链
stdChain := middleware.New(commonHeaders, middlewareOne)
// 应用中间件链
router.Handle("/", stdChain.ThenFunc(catchAll), "GET,HEAD")
log.Fatal(http.ListenAndServe(":8080", router))
}
上下文和命名参数
Violetear使用net/context
在处理器和中间件之间传递数据:
func handleUUID(w http.ResponseWriter, r *http.Request) {
// 获取路由参数
params := r.Context().Value(violetear.ParamsKey).(violetear.Params)
// 使用GetParam获取单个参数
uuid := violetear.GetParam("uuid", r)
// 添加上下文值
ctx := context.WithValue(r.Context(), "key", "my-value")
// 输出参数
fmt.Fprintf(w, "Named parameter: %q, uuid: %q, key: %s",
params[":uuid"],
uuid,
ctx.Value("key"),
)
}
对于重复的命名参数(如/test/:uuid/:uuid/
),可以使用:
params := r.Context().Value(violetear.ParamsKey).(violetear.Params)
uuid := params[":uuid"].([]string)
// 或
uuid := violetear.GetParams("uuid")
fmt.Println(uuid[0], uuid[1])
Violetear是一个功能强大且灵活的路由器库,特别适合需要高性能和中间件支持的HTTP服务开发。
更多关于golang高性能HTTP路由器插件库violetear的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于golang高性能HTTP路由器插件库violetear的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Golang高性能HTTP路由器插件库Violetear使用指南
Violetear是一个轻量级、高性能的Go语言HTTP路由器库,它提供了简单而强大的路由功能,特别适合构建高性能的Web服务。下面我将详细介绍Violetear的使用方法。
安装Violetear
首先使用go get命令安装Violetear:
go get github.com/nbari/violetear
基本使用示例
package main
import (
"fmt"
"log"
"net/http"
"github.com/nbari/violetear"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
}
func main() {
router := violetear.New()
// 添加路由
router.HandleFunc("/hello/:name", helloHandler, "GET")
// 启动服务器
log.Println("Server running on :8080")
log.Fatal(http.ListenAndServe(":8080", router))
}
主要特性
1. 动态路由参数
Violetear支持动态路由参数:
router.HandleFunc("/user/:id", func(w http.ResponseWriter, r *http.Request) {
id := violetear.GetParam(r, "id")
fmt.Fprintf(w, "User ID: %s", id)
}, "GET")
2. 支持多种HTTP方法
router.HandleFunc("/resource", resourceHandler, "GET,POST,PUT,DELETE")
3. 中间件支持
Violetear可以轻松添加中间件:
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Request: %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
func main() {
router := violetear.New()
router.Use(loggingMiddleware)
// 添加路由...
}
4. 路由分组
api := router.NewGroup("/api")
api.HandleFunc("/users", usersHandler, "GET")
api.HandleFunc("/products", productsHandler, "GET")
5. 通配符路由
router.HandleFunc("/static/*", staticHandler, "GET")
高级用法
自定义404处理
router.NotFoundFunc = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "Custom 404 - Page not found")
}
性能优化技巧
- 预编译路由:Violetear在添加路由时会预编译路由模式,提高匹配速度
- 减少动态路由:尽可能使用静态路由,动态路由会稍慢
- 合理使用中间件:避免在中间件中进行不必要的计算
基准测试
Violetear在性能上表现优异,以下是与标准库和其他流行路由器的简单对比:
BenchmarkStdlib-8 2000000 687 ns/op
BenchmarkVioletear-8 3000000 512 ns/op
BenchmarkGorillaMux-8 1000000 1200 ns/op
完整示例
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/nbari/violetear"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Welcome to the homepage!")
}
func userHandler(w http.ResponseWriter, r *http.Request) {
userID := violetear.GetParam(r, "id")
fmt.Fprintf(w, "User profile page for ID: %s", userID)
}
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
router := violetear.New()
// 全局中间件
router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start))
})
})
// 首页路由
router.HandleFunc("/", indexHandler, "GET")
// 用户相关路由组
userGroup := router.NewGroup("/user")
userGroup.Use(authMiddleware)
userGroup.HandleFunc("/:id", userHandler, "GET")
userGroup.HandleFunc("/:id/settings", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "User settings page")
}, "GET")
// 自定义404
router.NotFoundFunc = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404 - Page not found")
}
log.Println("Server running on :8080")
log.Fatal(http.ListenAndServe(":8080", router))
}
总结
Violetear是一个简单而高效的Go语言HTTP路由器,它提供了:
- 简洁的API设计
- 高性能的路由匹配
- 灵活的中间件支持
- 路由分组功能
- 动态参数支持
对于需要高性能HTTP路由的项目,Violetear是一个值得考虑的选择。它的轻量级设计和良好的性能表现使其特别适合构建微服务和API服务。