1. 程式人生 > >go http 傳遞json數據

go http 傳遞json數據

code happy json格式 buffer www char ref import ng-

上篇博文中簡單介紹了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數據