[英]how to define custom mux with golang
我查看了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))
}
讓我知道你想要的路線是什么,我可以給你一個更具體的例子來說明你想要的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.