golang轻量级路由和中间件处理插件库gocraft/web的使用

Golang轻量级路由和中间件处理插件库gocraft/web的使用

gocraft/web是一个Go语言的mux和中间件包。它通过类型转换和反射让你的代码保持静态类型,同时性能优异。

快速开始

首先安装gocraft/web:

go get github.com/gocraft/web

然后创建一个示例文件server.go

package main

import (
	"github.com/gocraft/web"
	"fmt"
	"net/http"
	"strings"
)

type Context struct {
	HelloCount int
}

// 中间件示例 - 设置HelloCount
func (c *Context) SetHelloCount(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	c.HelloCount = 3
	next(rw, req)
}

// 路由处理程序示例
func (c *Context) SayHello(rw web.ResponseWriter, req *web.Request) {
	fmt.Fprint(rw, strings.Repeat("Hello ", c.HelloCount), "World!")
}

func main() {
	router := web.New(Context{}).                   // 创建路由器
		Middleware(web.LoggerMiddleware).           // 使用内置中间件
		Middleware(web.ShowErrorsMiddleware).       // 错误显示中间件
		Middleware((*Context).SetHelloCount).       // 自定义中间件
		Get("/", (*Context).SayHello)               // 添加路由
	http.ListenAndServe("localhost:3000", router)   // 启动服务器
}

运行服务器:

go run src/myapp/server.go

服务器将在localhost:3000上运行。

主要特性

  • 高性能:每个请求仅增加3-9μs延迟,路由性能为O(log(N))
  • 自定义上下文:通过强静态类型在中间件和处理程序间传递信息
  • 强大路由:捕获路径变量、用正则验证路径段
  • 中间件支持:可以表达几乎任何web层功能
  • 嵌套路由器和上下文:自然表达应用层次结构
  • 兼容net/http:直接使用http.ListenAndServe()
  • 轻量级:核心轻量,可通过内置或自定义中间件扩展功能

完整示例

package main

import (
	"github.com/gocraft/web"
	"net/http"
	"fmt"
)

// 基础上下文
type Context struct {
	UserID string
}

// API上下文
type ApiContext struct {
	*Context
	AccessToken string
}

func (c *Context) AuthMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	// 模拟认证逻辑
	c.UserID = "user123"
	next(rw, req)
}

func (c *ApiContext) ApiAuthMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	// API认证
	c.AccessToken = "token123"
	next(rw, req)
}

func (c *Context) Home(rw web.ResponseWriter, req *web.Request) {
	fmt.Fprintf(rw, "Welcome, %s!", c.UserID)
}

func (c *ApiContext) ApiHandler(rw web.ResponseWriter, req *web.Request) {
	fmt.Fprintf(rw, "API Access with token: %s", c.AccessToken)
}

func main() {
	// 基础路由器
	rootRouter := web.New(Context{})
	rootRouter.Middleware((*Context).AuthMiddleware)
	rootRouter.Get("/", (*Context).Home)

	// API子路由器
	apiRouter := rootRouter.Subrouter(ApiContext{}, "/api")
	apiRouter.Middleware((*ApiContext).ApiAuthMiddleware)
	apiRouter.Get("/data", (*ApiContext).ApiHandler)

	http.ListenAndServe("localhost:3000", rootRouter)
}

中间件示例

中间件是gocraft/web的强大功能:

func (c *Context) AdminRequired(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	if c.UserID == "admin" {
		next(rw, req)
	} else {
		rw.WriteHeader(http.StatusUnauthorized)
		fmt.Fprint(rw, "Admin access required")
	}
}

路径参数

捕获路径参数:

router.Get("/users/:id", (*Context).UserHandler)

func (c *Context) UserHandler(rw web.ResponseWriter, req *web.Request) {
	userID := req.PathParams["id"]
	fmt.Fprintf(rw, "User ID: %s", userID)
}

内置中间件

gocraft/web包含几个有用的内置中间件:

router := web.New(Context{})
router.Middleware(web.LoggerMiddleware)  // 请求日志
router.Middleware(web.ShowErrorsMiddleware)  // 开发环境错误展示

// 静态文件服务
router.Middleware(web.StaticMiddleware("public", web.StaticOption{IndexFile: "index.html"}))

gocraft/web提供了强大而灵活的路由和中间件功能,同时保持了Go语言的简洁性和高性能。通过自定义上下文和嵌套路由器,你可以构建复杂的web应用架构。


更多关于golang轻量级路由和中间件处理插件库gocraft/web的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang轻量级路由和中间件处理插件库gocraft/web的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


GoCraft/web: 轻量级Golang路由和中间件处理库

GoCraft/web是一个轻量级但功能强大的Golang路由和中间件处理库,它提供了简洁的API和灵活的中间件机制,非常适合构建RESTful API服务。

主要特性

  • 简单易用的路由定义
  • 强大的中间件支持
  • 上下文(Context)传递机制
  • 轻量级,无外部依赖
  • 良好的性能表现

安装

go get github.com/gocraft/web

基本使用示例

package main

import (
	"fmt"
	"net/http"
	"github.com/gocraft/web"
)

type Context struct {
	HelloCount int
}

func (c *Context) SetHelloCount(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	c.HelloCount = 7
	next(rw, req)
}

func (c *Context) SayHello(rw web.ResponseWriter, req *web.Request) {
	fmt.Fprint(rw, "Hello ", c.HelloCount, " times!")
}

func main() {
	router := web.New(Context{}) // 创建带有自定义上下文的router
	
	// 添加中间件
	router.Middleware((*Context).SetHelloCount)
	
	// 添加路由
	router.Get("/", (*Context).SayHello)
	
	// 启动服务器
	http.ListenAndServe("localhost:3000", router)
}

路由定义

GoCraft/web支持常见的HTTP方法路由:

router.Get("/path", (*Context).HandlerFunc)      // GET请求
router.Post("/path", (*Context).HandlerFunc)     // POST请求
router.Put("/path", (*Context).HandlerFunc)      // PUT请求
router.Delete("/path", (*Context).HandlerFunc)   // DELETE请求
router.Patch("/path", (*Context).HandlerFunc)    // PATCH请求
router.Options("/path", (*Context).HandlerFunc)  // OPTIONS请求
router.Head("/path", (*Context).HandlerFunc)     // HEAD请求

路径参数

func (c *Context) UserHandler(rw web.ResponseWriter, req *web.Request) {
	// 获取路径参数
	userId := req.PathParams["id"]
	fmt.Fprintf(rw, "User ID: %s", userId)
}

func main() {
	router := web.New(Context{})
	router.Get("/users/:id", (*Context).UserHandler)
	http.ListenAndServe("localhost:3000", router)
}

中间件

中间件是GoCraft/web的强大功能之一,可以用于认证、日志记录、错误处理等:

func (c *Context) AuthMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	token := req.Header.Get("X-Auth-Token")
	if token != "secret" {
		rw.WriteHeader(http.StatusUnauthorized)
		fmt.Fprint(rw, "Unauthorized")
		return
	}
	next(rw, req)
}

func (c *Context) LoggingMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	start := time.Now()
	next(rw, req)
	duration := time.Since(start)
	log.Printf("%s %s took %v", req.Method, req.URL.Path, duration)
}

func main() {
	router := web.New(Context{})
	
	// 全局中间件
	router.Middleware((*Context).LoggingMiddleware)
	
	// 特定路由组的中间件
	apiRouter := router.Subrouter(Context{}, "/api")
	apiRouter.Middleware((*Context).AuthMiddleware)
	apiRouter.Get("/data", (*Context).GetData)
	
	http.ListenAndServe("localhost:3000", router)
}

子路由

可以创建嵌套的路由结构:

func main() {
	router := web.New(Context{})
	
	// API v1 路由组
	apiV1 := router.Subrouter(Context{}, "/api/v1")
	apiV1.Get("/users", (*Context).ListUsers)
	apiV1.Post("/users", (*Context).CreateUser)
	apiV1.Get("/users/:id", (*Context).GetUser)
	
	// API v2 路由组
	apiV2 := router.Subrouter(Context{}, "/api/v2")
	apiV2.Middleware((*Context).V2Middleware)
	apiV2.Get("/users", (*Context).ListUsersV2)
	
	http.ListenAndServe("localhost:3000", router)
}

错误处理

func (c *Context) ErrorHandler(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	defer func() {
		if err := recover(); err != nil {
			rw.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintf(rw, "Error: %v", err)
		}
	}()
	next(rw, req)
}

func (c *Context) DangerousHandler(rw web.ResponseWriter, req *web.Request) {
	panic("something went wrong!")
}

func main() {
	router := web.New(Context{})
	router.Middleware((*Context).ErrorHandler)
	router.Get("/danger", (*Context).DangerousHandler)
	http.ListenAndServe("localhost:3000", router)
}

静态文件服务

func main() {
	router := web.New(Context{})
	
	// 静态文件服务
	router.Get("/*", web.StaticMiddleware("public", web.StaticOption{IndexFile: "index.html"}))
	
	http.ListenAndServe("localhost:3000", router)
}

性能考虑

GoCraft/web在设计上考虑了性能因素:

  1. 使用高效的路由匹配算法
  2. 中间件链在启动时构建,运行时无额外开销
  3. 轻量级上下文传递机制

与其他库的比较

  • net/http标准库提供更多功能但保持简洁
  • 比Gin更轻量,但功能稍少
  • 比Echo更专注于核心路由和中间件功能
  • 比Beego更轻量,无ORM等额外组件

总结

GoCraft/web是一个优秀的轻量级路由和中间件库,特别适合需要简洁API和灵活中间件机制的项目。它的学习曲线平缓,性能良好,是构建中小型RESTful服务的理想选择。

对于更复杂的项目需求,可以考虑功能更全面的框架如Gin或Echo,但如果你追求简洁和轻量,GoCraft/web是一个值得考虑的选择。

回到顶部