也许这里已经有了解决我的问题的办法,但我哪儿也找不到。我试过一堆东西,但到目前为止都没有用。
我有这样的事情:
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
发布于 2022-04-16 19:34:30
一种解决方案是简单地处理处理程序中的查询参数:
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)
}根据大猩猩/mux文档,Queries方法意味着将处理程序与特定函数相匹配,类似于正则表达式。
https://stackoverflow.com/questions/71894537
复制相似问题