The server and client of Go HTTP are briefly described in the previous blog post. This article describes how to pass data in JSON format in HTTP.
Server
Package Mainimport ("Encoding/json" "FMT" "html" "Io/ioutil" "Log" "Net/http") Type CMD struct {reqtype int FileName string}func Main () {http. Handlefunc ("/bar", func (w http). Responsewriter, R *http. Request) {fmt. fprintf (W, "Hello,%q", HTML. Escapestring (R.url. Path)) If R.method = = "POST" {b, err: = Ioutil. ReadAll (r.body) if err! = Nil {log. Println ("Read failed:", err)} defer r.body.close () c MD: = &cmd{} err = json. Unmarshal (b, cmd) if err! = Nil {log. PRINTLN ("JSON format error:", err)} log. Println ("cmd:", cmd)} else {log. PRINTLN ("Only support Post") fmt. Fprintf (W, "only support Post")}) log. Fatal (http. Listenandserve (": 8080", nil))}
Receive data for JSON decoding.
Client
package mainimport ( "bytes" "io/ioutil" "log" "net/http")func main() { url := "http://127.0.0.1:8080/bar" contentType := "application/json;charset=utf-8" b := []byte("Hello, Server") body := bytes.NewBuffer(b) resp, err := http.Post(url, contentType, body) if err != nil { log.Println("Post failed:", err) return } defer resp.Body.Close() content, err := ioutil.ReadAll(resp.Body) if err != nil { log.Println("Read failed:", err) return } log.Println("content:", string(content))}
The data to be sent is converted to JSON format and sent.
Reference
http://www.01happy.com/golang-http-client-get-and-post/
http://blog.csdn.net/typ2004/article/details/38669949
Go HTTP pass JSON data