2 回答
TA贡献1876条经验 获得超5个赞
您应该返回的状态代码是“405 MethodNotAllowed”或http.StatusMethodNowAllowed
in go。
来自维基百科:
使用资源不支持的请求方法对资源发出请求;例如,在需要通过 POST 呈现数据的表单上使用 GET,或在只读资源上使用 PUT。
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
TA贡献1818条经验 获得超8个赞
您可以设置自定义,NotFoundHandler但这将适用于所有不匹配的路由。
如果您想要返回特定的响应,则必须明确定义路由。
例子:
func main() {
r := mux.NewRouter().PathPrefix("/api").Subrouter()
// custom not found handler used for unmatched routes
var notFound NotFound
r.NotFoundHandler = notFound
r.HandleFunc("/users", APIUsers).Methods("GET", "POST")
// return 405 for PUT, PATCH and DELETE
r.HandleFunc("/users", status(405, "GET", "POST")).Methods("PUT", "PATCH", "DELETE")
http.Handle("/", r)
http.ListenAndServe(":8083", nil)
}
type NotFound func(w http.ResponseWriter, req *http.Request)
func (NotFound) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(404)
w.Write([]byte(`{"message": "Not Found"}`))
}
// status is used to set a specific status code
func status(code int, allow ...string) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(code)
if len(allow) > 0 {
w.Write([]byte(`Allow: ` + strings.Join(allow, ", ")))
}
}
}
func APIUsers(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("hello"))
}
- 2 回答
- 0 关注
- 150 浏览
添加回答
举报