gpt4 book ai didi

Go chi 渲染难以处理绑定(bind)列表

转载 作者:行者123 更新时间:2023-12-01 22:12:50 25 4
gpt4 key购买 nike

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

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)
所以即使我定义了 Bind对于 Order ,它似乎不会自动应用 BindOrders 的集合/列表.
谁能看到我错过了什么?一些端点只会返回一个 Order ,而其他人(比如这个)需要能够返回 Orders 的集合/列表.

最佳答案

chi 中的示例存储库,您必须为 创建一个辅助方法渲染列表 ,在你的情况下,订单列表。
首先,你必须实现 render.Renderer方法然后创建一个辅助方法来构建 render.Renderer 的列表.
我已经从示例 here 中修改了您的代码:

type Order struct {
OrderId string
Status string
}

// Render implement render.Renderer
func (*Order) Render(w http.ResponseWriter, r *http.Request) error {
// do something
return nil
}

// newOrderList is a helper method to make list of render.Renderer
func 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

}
}

关于Go chi 渲染难以处理绑定(bind)列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62513646/

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