当前位置: 首页 > 工具软件 > gohttp > 使用案例 >

go http 传递json数据

钦侯林
2023-12-01

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

//post json
package main

import (
    "bytes"
    "encoding/json"
    "io/ioutil"
    "log"
    "net/http"

)

type Cmd struct {

    ReqType int
    FileName string

}


func main() {

    url := "http://127.0.0.1:8080/bar"
    contentType := "application/json;charset=utf-8"

    cmd := Cmd{ReqType: 12, FileName: "plugin"}
    b ,err := json.Marshal(cmd)
    if err != nil {
        log.Println("json format error:", err)
        return
    }

    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

 类似资料: