duanqing3026 2016-05-26 13:31
浏览 13
已采纳

发送八位字节流

I have two go programs - one running as a server daemon, the other being executed manually. I want to be able to send a request to the server from the other program, sending some binary data there via post request. How can I do this?

I know I can send a string like this:

data := url.Values{}
data.Set("req", buf)
u, _ := url.ParseRequestURI(domain)
u.Path = path
urlStr := fmt.Sprintf("%v", u)
client := &http.Client{}
r, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode()))
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
return resp.Status

But I want to send an octet-stream which I can then read from ioutil.ReadAll(r.Body).

  • 写回答

1条回答 默认 最新

  • dopuz8728 2016-05-26 14:35
    关注

    The following show how to send data inside the request body to a server, and read it on the server side. The client part is as follow:

    c := http.Client{}
    data := []byte("This is a content that will be sent in the body")
    r, err := http.NewRequest("POST", "http://localhost:8080", bytes.NewBuffer(data))
    // You should never ignore the error returned by a call.
    if err != nil {
        panic(err)
    }
    c.Do(r)
    

    And in your http.Handler function:

    d, err := ioutil.ReadAll(r.Body)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
    }
    
    fmt.Println("Request content : ", string(d))
    

    This is the easiest way.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)