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// encoded query values, without '?' Fragment string// fragment for references, without '#' RawFragment string// encoded fragment hint (see EscapedFragment method) }
funcbody(writer http.ResponseWriter, request *http.Request) { len := request.ContentLength body := make([]byte, len) request.Body.Read(body) fmt.Fprintln(writer, string(body)) }
解析Form字段
可以解析form也可以解析x-www-form-urlencoded
1 2 3 4 5 6
funcform(w http.ResponseWriter, r *http.Request) { r.ParseForm() id := r.Form.Get("id") fmt.Fprintln(w, r.Form) fmt.Fprintln(w, "id is ", id) }
form-data 和 x-www-form-urlencoded的区别
multipart/form-data:可以上传文件或者键值对,最后都会转化为一条消息
x-www-form-urlencoded:只能上传键值对,而且键值对都是通过&间隔分开的
PostForm字段
只能解析x-www-form-urlencoded类型的
1 2 3 4 5 6
funcpostForm(w http.ResponseWriter, r *http.Request) { r.ParseForm() id := r.Form.Get("id") fmt.Fprintln(w, r.Form) fmt.Fprintln(w, "id is ", id) }
multipartForm字段
1 2 3 4
funcmultipartForm(w http.ResponseWriter, r *http.Request) { r.ParseMultipartForm(1000) fmt.Fprintln(w, r.MultipartForm) }
对比
文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcfile(w http.ResponseWriter, r *http.Request) { r.ParseMultipartForm(1024) fileHeader := r.MultipartForm.File["file"][0] file, _ := fileHeader.Open() NewFile, _ := os.Create("file.proto") bytes := make([]byte, 1024) for { n, err := file.Read(bytes) NewFile.Write(bytes[:n]) if err != nil { if err == io.EOF { break } } } NewFile.Close() fmt.Fprintln(w, r.MultipartForm) }
json数据
1 2 3 4 5 6 7 8 9 10 11 12 13
funcfromJson(w http.ResponseWriter, r *http.Request) { //接收json并解析 var person person _ = json2.NewDecoder(r.Body).Decode(&person) bytes, _ := json2.Marshal(&person) w.Header().Set("Content-Type", "application/json") w.Write(bytes) }
type person struct { Name string`json:"name"` Age int`json:"age"` }