Request

Request
结构表示客户端发送的HTTP请求报文,且并不是逐句定义。这个结构是HTTP请求报文经过语法分析后,其中较为重要的信息。主要结构为:
URL字段
Header字段
Body字段
Form字段、PostForm字段和MultipartForm字段

type Request struct {   
    //
    Method string
    //是一个指向*url.URL指针
    URL *url.URL

    Proto      string // "HTTP/1.0"
    ProtoMajor int    // 1
    ProtoMinor int    // 0
    //
    Header Header
    //
    Body io.ReadCloser

    GetBody func() (io.ReadCloser, error)

    ContentLength int64

    TransferEncoding []string

    Close bool

    Host string
    //
    Form url.Values
    //
    PostForm url.Values
    //
    MultipartForm *multipart.Form

    Trailer Header

    RemoteAddr string

    RequestURI string

    TLS *tls.ConnectionState

    Cancel <-chan struct{}

    Response *Response

    ctx context.Context
}

请求URL
Request结构中的URL字段表示请求行中包含的URL(请求行也就是HTTP请求报文的第一行)。其结构如下:

type URL struct {
    Scheme     string
    Opaque     string    // encoded opaque data
    User       *Userinfo // username and password information
    Host       string    // host or host:port
    Path       string    // path (relative paths may omit leading slash)
    RawPath    string    // encoded path hint (see EscapedPath method)
    ForceQuery bool      // append a query ('?') even if RawQuery is empty
    RawQuery   string    // 记录查询参数字符串,经语法分析后可得查询参数,但一般用Form字段获取更方便
    Fragment   string    // fragment for references, without '#'
}

URL的一般格式为:

[scheme:][//[userinfo@]host][/]path[?query][#fragment]

请求首部
这种类型使用一个映射表示HTTP首部中的多个键值对,该类型有4个基本方法,可根据给定的键执行增删改查。

type Header map[string][]string

想要获取特定的首部:

h1 := r.Header.Get("Accept-Encoding")  //获取字符串
h2 := r.Header["Accept-Encoding"]  //获取切片

请求主体
这个字段是一个io.ReadCloser接口,例如:

func body(w http.ResponseWriter, r *http.Request) {
    len := r.ContentLength
    temp := make([]byte, len)
    r.Body.Read(temp)
    fmt.Fprintln(w, string(temp), time.Now().Weekday().String())
}

func main() {
    http.HandleFunc("/body/", body)

    s := http.Server{
        Addr:    "127.0.0.1:8100",
        Handler: nil,
    }
    s.ListenAndServe()
}

因为GET请求不包含报文主体,所以测试需要给它发送POST请求。浏览器一般通过HTML表单才能发送POST请求。
使用curl发送POST请求:

curl -id "f=zbh&h=hello" 127.0.0.1:8100/body/

结果

HTTP/1.1 200 OK
Date: Thu, 30 Aug 2018 11:26:56 GMT
Content-Length: 23
Content-Type: text/plain; charset=utf-8

f=zbh&h=hello Thursday

用户一般不需要自行读取主体中文未处理的表单,因为Go语言提供了FormValue和FormFIle的方法来提取表单。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值