Chinaunix首页 | 论坛 | 博客
  • 博客访问: 789245
  • 博文数量: 211
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1480
  • 用 户 组: 普通用户
  • 注册时间: 2018-03-07 14:59
文章分类
文章存档

2019年(161)

2018年(50)

我的朋友

分类: 系统运维

2018-10-31 19:47:56

使用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  -d '{"Id": "", "Balance": 8}'

通过curl命令执行后,在server端屏幕上能正常打印就表示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: "", Balance: 8}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(u)
res, _ := http.Post("", "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: "", Balance: 8}
json.NewEncoder(w).Encode(u)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}

通过curl 其会返回{Id: "", Balance: 8}数据给客户端。

四、返回响应头信息

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

package main
import (
"net/http"
"encoding/json"
"bytes"
"fmt"
)
type User struct{
Id string
Balance uint64
}
func main() {
u := User{Id: "", Balance: 8}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(u)
res, _ := http.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}
阅读(1741) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:tomcat搭建之Jenkins环境

给主人留下些什么吧!~~