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

标签 go

现在我有这个:

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/

相关文章:

dictionary - 如何在 Go 中获取变量的内存大小?

go - golang 中映射的结构有多大?

go - Beego框架如何进行数据库迁移?

javascript - 将代码从 javascript 移植到 go 的问题

php - 将一段代码作为字符串存储在数据库中

html - 如何将文件从 html 选择器发送到 golang apis?

http - 使用golang终止来自IP层的http请求

go - go get 中的 `...` 是什么意思

mongodb - 使用Go驱动程序在MongoDB中运行命令

go - 如何列出指向golang struct所有字段的指针?