登录
首页 >  Golang >  Go问答

修改 http.ResponseWriter 作为函数参数传递的方法修改

来源:stackoverflow

时间:2024-02-11 16:12:23 421浏览 收藏

哈喽!今天心血来潮给大家带来了《修改 http.ResponseWriter 作为函数参数传递的方法修改》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我有一个处理应用程序身份验证的身份验证中间件,需要检查几种情况,每次检查在出现错误时都有相同的逻辑:

res, err := dosomecheck()
if err != nil {
    log.println("authentication failed: %v", err)
    json.newencoder(w).encode(struct {error string}{error: "something is broke!"})
    w.header().set("content-type", "application/json")
    w.writeheader(http.statusforbidden)
    return
}

我想用这样的函数编写一次这个逻辑(每种情况之间的唯一区别是错误和客户端消息):

func authError(w http.ResponseWriter, err error, clientMsg string) {
    log.Println("Authentication failed: %v", err)
    json.NewEncoder(w).Encode(struct {
        Error string
    }{Error: clientMsg})
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusForbidden)
    return
}

但是 w 不是一个指针(我没有将它作为指向中间件处理程序的指针),所以我无法从函数中更改它,autherror() 不会更改实际响应。 我怎样才能优雅地完成这项工作?


正确答案


w 不是一个指针,但它是一个接口类型,并且它在底层包装了一个指针。所以你可以按原样传递它,当你调用它的方法时,它会反映在调用者处。

只是不要忘记,如果之前向响应写入了任何内容,则无法(再次)写入标头。同样,如果您的 autherror() 向输出写入了某些内容,则调用者无法收回该内容。如果 autherror() 生成响应,则调用者应在这种情况下返回。

还要注意,必须先设置 headers,然后调用 responsewriter.writeheader(),然后才能编写响应正文。

如果您调用 responsewriter.write(),如果尚未写入响应状态,则会写入响应状态(假设 http 200 ok)。

引自ResponseWriter.Write()

// if writeheader has not yet been called, write calls
// writeheader(http.statusok) before writing the data. if the header
// does not contain a content-type line, write adds a content-type set
// to the result of passing the initial 512 bytes of written data to
// detectcontenttype. additionally, if the total size of all written
// data is under a few kb and there are no flush calls, the
// content-length header is added automatically.
write([]byte) (int, error)

所以你的 autherror() 应该是这样的:

func authError(w http.ResponseWriter, err error, clientMsg string) {
    log.Println("Authentication failed: %v", err)
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusForbidden)

    err = json.NewEncoder(w).Encode(struct {
        Error string
    }{Error: clientMsg})
    if err != nil {
        log.Println("Failed to write response: %v", err)
    }

    return
}

好了,本文到此结束,带大家了解了《修改 http.ResponseWriter 作为函数参数传递的方法修改》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>