golang post发送application/json数据到服务器

前端之家收集整理的这篇文章主要介绍了golang post发送application/json数据到服务器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import (
    "net/http"
    "encoding/json"
    "fmt"
    "bytes"
    "io/IoUtil"
    "unsafe"
)
 
type JsonPostSample struct {
 
}
 
func (this *JsonPostSample) SamplePost() {
    song := make(map[string]interface{})
    song["name"] = "李白"
    song["timelength"] = 128
    song["author"] = "李荣浩"
    bytesData,err := json.Marshal(song)
    if err != nil {
        fmt.Println(err.Error() )
        return
    }
    reader := bytes.NewReader(bytesData)
    url := "http://localhost/echo.PHP"
    request,err := http.NewRequest("POST",url,reader)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    request.Header.Set("Content-Type","application/json;charset=UTF-8")
    client := http.Client{}
    resp,err := client.Do(request)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    respBytes,err := IoUtil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    //byte数组直接转成string,优化内存
    str := (*string)(unsafe.Pointer(&respBytes))
    fmt.Println(*str)
}
http://www.cnblogs.com/hitfire/articles/6427033.html 原文链接:https://www.f2er.com/go/188199.html

猜你在找的Go相关文章