英文:
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>
(
还有以下内容:
curl http://localhost:8080/health-check?foo=bar
应该返回:Healthy bar
英文:
Probably there is already a solution here to my problem, but I couldn't find it anywhere. I tried a bunch of stuff, but nothing worked so far.
I have something like this:
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)
}
What I'm trying to achieve:
curl http://localhost:8080/health-check
Should respond with: Healthy <foo>
(<foo> -> the default value of foo)
And also the following:
curl http://localhost:8080/health-check?foo=bar
Should respond with: Healthy bar
答案1
得分: 0
一个解决方案是在处理程序中简单地处理查询参数:
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("健康 " + foo))
} else {
w.Write([]byte("健康 <foo>"))
}
w.WriteHeader(http.StatusOK)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/health-check", HealthCheckHandler)
http.ListenAndServe(":8080", r)
}
根据gorilla/mux文档,Queries
方法用于将处理程序与特定函数匹配,类似于正则表达式。
英文:
One solution if to simply handle the query params in your handler:
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)
}
according to the gorilla/mux documentation, the Queries
method is meant to match your handler to specific functions, akin to a regular expression.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论