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 依据报错在原代吗格式的基础上解决问题
  • ¥15 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?