mux 在 url 中有空参数

mux is having empty parameters in the url

我有这个主要的:

func main() {
    r := _routerprovider.GetRouter()
    srv := &http.Server{
        Handler:      r,
        Addr:         "127.0.0.1:8000",
        WriteTimeout: 60 * time.Second,
        ReadTimeout:  15 * time.Second,
    }
    fmt.Println("Running in port 8000!")
    err := srv.ListenAndServe()
    if err != nil {
        log.Fatalln(err.Error())
    }
}

这是路由器:

func (h HandlerProvider) GetRouter() *mux.Router {
    r := mux.NewRouter()
    r.HandleFunc("/health", Health).Methods("GET")
    r.HandleFunc("/users", GetUsers).Methods("GET")
    r.HandleFunc("/users", CreateUser).Methods("POST")
    r.HandleFunc("/people", GetPeople).Methods("GET")
    r.HandleFunc("/peoplebyid", GetPeopleByID).Methods("GET")
    return r
}

无论我做什么,mux.Vars 总是returns 一张空地图。我究竟做错了什么? 这是一个示例处理程序:

func GetPeopleByID(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    id, ok := params["id"]
    if !ok {
        ErrorHandler(w, r, fmt.Errorf("Error!"), 400)
        return
    }
    idasnumber, err := strconv.Atoi(id)
    if err != nil {
        ErrorHandler(w, r, fmt.Errorf("Error!"), 400)
        return
    }
    value, ok := services.PeopleDict[idasnumber]

    bs, _ := json.MarshalIndent(value, "", "  ")
    w.Write(bs)
}

mux.Vars() 仅在路由匹配时填充(因此 Gorilla mux 知道在哪里寻找它们)。通过在路由中预期变量值的位置使用 {name}{name:pattern} 占位符来完成路由中的匹配。

因此对于以下路线:

r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)

您可以将变量键 categoryid 设置为各自的值:

vars := mux.Vars(r)
fmt.Fprintf(w, "Category: %v\n", vars["category"])
fmt.Fprintf(w, "Id: %v\n", vars["id"])

在您的代码中,您可以通过这种方式修复 /peoplebyid(取决于 id 是什么)以使您的 GetPeopleById() 处理程序工作:

func (h HandlerProvider) GetRouter() *mux.Router {
// ...
r.HandleFunc("/people/{id:[0-9]+}", GetPeopleByID).Methods("GET")
// ...
}

在此处查看有关如何使用变量的 Gorilla Mux 文档:https://github.com/gorilla/mux#examples,特别是开头部分:

Paths can have variables. They are defined using the format {name} or {name:pattern}. If a regular expression pattern is not defined, the matched variable will be anything until the next slash.