使用golang下的net/http模塊,能夠很容易的實現webserver功能。本篇就結合http模塊在POST發送josn數據給webserver以及webserver在收到json數據後如何處理。linux
1、server端處理json數據golang
server端代碼以下:web
package main import ( "net/http" "fmt" "log" "encoding/json" ) type User struct{ Id string Balance uint64 } func main() { http.HandleFunc("/", func(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.Id) }) log.Fatal(http.ListenAndServe(":8080", nil)) }
經過go run server.go運行後,能夠經過curl 命令進行測試:json
curl http://127.0.0.1:8080 -d '{"Id": "www.361way.com", "Balance": 8}'
經過curl命令執行後,在server端屏幕上能正常打印www.361way.com就表示server端已正常處理json數據。服務器
2、client端的json post處理app
client端實現的功能就是上面curl命令執行實現的功能,其代碼以下:curl
package main import ( "net/http" "encoding/json" "io" "os" "bytes" ) type User struct{ Id string Balance uint64 } func main() { u := User{Id: "www.361way.com", Balance: 8} b := new(bytes.Buffer) json.NewEncoder(b).Encode(u) res, _ := http.Post("http://127.0.0.1:8080", "application/json; charset=utf-8", b) io.Copy(os.Stdout, res.Body) }
3、服務端返回json數據post
避免可能描述的歧義,這裏用英文描述爲「Encoding JSON in a server response」,即經過服務器處理後,將json數據返回給客戶端測試
package main import ( "net/http" "log" "encoding/json" ) type User struct{ Id string Balance uint64 } func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { u := User{Id: "www.361way.com", Balance: 8} json.NewEncoder(w).Encode(u) }) log.Fatal(http.ListenAndServe(":8080", nil)) }
經過curl http://127.0.0.1:8080 其會返回{Id: "www.361way.com", Balance: 8}數據給客戶端。ui
4、返回響應頭信息
在向服務端發送數據後,有時咱們須要獲取響應頭的信息,能夠經過以下代碼處理:
package main import ( "net/http" "encoding/json" "bytes" "fmt" ) type User struct{ Id string Balance uint64 } func main() { u := User{Id: "www.361way.com", Balance: 8} b := new(bytes.Buffer) json.NewEncoder(b).Encode(u) res, _ := http.Post("https://httpbin.org/post", "application/json; charset=utf-8", b) var body struct { //sends back key/value pairs, no map[string][]string Headers map[string]string `json:"headers"` Origin string `json:"origin"` } json.NewDecoder(res.Body).Decode(&body) fmt.Println(body) }
以上代碼在向httpbin.org post數據後,會獲得以下響應信息:
{map[Content-Length:36 Content-Type:application/json; charset=utf-8 Host:httpbin.org User-Agent:Go-http-client/1.1 Accept-Encoding:gzip Connection:close] 115.28.174.118}