介绍 golang json数据的处理

使用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}
相关文章
相关标签/搜索