You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在fasthttp中获取与请求匹配的通用路由?

如何在fasthttp路由中获取通用路由模板路径

现有服务器代码

func requestHandler(ctx *fasthttp.RequestCtx) {
    id := ctx.UserValue("id").(string)
    name := ctx.UserValue("name").(string)

    response := fmt.Sprintf("Received ID: %s, Name: %s", id, name)
    ctx.SetBody([]byte(response))
}

func main() {
    r := router.New()

    r.GET("/rest/:id/:name", requestHandler)

    addr := ":9090"
    fmt.Printf("Starting server on %s\n", addr)
    if err := fasthttp.ListenAndServe(addr, r.Handler); err != nil {
        log.Fatalf("Error in ListenAndServe: %s", err)
    }
}

需求

当访问http://localhost:8080/rest/1/peter这类具体请求路径时,需要获取定义的通用路由模板/rest/:id/:name,类似go-restful框架中SelectedRoutePath()的功能。

解决方案

方法1:利用router的Find方法

将router实例设为全局可访问,在handler中通过Find方法匹配当前请求对应的路由条目,从而获取路由模板:

package main

import (
	"fmt"
	"log"

	"github.com/fasthttp/router"
	"github.com/valyala/fasthttp"
)

var r *router.Router

func requestHandler(ctx *fasthttp.RequestCtx) {
	id := ctx.UserValue("id").(string)
	name := ctx.UserValue("name").(string)

	// 获取通用路由模板
	var routeTemplate string
	route, _, _ := r.Find(ctx.Method(), ctx.Path())
	if route != nil {
		routeTemplate = route.Path
	}

	response := fmt.Sprintf("Received ID: %s, Name: %s\nRoute Template: %s", id, name, routeTemplate)
	ctx.SetBody([]byte(response))
}

func main() {
	r = router.New()

	r.GET("/rest/:id/:name", requestHandler)

	addr := ":9090"
	fmt.Printf("Starting server on %s\n", addr)
	if err := fasthttp.ListenAndServe(addr, r.Handler); err != nil {
		log.Fatalf("Error in ListenAndServe: %s", err)
	}
}

方法2:通过闭包传递路由模板

注册路由时,将模板路径通过闭包直接传递给handler,无需依赖全局router:

package main

import (
	"fmt"
	"log"

	"github.com/fasthttp/router"
	"github.com/valyala/fasthttp"
)

func main() {
	r := router.New()

	routeTemplate := "/rest/:id/:name"
	r.GET(routeTemplate, func(ctx *fasthttp.RequestCtx) {
		id := ctx.UserValue("id").(string)
		name := ctx.UserValue("name").(string)
		response := fmt.Sprintf("Received ID: %s, Name: %s\nRoute Template: %s", id, name, routeTemplate)
		ctx.SetBody([]byte(response))
	})

	addr := ":9090"
	fmt.Printf("Starting server on %s\n", addr)
	if err := fasthttp.ListenAndServe(addr, r.Handler); err != nil {
		log.Fatalf("Error in ListenAndServe: %s", err)
	}
}

两种方法都能实现需求,访问http://localhost:9090/rest/1/peter时,响应会包含对应的通用路由模板。

内容的提问来源于stack exchange,提问作者Pccc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 23:47:32