dougan6982 2014-12-30 19:12
浏览 48
已采纳

在REST上不受支持的HTTP方法上返回什么响应代码?

I'm using Gorilla Mux to handle my HTTP routes for my REST API. I'm using the following binding for my API:

r := mux.NewRouter()
r.Host(baseUrl)

api := r.PathPrefix("/api").Subrouter()
api.HandleFunc("/users", APIUsers).Methods("GET", "POST")

http.Handle("/", r)
http.ListenAndServe(":8083", nil)

Then I do a CURL like this:

$ curl -i -X PUT http://127.0.0.1:8083/api/users

The Method APIUsers doesn't get called, as expected. I do get a 200 OK back tho:

HTTP/1.1 200 OK
Date: Tue, 30 Dec 2014 19:03:59 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8

Should I do this different with Gorilla to, let's say, bind all failing functions to a designated function? Also I wonder what's the typical HTTP code to return on non-supported functions. I'm a assuming a code in the 400 range, but I'm not sure which to use. I don't want it to be 200 tho, as the request was not "OK".

Any ideas and tips on this subject?

  • 写回答

2条回答 默认 最新

  • dpbrrczhlwbv849228 2014-12-30 22:41
    关注

    You can set a custom NotFoundHandler but that will apply to all unmatched routes.

    If you want a specific response returned you have to define the route explicitly.

    Example:

    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"))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)