go - 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 `
解决方案
正如mux.Router.Handle的文档所示,它需要一个http.Handler。这是一个只有一个方法的接口:ServeHTTP(ResponseWriter, *Request)
.
如果您想将对象作为处理程序传递,这很有用。
要注册函数myHandler
,请改用mux.Router.HandleFunc:
r.HandleFunc("/status", myHandler)
这也显示在mux 包的基本示例中。
推荐阅读
- python - 如何从熊猫列中的字符串中删除空格
- wpf - 如何在不使用按钮的情况下关闭打开的 PowerShell WPF 对话框
- swift - 如何使用 UIView 的平移手势更新 UIBezierpath 和 CAShapeLayer 路径?
- typescript - 通过以角度分组来自firestore的字段值来计数
- c++ - 如何重构以下课程
- php - WooCommerce - 在用户注册时将显示名称设置为名字
- javascript - React - 仅更新被点击元素的状态
- dart - 如何在构造函数中将常量值分配为默认值
- javascript - 使用reduce返回具有每个对象值总和的新对象数组
- json - React:在动态输入字段中动态添加输入字段