如何使用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?

使用golang代码,我必须使用其api将文件传输到远程服务。 他们的要求是,请求不得 strong>使用multipart / form-data。 我尝试了这个curl命令: p>

  curl -i -X PUT -F filedata=@text.txt -H“ Content-Type:text / plain” https:// url  .of.endpoint.com 
  code>  pre> 
 
 

,因为它模拟表单,所以不起作用,但是此命令: p>

  curl -i -X PUT -T text.txt -H“内容类型:文本/纯文本” https://url.of.endpoint.com 
  code>  pre> 
 
 

工作正常。 p>

如何将curl命令转换为golang代码? p> div>

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()
}

It would be like this:

package main

import (
    "fmt"
    "net/http"
    "net/http/httputil"
    "os"
)

func main() {
    // Open a file.
    f, err := os.Open("text.txt")
    if err != nil {
        panic(err)
    }
    defer f.Close()

    // Post a file to URL.
    resp, err := http.Post("https://url.of.endpoint.com", "text/plain", f)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    // Dump response to debug.
    b, err := httputil.DumpResponse(resp, true)
    if err != nil {
        panic(err)
    }
    fmt.Println(b)
}