我是新手,正在学习在线教程。我从 VS Code 得到这个错误
“不能在 router.Get 的参数中使用 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 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
最佳答案
使用http.HandlerFunc :
router := muxinator.NewRouter()
router.Get("/read/{serviceName}", http.HandlerFunc(c.ReadConfig))
它需要一个 ServeHTTP 方法,但你给了它一个直接的函数。 http.HandlerFunc
充当包装器,因此您可以使用普通函数作为处理程序。
关于go - 运行 go 应用程序时出现 VS Code 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57684022/