Go语言Golang语言社区go学习

Go 网络编程:解析请求数据

2018-01-30  本文已影响133人  Aaaaaaaaaaayou

几个重要的变量

http.request 中涉及到数据解析的几个重要变量为:

    // Form contains the parsed form data, including both the URL
    // field's query parameters and the POST or PUT form data.
    // This field is only available after ParseForm is called.
    // The HTTP client ignores Form and uses Body instead.
    Form url.Values

    // PostForm contains the parsed form data from POST, PATCH,
    // or PUT body parameters.
    //
    // This field is only available after ParseForm is called.
    // The HTTP client ignores PostForm and uses Body instead.
    PostForm url.Values

    // MultipartForm is the parsed multipart form, including file uploads.
    // This field is only available after ParseMultipartForm is called.
    // The HTTP client ignores MultipartForm and uses Body instead.
    MultipartForm *multipart.Form

说明:

Form:存储了post、put和get参数,在使用之前需要调用 ParseForm 方法。
PostForm:存储了post、put参数,在使用之前需要调用 ParseForm 方法。
MultipartForm:存储了包含了文件上传的表单的post参数,在使用前需要调用 ParseMultipartForm
 方法。

获取 GET 参数

因为 Form 中同时存储了 GET 和 POST 请求的参数,所以最好不要用该变量来获取 GET 参数,取而代之的方法为:

queryForm, err := url.ParseQuery(r.URL.RawQuery)
if err == nil && len(queryForm["id"]) > 0 {
    fmt.Fprintln(w, queryForm["id"][0])
}

获取 POST 参数

application/x-www-form-urlencoded 格式

r.ParseForm()
// 法一
r.PostForm["id"][0]
// 法二
r.PostFormValue["id"]

multipart/form-data 格式

普通参数

r.ParseMultipartForm(32<<20)
// 法一
r.PostForm["id"][0]
// 法二
r.PostFormValue["id"]

文件

    r.ParseMultipartForm(32 << 20)
    file, handler, err := r.FormFile("file")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()
    fmt.Fprintf(w, "%v", handler.Header)
    f, err := os.OpenFile("./test.txt", os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()
    io.Copy(f, file)

application/json 格式

type User struct {
    Name string `json:"username"`
    Pwd string `json:"password"`
}

type RetMessage struct {
    Code string `json:"code"`
    Msg string  `json:"msg"`
}

func processJson(w http.ResponseWriter, r *http.Request) {
    var u User
    if r.Body == nil {
        http.Error(w, "Please send a request body", 400)
        return
    }
    err := json.NewDecoder(r.Body).Decode(&u)
    if err != nil {
        http.Error(w, err.Error(), 400)
        return
    }
    fmt.Println(u)
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(RetMessage{"200", "ok"})
}
上一篇 下一篇

猜你喜欢

热点阅读