Go chi 渲染器难以处理绑定列表

到这里。试图让 chi 渲染器返回一个Order结构实例列表并得到一个我不明白的编译器错误:


package myapp


import (

    "net/http"

    "github.com/go-chi/render"

)


type Order struct {

    OrderId    string

  Status     string

}


func (*Order) Bind(r *http.Request) error {

    return nil

}


func GetAllOrderByCustomerId(dbClient DbClient, customerId string) http.HandlerFunc {

  return func(w http.ResponseWriter, r *http.Request) {


    // fetch all customer orders from the DB

    orders,err := dbClient.FetchAllOrdersByCustomerId(customerId)

    if err != nil {

      log.Error("unable to fetch orders for customer", err)

      render.Render(w, r, NewInternalServerError(err))

      return

    }


    render.Bind(r, &orders)

    return


  }

}

当我去编译这段代码时,我得到:


fizz/buzz/myapp/order_fetcher.go:136:20: cannot use &orders (type *[]Order) as type render.Binder in argument to render.Bind:

    *[]Order does not implement render.Binder (missing Bind method)

因此,即使我定义了Bindfor Order,它似乎也不会自动将其Bind应用于Orders.


谁能看到我错过了什么?一些端点只会返回一个Order,而其他端点(比如这个)需要能够返回一个集合/列表Orders。


浮云间
浏览 117回答 1
1回答

一只萌萌小番薯

与存储库中的示例一样chi,您必须创建一个辅助方法来呈现某些东西的列表,在您的情况下是订单列表。首先,您必须实现该render.Renderer方法,然后创建一个辅助方法来构建render.Renderer.我已从此处的示例中修改了您的代码:type Order struct {    OrderId string    Status  string}// Render implement render.Rendererfunc (*Order) Render(w http.ResponseWriter, r *http.Request) error {    // do something    return nil}// newOrderList is a helper method to make list of render.Rendererfunc newOrderList(orders []*Order) []render.Renderer {    list := []render.Renderer{}    for _, order := range orders {        list = append(list, order)    }    return list}func GetAllOrderByCustomerId(dbClient DbClient, customerId string) http.HandlerFunc {    return func(w http.ResponseWriter, r *http.Request) {        // fetch all customer orders from the DB        orders, err := dbClient.FetchAllOrdersByCustomerId(customerId)        if err != nil {            log.Error("unable to fetch orders for customer", err)            render.Render(w, r, NewInternalServerError(err))            return        }        // render list of orders        render.RenderList(w, r, newOrderList(orders))        return    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go