首页 > 解决方案 > r.Handle 参数中的 http.Handler 值:缺少方法 ServeHTTP 错误

问题描述

我试图在 Go 中使用 gorilla mux 构建基本的 Web API。这是我的代码。请帮助我了解一些接口是如何在这里工作的。

func main() {
    r := mux.NewRouter()

    r.Handle("/", http.FileServer(http.Dir("./views/")))
    r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))

    r.Handle("/status", myHandler).Methods("GET")

    http.ListenAndServe(":8080", r)

}

func myHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)

} ```


error :- `cannot use myHandler (value of type func(w http.ResponseWriter, r *http.Request)) as http.Handler value in argument to r.Handle: missing method ServeHTTP `

标签: goservergorillamux

解决方案


正如mux.Router.Handle的文档所示,它需要一个http.Handler。这是一个只有一个方法的接口:ServeHTTP(ResponseWriter, *Request).

如果您想将对象作为处理程序传递,这很有用。

要注册函数myHandler,请改用mux.Router.HandleFunc

r.HandleFunc("/status", myHandler)

这也显示在mux 包的基本示例中。


推荐阅读