如何使用os.Open()的返回值作为http.Post()的第三个参数并设置Content-Length?

http.Post()</ code>的第三个参数允许 io.Reader < / code>,这意味着 os.Open()</ code>的返回值应该起作用。 但是下面的代码得到了意外的结果,换句话说,它不会正确设置 Content-Length </ code>。 也许 File </ code>类型没有实现某些功能。 是否可以使用 * File </ code>设置 Content-Length </ code>的任何正确方法?</ p>

 包main 

import(\ n个[位元组]
“ io / ioutil”
“ log”
“ net / http”
“ net / http / httptest”
“ os”

var样本= [] byte( hello

func main(){
ts:= httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter,r * http.Request){{n log.Println(r.Header)\ n如果int(r.ContentLength)!= len(sample){
log.Fatal(“意外的Content-Length:”,r.ContentLength)
}
w.Header()。Set(“ Content-Type “,” application / json“)
w.Write([] byte({}))
})))
延迟ts.Close()

文件,错误:= ioutil.TempFile( os.TempDir(),“”)
如果err!= nil {
log.Fatal(err)
}
延迟os.Remove(file.Name())
file.Write(sample)\ n
//可以使用
buf,错误:= ioutil.ReadFile(file.Name())
如果错误!= nil {
log.Fatal(err)
}
_,错误= http .Post(ts.URL,“ application / octet-stream”,bytes.Ne wBuffer(buf))
if err!= nil {
log.Fatal(err)
}

//在我看来,这看起来不错,尽管它没有设置Content-Length
f,err := os.Open(file.Name())
,如果错误!=无{
log.Fatal(err)
}
_,错误= http.Post(ts.URL,“ application / octet- 流”,则f)
如果错误!=无{
log.Fatal(err)
}
}
</ code> </ pre>

输出:</ p>

  2009/11/10 23:00:00 map [Content-Type:[application / octet-stream] Accept-Encoding:[gzip] User-Agent:[Go-http-client  /1.1] Content-Length:[5]] 
2009 / 11/10 23:00:00 map [Content-Type:[application / octet-stream] Accept-Encoding:[gzip] User-Agent:[Go-http -client / 1.1]]
2009 / 11/10 23:00:00意外的内容长度:-1
</ code> </ pre>

https://play.golang.org/p/hJLN2H9Y9p </ p>
</ div>

展开原文

原文

The third parameter of http.Post() allows io.Reader and that means the return value of os.Open() should work. But the below code gets unexpected result, in other words, it won't set Content-Length properly. Perhaps File type doesn't implement something. Is there any proper way to set Content-Length with *File?

package main

import (
    "bytes"
    "io/ioutil"
    "log"
    "net/http"
    "net/http/httptest"
    "os"
)

var sample = []byte(`hello`)

func main() {
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println(r.Header)
        if int(r.ContentLength) != len(sample) {
            log.Fatal("Unexpected Content-Length:", r.ContentLength)
        }
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(`{}`))
    }))
    defer ts.Close()

    file, err := ioutil.TempFile(os.TempDir(), "")
    if err != nil {
        log.Fatal(err)
    }
    defer os.Remove(file.Name())
    file.Write(sample)

    // This works
    buf, err := ioutil.ReadFile(file.Name())
    if err != nil {
        log.Fatal(err)
    }
    _, err = http.Post(ts.URL, "application/octet-stream", bytes.NewBuffer(buf))
    if err != nil {
        log.Fatal(err)
    }

    // This looks fine in my opinion, though it doesn't set Content-Length
    f, err := os.Open(file.Name())
    if err != nil {
        log.Fatal(err)
    }
    _, err = http.Post(ts.URL, "application/octet-stream", f)
    if err != nil {
        log.Fatal(err)
    }
}

Output:

2009/11/10 23:00:00 map[Content-Type:[application/octet-stream] Accept-Encoding:[gzip] User-Agent:[Go-http-client/1.1] Content-Length:[5]]
2009/11/10 23:00:00 map[Content-Type:[application/octet-stream] Accept-Encoding:[gzip] User-Agent:[Go-http-client/1.1]]
2009/11/10 23:00:00 Unexpected Content-Length:-1

https://play.golang.org/p/hJLN2H9Y9p

douwo3665
douwo3665 使用Flask(python)构建的Web应用程序具有request.stream,如果不发送Content-Length,该应用程序将无法正常工作。
大约 4 年之前 回复
duanfei8897
duanfei8897 为什么需要设置Content-Length?
大约 4 年之前 回复

2个回答



如果您查看 NewRequest 中,您可以看到contentLength是专门为特定输入类型处理的,而文件阅读器不是其中之一。 如果这很重要,则必须手动设置Content-Length标头[分块也可以正常工作,除非您要发送到旧的服务器impl]。</ p>
</ div>

展开原文

原文

If you look at source for NewRequest you can see that contentLength is handled specially for specific input types, and the file reader isn't one of them. You'll have to manually set the Content-Length header if that's important [chunked should also work fine, unless you're sending to an old server impl].



如果要添加添加 Content-Length </ code>,则需要统计文件以获取 尺寸。 无法自动计算ContentLength,因为 os.File </ code>可能没有有用的大小。 </ p>

  f,err:= os.Open(file.Name())
if err!= nil {
log.Fatal(err)
}
\ nreq,err:= http.NewRequest(“ POST”,ts.URL,f)
if err!= nil {
log.Fatal(err)
}

stat,err:= f.Stat()

if err!= nil {
log.Fatal(err)
}

req.ContentLength = stat.Size()
req.Header.Set(“ Content-Type”,“ application / octet-stream” )

resp,错误= http.Do(req)
...
</ code> </ pre>
</ div>

展开原文

原文

If you want to add a add the Content-Length, you need to stat the file to get the size. The ContentLength isn't calculated automatically because an os.File may not have a useful size.

f, err := os.Open(file.Name())
if err != nil {
    log.Fatal(err)
}

req, err := http.NewRequest("POST", ts.URL, f)
if err != nil {
    log.Fatal(err)
}

stat, err := f.Stat()
if err != nil {
    log.Fatal(err)
}

req.ContentLength = stat.Size()
req.Header.Set("Content-Type", "application/octet-stream")

resp, err = http.Do(req)
...

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐