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条)

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样