gpt4 book ai didi

go - 为什么我的 Go 代码不运行?

转载 作者:数据小太阳 更新时间:2023-10-29 03:38:19 24 4
gpt4 key购买 nike

package main

import (
"fmt"
"github.com/ant0ine/go-json-rest"
"net/http"
)

type App struct {
Id string
Name string
}

func GetApp(w *rest.ResponseWriter, req *rest.Request) {
user := App{
Id: req.PathParam("id"),
Name: "Antoine",
}
w.WriteJson(&user)
}

type MyResourceHandler struct {
rest.ResourceHandler
}

type ResourceController interface {
Show(w *rest.ResponseWriter, req *rest.Request)
Create(w *rest.ResponseWriter, req *rest.Request)
Update(w *rest.ResponseWriter, req *rest.Request)
Delete(w *rest.ResponseWriter, req *rest.Request)
}

func (self *MyResourceHandler) AddResource(name string, c ResourceController) error {
show_func := func(w *rest.ResponseWriter, r *rest.Request) {
c.Show(w, r)
}
create_func := func(w *rest.ResponseWriter, r *rest.Request) {
c.Create(w, r)
}
update_func := func(w *rest.ResponseWriter, r *rest.Request) {
c.Update(w, r)
}
delete_func := func(w *rest.ResponseWriter, r *rest.Request) {
c.Delete(w, r)
}

err := self.ResourceHandler.SetRoutes(
rest.Route{"GET", fmt.Sprintf("/%s/:id", name), show_func},
rest.Route{"POST", fmt.Sprintf("/%s", name), create_func},
rest.Route{"PUT", fmt.Sprintf("/%s/:id", name), update_func},
rest.Route{"DELETE", fmt.Sprintf("/%s/:id", name), delete_func},
)
return err
}

type AppController struct{}

func (self *AppController) Show(w *rest.ResponseWriter, r *rest.Request) {
app := App{
Id: r.PathParam("id"),
Name: "Antoine",
}
w.WriteJson(&app)
}

func (self *AppController) Create(w *rest.ResponseWriter, r *rest.Request) {
app := App{
Id: r.PathParam("id"),
Name: "Antoine",
}
w.WriteJson(&app)
}

func (self *AppController) Update(w *rest.ResponseWriter, r *rest.Request) {
app := App{
Id: r.PathParam("id"),
Name: "Antoine",
}
w.WriteJson(&app)
}

func (self *AppController) Delete(w *rest.ResponseWriter, r *rest.Request) {
app := App{
Id: r.PathParam("id"),
Name: "Antoine",
}
w.WriteJson(&app)
}

func main() {
handler := MyResourceHandler{}
controler := AppController{}
handler.AddResource("app", controler)
http.ListenAndServe(":9008", &handler)
}

我已经实现了接口(interface) ResourceController 的所有四种方法,但它告诉我:

./fakeapi.go:93: cannot use controler (type AppController) as type ResourceController in function argument:
AppController does not implement ResourceController (Create method requires pointer receiver)

最佳答案

它在错误消息中:(Create method requires pointer receiver)

您已在 *AppController 上定义了创建(指向 AppController 的指针),但您正在尝试使用 AppController , 不满足接口(interface)。

您可能想要的解决方案是更改 controler := AppController{}controler := &AppController{}

关于go - 为什么我的 Go 代码不运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15680370/

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