gpt4 book ai didi

go - r.Handle : missing method ServeHTTP error 参数中的 http.Handler 值

转载 作者:行者123 更新时间:2023-12-01 22:40:02 25 4
gpt4 key购买 nike

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

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 `

最佳答案

作为docs for mux.Router.Handle显示,它需要一个 http.Handler .这是一个单一方法的接口(interface):ServeHTTP(ResponseWriter, *Request) .
如果您想将对象作为处理程序传递,这很有用。
注册函数myHandler , 使用 mux.Router.HandleFunc反而:

r.HandleFunc("/status", myHandler)
这也显示在基本 examples多路复用器包。

关于go - r.Handle : missing method ServeHTTP error 参数中的 http.Handler 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63361891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com