duandaiqin6080 2014-12-26 12:05
浏览 221
已采纳

如何使用Golang代码上传文件

With golang code I have to transfer file to remote service using their api. Their requirement is that request MUST NOT use multipart/form-data. I tried this curl command:

curl -i -X PUT -F filedata=@text.txt -H "Content-Type: text/plain"  https://url.of.endpoint.com

it doesn't work since it simulates form, but this command:

curl -i -X PUT -T text.txt -H "Content-Type: text/plain"  https://url.of.endpoint.com

works perfectly.

How can I translate this curl command to golang code?

  • 写回答

2条回答 默认 最新

  • doulu1907 2014-12-26 16:57
    关注

    You have to create a "PUT" request and set its request body to the contents of the file:

    package main
    
    import (
        "log"
        "net/http"
        "os"
    )
    
    func main() {
        data, err := os.Open("text.txt")
        if err != nil {
            log.Fatal(err)
        }
        defer data.Close()
        req, err := http.NewRequest("PUT", "http://localhost:8080/test.txt", data)
        if err != nil {
            log.Fatal(err)
        }
        req.Header.Set("Content-Type", "text/plain")
    
        client := &http.Client{}
        res, err := client.Do(req)
        if err != nil {
            log.Fatal(err)
        }
        defer res.Body.Close()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100