码迷,mamicode.com
首页 > Web开发 > 详细

go http 传递json数据

时间:2017-12-03 18:59:24      阅读:465      评论:0      收藏:0      [点我收藏+]

标签:rsh   encoding   com   package   发送   html   net   only   app   

上篇博文中简单介绍了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

go http 传递json数据

标签:rsh   encoding   com   package   发送   html   net   only   app   

原文地址:http://www.cnblogs.com/lanyangsh/p/7966705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!