自学内容网 自学内容网

golang web笔记-3.响应ResponseWriter

简介        

        从服务器向客户端返回响应需要使用 ResponseWriter,ResponseWriter是一个接口,handler用它来返回响应。

ResponseWriter常用方法

  1. Write:接收一个byte切片作为参数,然后把它写入到响应的body中。如果Write被调用时,header里边没有设定content type,那么数据的前512个字节就会被用来监测content type。

  2. Header:返回headers的map,可以进行修改,修改后的headers将会体现在返回给客户段的http响应里。
  3. WriteHeader: 方法接收一个整数类型作为参数,并把它设置为Http响应的状态吗,如果状态码没有被显示调用,默认WriteHeader(http.StatusOK);WriteHeader主要用来设置错误码。WriteHeader设置后Header将不能再被修改。
    package main
    
    import (
    "fmt"
    "net/http"
    )
    
    func main() {
    server := http.Server{
    Addr: "localhost:8080",
    }
    http.HandleFunc("/test", func(writer http.ResponseWriter, request *http.Request) {
    html := "<html><head><title>测试response</title></head><body><h1>Hello World!</h1></body></html>"
    writer.Header().Set("Location", "http:localhost:8080")
    writer.WriteHeader(302) //WriteHeader设置后Header将不能再被修改。修改header需要在设置WriteHeader之前
    fmt.Fprintln(writer, "测试错误返回501")
    writer.Write([]byte(html))
    })
    server.ListenAndServe()
    }

ResponseWriter返回json

创建json对应的struct

  1. 创建struct对应的实例
  2. 响应header的Content-Type需设置为appliation/json
  3. 使用json.Marshal将struct的实例转换为json
  4. 使用Write方法返回json
package main

import (
"encoding/json"
"net/http"
)

type Post struct {
User    string
Threads []string
}

func main() {
server := http.Server{
Addr: "localhost:8080",
}
http.HandleFunc("/test", func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "appliation/json")
post := &Post{
User:    "Xiaoqiang",
Threads: []string{"first", "second", "third"},
}
jsonStr, _ := json.Marshal(post)
writer.Write(jsonStr)

})
server.ListenAndServe()
}

内置响应

NotFound函数:返回404状态码和一个额外的信息

ServeFile函数:从文件系统提供文件返回给请求者

ServeContent函数:实现了io.ReadSeeker接口的任何东西里面的内容返回给请求者

Redirect函数:告诉客户段重定向到另外一个URl


原文地址:https://blog.csdn.net/m0_37514863/article/details/142639154

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!