我是新手,正在关注在线教程。我从VS Code收到此错误
“不能在路由器的参数中使用c.ReadConfig(类型func(http.ResponseWriter,* http.Request))作为类型http.Handler。 func(http.ResponseWriter,* http.Request)没有实现http.Handler(缺少ServeHTTP方法)。
我检查了Get和Redconfig函数,它们看起来还不错。最后的老师没有收到错误,他可以很好地运行Go代码。这是主要的代码段
这是主要功能
func main() {
config := domain.Config{}
configService := service.ConfigService{
Config: &config,
Location: "config.yaml",
}
go configService.Watch(time.Second * 30)
c := controller.Controller{
Config: &config,
}
router := muxinator.NewRouter()
router.Get("/read/{serviceName}", c.ReadConfig)
log.Fatal(router.ListenAndServe(":8080"))
}
这是Get函数
// Get returns the config for a particular service
func (c *Config) Get(serviceName string) (map[string]interface{}, error) {
c.lock.RLock()
defer c.lock.RUnlock()
a, ok := c.config["base"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("base config is not a map")
}
// If no config is defined for the service
if _, ok = c.config[serviceName]; !ok {
// Return the base config
return a, nil
}
b, ok := c.config[serviceName].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("service %q config is not a map", serviceName)
}
// Merge the maps with the service config taking precedence
config := make(map[string]interface{})
for k, v := range a {
config[k] = v
}
for k, v := range b {
config[k] = v
}
return config, nil
}
这是ReadConfig
// ReadConfig writes the config for the given service to the ResponseWriter
func (c *Controller) ReadConfig(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
serviceName, ok := vars["serviceName"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "error")
}
config, err := c.Config.Get(serviceName)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error")
}
rsp, err := json.Marshal(&config)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error")
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(rsp))
}
应该发生的事情是我应该能够跑步并且可以去http://localhost:8080/read/base
答案 0 :(得分:1)
router := muxinator.NewRouter()
router.Get("/read/{serviceName}", http.HandlerFunc(c.ReadConfig))
期望使用ServeHTTP方法,但是您为它提供了直接功能。 http.HandlerFunc
充当包装器,因此您可以将普通函数用作处理程序。