如何在 Go gorilla/mux 中使用可选的查询参数?

How to use an optional query parameter in Go gorilla/mux?

可能这里已经有我的问题的解决方案,但我找不到任何地方。我尝试了很多东西,但到目前为止没有任何效果。

我有这样的东西:

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
)

func HealthCheck(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    fmt.Fprintln(w, "Healthy")
    // Also print the value of 'foo'
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/health-check", HealthCheck).Methods("GET").Queries("foo", "{foo}").Name("HealthCheck")
    r.HandleFunc("/health-check", HealthCheck).Methods("GET")
    http.ListenAndServe(":8080", r)
}

我想要达到的目标:

curl http://localhost:8080/health-check

应响应:Healthy <foo>(-> foo 的默认值)

还有以下内容:

curl http://localhost:8080/health-check?foo=bar

应回复:Healthy bar

一种解决方案,如果只是在处理程序中处理查询参数:

package main

import (
    "net/http"

    "github.com/gorilla/mux"
)

func HealthCheckHandler(w http.ResponseWriter, req *http.Request) {
    values := req.URL.Query()
    foo := values.Get("foo")

    if foo != "" {
        w.Write([]byte("Healthy " + foo))
    } else {
        w.Write([]byte("Healthy <foo>"))
    }
    w.WriteHeader(http.StatusOK)
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/health-check", HealthCheckHandler)
    http.ListenAndServe(":8080", r)
}

根据 gorilla/mux 文档,Queries 方法旨在将您的处理程序与特定函数相匹配,类似于正则表达式。