Golang中URL路径路由选择:Gorilla Mux还是Httprouter?

Golang中URL路径路由选择:Gorilla Mux还是Httprouter? 我正在使用内置的 net/http 路由器。如果 URL 是

https://localhost:9999/product/10

我使用了

strings.Trim(r.URL.Path, "/") 来获取路径 productr.URL.Query().Get("id") 来获取值 10

但我发现无法使用 Gorilla Mux 或 julienschmidt 的 httprouter 来获取相应的路径。

如何使用其他路由器来获取路径?

9 回复

luk4z7:

vars := mux.Vars® id := vars[“id”]

我在理解这个代码的上下文时遇到了一些困难。我应该如何使用它?是 Gorilla 吗?

更多关于Golang中URL路径路由选择:Gorilla Mux还是Httprouter?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


路由:/v1/product/{id:[0-9]+}

func Get(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  vars := mux.Vars(r)
  id := vars["id"]
}

如果您想处理静态文件,仓库中有一个相关的示例,地址如下: https://github.com/gorilla/mux#static-files

要为您的“处理程序”设置方法,请在最后添加 Methods("POST") https://github.com/gorilla/mux#walking-routes

请查看示例。

在你的控制器或中间件中导入 github.com/gorilla/mux,当你接收到 r *http.Request 时,以同样的方式使用它。

类似这样:

import (
  "github.com/gorilla/mux"
)

func Get(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  vars := mux.Vars(r)
  id := vars["id"]
}
// 路由由路径和处理函数组成。r.HandleFunc("/product/{id:[0-9]+}", YourHandler)
  1. 如果路径是动态的(Url.Path)怎么办?例如使用 /{path}/ 而不是 /product/
  2. 如何处理 GET、PUT、DELETE 和 UPDATE?(REST API)

我的主要问题是关于避免使用静态路径。我有超过 600 个端点,静态端点(路径)可能难以管理。

GitHub - gorilla/mux: 一个强大的HTTP路由器和URL匹配器,用于构建Go...

一个强大的HTTP路由器和URL匹配器,用于构建Go Web服务器 🦍 - GitHub - gorilla/mux: 一个强大的HTTP路由器和URL匹配器,用于构建Go Web服务器 🦍

是一样的,你把 mux.Vars 放到你的方法/函数里。

package main

import (
	"fmt"
	"github.com/gorilla/mux"
	"log"
	"net/http"
)

func YourHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["id"]

	fmt.Println(id)

	w.Write([]byte("Gorilla!\n"))
}

func main() {
	r := mux.NewRouter()
	// Routes consist of a path and a handler function.
	r.HandleFunc("/product/{id:[0-9]+}", YourHandler)

	// Bind to a port and pass our router in
	log.Fatal(http.ListenAndServe(":8000", r))
}

试试这个例子,和上面的一样。 https://github.com/gorilla/mux#full-example

并以相同的方式使用它

我寻找的上下文是这样的:

func main() {
	r := mux.NewRouter()
    path := mux.Vars(r)
    val := vars["id"]

	r.HandleFunc("/{path}/{val}",{path}).Methods(http.MethodPost)
	r.HandleFunc("/{path}/{val}",{path}).Methods(http.MethodGet)
	r.HandleFunc("/{path}/{val}",{path}).Methods(http.MethodPut)
	r.HandleFunc("/{path}/{val}",{path}).Methods(http.MethodDelete)
	r.HandleFunc("/", notFound)
	log.Fatal(http.ListenAndServe(":9999", nil))
}

我希望路径能更加动态。我在我的测试网站上使用 net/http The Web Server 来实现这一点,效果很好。

我的目标是用 Gorilla Mux 或 httprouter 来替代 net/http。这有可能实现吗?

在Golang中,Gorilla Mux和Httprouter都提供了更强大的路由功能。以下是两种路由器的具体实现示例:

1. Gorilla Mux 实现

package main

import (
    "fmt"
    "net/http"
    "github.com/gorilla/mux"
)

func ProductHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]
    
    fmt.Fprintf(w, "产品ID: %s", id)
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/product/{id}", ProductHandler)
    
    http.ListenAndServe(":9999", r)
}

2. Httprouter 实现

package main

import (
    "fmt"
    "net/http"
    "github.com/julienschmidt/httprouter"
)

func ProductHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    id := ps.ByName("id")
    
    fmt.Fprintf(w, "产品ID: %s", id)
}

func main() {
    router := httprouter.New()
    router.GET("/product/:id", ProductHandler)
    
    http.ListenAndServe(":9999", router)
}

3. 获取完整路径参数(多个参数)

// Gorilla Mux 多参数示例
func ProductDetailHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    category := vars["category"]
    id := vars["id"]
    
    fmt.Fprintf(w, "分类: %s, ID: %s", category, id)
}

// 路由注册
r.HandleFunc("/{category}/product/{id}", ProductDetailHandler)

// Httprouter 多参数示例
func ProductDetailHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    category := ps.ByName("category")
    id := ps.ByName("id")
    
    fmt.Fprintf(w, "分类: %s, ID: %s", category, id)
}

// 路由注册
router.GET("/:category/product/:id", ProductDetailHandler)

4. 查询参数处理

// Gorilla Mux 查询参数
func ProductHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]
    
    // 获取查询参数
    page := r.URL.Query().Get("page")
    limit := r.URL.Query().Get("limit")
    
    fmt.Fprintf(w, "ID: %s, Page: %s, Limit: %s", id, page, limit)
}

// Httprouter 查询参数
func ProductHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    id := ps.ByName("id")
    
    // 获取查询参数
    page := r.URL.Query().Get("page")
    limit := r.URL.Query().Get("limit")
    
    fmt.Fprintf(w, "ID: %s, Page: %s, Limit: %s", id, page, limit)
}

5. 正则表达式约束

// Gorilla Mux 正则约束
r := mux.NewRouter()
r.HandleFunc("/product/{id:[0-9]+}", ProductHandler) // 只匹配数字ID

// Httprouter 正则约束
router := httprouter.New()
router.GET("/product/:id(\\d+)", ProductHandler) // 只匹配数字ID

这两种路由器都比内置的 net/http 提供了更清晰的路径参数提取方式,无需手动解析URL路径。Gorilla Mux功能更丰富,Httprouter性能更高。

回到顶部