上篇博文中简单介绍了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
package main
import (
"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))
}
将要发送的数据转为json格式再发送。
参考
http://www.01happy.com/golang-http-client-get-and-post/
http://blog.csdn.net/typ2004/article/details/38669949
时间: 2024-10-11 21:05:46