go http 傳遞json資料
阿新 • • 發佈:2019-01-24
上篇博文中簡單介紹了Go HTTP的Server 和Client。本文介紹如何在HTTP中傳遞json格式的資料。
Server
package main
import (
"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()
cmd := &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))
}
接收資料,進行json解碼。
Client
//post json
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
type Cmd struct {
ReqType int
FileName string
}
func main() {
url := "http://127.0.0.1:8080/bar"
contentType := "application/json;charset=utf-8"
cmd := Cmd{ReqType: 12, FileName: "plugin"}
b ,err := json.Marshal(cmd)
if err != nil {
log.Println("json format error:", err)
return
}
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))
}
將要傳送的資料轉為json格式再發送。