gpt4 book ai didi

go - 从 HandlerFunc 返回错误 - 需要一个新类型

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

现在我有这个:

type AppError struct{
Status int
Message string
}

func (h NearbyHandler) makeUpdate(v NearbyInjection) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {

item, ok := v.Nearby[params["id"]]

if !ok {
return AppError{
500, "Missing item in map.",
}
}

}
}

问题是如果我这样做:

func (h NearbyHandler) makeUpdate(v NearbyInjection) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) AppError { // <<< return AppError

}
}

不会编译 b/c http.HandlerFunc 不会返回返回 AppError 的函数。

我的另一个问题是,如果我使用 AppError 作为返回值,如何避免显式返回 nil

请注意,我收到此错误:

cannot use func literal (type func(http.ResponseWriter, *http.Request) AppError) as type http.HandlerFunc in return argument

最佳答案

因此,go 的设计者没有返回请求的状态,而是给了你 ResponseWriter .这是您与客户的主要互动。例如,要设置状态代码,请执行 WriteHeader(500)

关于go - 从 HandlerFunc 返回错误 - 需要一个新类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53025592/

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