ResponseWriter

*response是ResponseWriter接口的实现。
WriteHeader方法:
设置响应的状态码,返回错误状态码特别有用。WriteHeader方法在执行完毕之后就不允许对首部进行写入了。

func redirect(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("location", "https://www.baidu.com")
    w.WriteHeader(302)
}

向客户端返回JSON数据:
首先使用Header方法将内容类型设置成application/json,然后将JSON数据写入ResponseWriter中

func JSONExample(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    post := &post{
        User:    "mc",
        Threads: []string{"first", "second", "third", "fourth", "fifth"},
    }
    json, err := json2.Marshal(post)
    if err != nil {
        return
    }
    w.Write(json)
}

猜你喜欢

转载自blog.csdn.net/weixin_42506905/article/details/82555944