如何解决带有针对坏端点和不允许方法的自定义错误处理程序的 API
我正在研究 Go GorillaMux API,但遇到了一个我无法弄清楚的问题。我想使用自定义错误消息在我的整个 API 中禁用 HTTP 方法,并为未定义的端点提供不同的自定义错误消息。我似乎无法让它们一起正常工作。我已经尝试过 SubRouters 和 Middleware,但它们似乎都不适合我。这是我的带有子路由器的代码。
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
)
type RestResponseHome struct {
Code int `json:"-"`
Action string `json:"action"`
Method string `json:"method,omitempty"`
Message string `json:"message,omitempty"`
}
type RestResponseError struct {
Code int `json:"-"`
Action string `json:"action"`
Method string `json:"method,omitempty"`
Errors []RestError `json:"errors,omitempty"`
Message string `json:"message,omitempty"`
}
type RestError struct {
Status string `json:"status,omitempty"`
Title string `json:"title,omitempty"`
Detail string `json:"detail,omitempty"`
}
func homePage(w http.ResponseWriter,r *http.Request) {
fmt.Println("Start homePage()")
var resp = RestResponseHome{
Code: 200,Action: "/",Method: r.Method,Message: "Hello,World!",}
w.Header().Set("Content-Type","application/json; charset=utf-8")
w.WriteHeader(resp.Code)
body,_ := json.Marshal(resp)
w.Write(body)
fmt.Println("End homePage()")
}
func badMethod(w http.ResponseWriter,r *http.Request) {
fmt.Println("Start badMethod()")
var resp = RestResponseError{
Code: 405,Action: r.URL.Path,Method: r.Method,Errors: []RestError{{
Title: fmt.Sprintf("Bad Method - %s",r.URL),Status: "405",Detail: "DELETE method is not supported on this api.",}},Message: "DELETE method is not supported on this api.",_ := json.Marshal(resp)
w.Write(body)
fmt.Println("End badMethod()")
}
func badEndpoint(w http.ResponseWriter,r *http.Request) {
fmt.Println("Start badEndpoint()")
var resp = RestResponseError{
Code: 404,Errors: []RestError{{
Title: fmt.Sprintf("Bad Endpoint - %s",Status: "404",Detail: "Endpoint is not supported",Message: "Endpoint is not supported",_ := json.Marshal(resp)
w.Write(body)
fmt.Println("End badEndpoint()")
}
func main() {
fmt.Println("Start main()")
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/",homePage).Methods("GET")
subRouter := myRouter.Methods("DELETE").Subrouter()
// Default Routers for unhandled endpoints/Methods
myRouter.NotFoundHandler = http.HandlerFunc(badEndpoint)
subRouter.NotFoundHandler = http.HandlerFunc(badMethod)
http.ListenAndServe(":10000",myRouter)
fmt.Println("End main()")
}
当我运行它并使用 GET 命中 / 端点时,它可以正常工作。当我遇到一个不存在的端点时,我的 badEndpoint()
函数不会运行。当我使用 DELETE 方法(存在或不存在)命中任何端点时,我的 badMethod()
函数不会运行。
在本示例中,我的预期行为是 badMethod()
函数将针对任何 DELETE 运行,而 badEndpoint()
函数将针对除 /
之外的任何端点上的任何其他方法运行.
如果我省略 badMethod()
的 SubRouter 逻辑,badEndpoint()
似乎可以正常工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。