我查看了 mux 的源代码,但我只想要一些简单的东西,而不是使用所有功能。
我想在 url 中获取 “id” 的值,如/url/{id},在 req.Form 中设置值并像 mux 一样清理路径。
像这样的代码
r:=http.NewServeMux()
r.HandlerFunc("/",func(w http.ResponseWriter,r *http.Request){
// Clean path to canonical form and redirect.
if p := cleanPath(req.URL.Path); p != req.URL.Path {
url := *req.URL
url.Path = p
p = url.String()
//根据HTTP的协议重定向
w.Header().Set("Location", p)
w.WriteHeader(http.StatusMovedPermanently)
return
}
// some code check the url parse id and set to req.form
})
//then add some specific url handlers.
在 go doc 中,它说长模式将比短模式具有更高的优先级。 我想在所有处理程序之前运行一些东西(解析 ID、清理路径等)。
我不想放弃 defaultmux 的功能。我应该重新定义一条全新的路线,还是使用 http.NewServeMux()?如果我使用 http.NewServerMux(),我应该如何在保持特性的同时添加一些东西?
最佳答案
我们使用了http://www.gorillatoolkit.org/pkg/mux在我们的生产堆栈中工作了一年多,对此非常满意。
对于我托管的一些非常简单的网站,我使用像这样的内置路由:
package main
import (
"flag"
"fmt"
"net/http"
"os"
)
const (
version = "0.1.0"
)
var (
port uint
)
func init() {
flag.UintVar(&port, "port", 8000, "the port to listen on")
flag.UintVar(&port, "p", 8000, "the port to listen on")
}
func main() {
flag.Parse()
// Retrieve the current working directory.
path, err := os.Getwd()
if err != nil {
panic(err)
}
http.HandleFunc("/gallery/view.aspx", handleGallery)
http.HandleFunc("/gallery/viewLarge.aspx", handleViewLarge)
http.HandleFunc("/ir.ashx", handleImageResize)
http.Handle("/", http.FileServer(http.Dir(path)))
panic(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}
让我知道您想要的路线是什么,我可以给您一个更具体的例子来说明您正在寻找什么。
关于http - 如何使用 golang 定义自定义 mux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21978883/