golang php 解析json,golang json数据的处理

使用golang下的net/http模块,可以很容易的实现webserver功能。本篇就结合http模块在POST发送josn数据给webserver以及webserver在收到json数据后如何处理。

一、server端处理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 http://127.0.0.1:8080 -d '{"Id": "www.361way.com", "Balance": 8}'

通过curl命令执行后,在server端屏幕上能正常打印www.361way.com就表示server端已正常处理json数据。

二、client端的json post处理

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("http://127.0.0.1:8080", "application/json; charset=utf-8", b)

io.Copy(os.Stdout, res.Body)

}

三、服务端返回json数据

避免可能描述的歧义,这里用英文描述为“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}数据给客户端。

四、返回响应头信息

在向服务端发送数据后,有时我们需要获取响应头的信息,可以通过如下代码处理: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}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值