使用golang下的net/http模块,可以很容易的实现webserver功能。本篇就结合http模块在POST发送josn数据给webserver以及webserver在收到json数据后如何处理。
server端代码如下:
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 进行测试:
curl //127.0.0.1:8080 -d '{"Id": "www.361way.com", "Balance": 8}'
通过curl执行后,在server端屏幕上能正常打印www.361way.com就表示server端已正常处理json数据。
client端实现的功能就是上面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("//127.0.0.1:8080", "application/json; charset=utf-8", b) io.Copy(os.Stdout, res.Body) }
避免可能描述的歧义,这里用英文描述为“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 //127.0.0.1:8080 其会返回{Id: "www.361way.com", Balance: 8}数据给客户端。
在向服务端发送数据后,有时我们需要获取响应头的信息,可以通过如下代码处理:
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("//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}
原文来自:
本文地址://gulass.cn/golang-json-sovle.html编辑:问题终结者,审核员:逄增宝
Linux命令大全:
Linux系统大全: