"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > HTTP 서버가 점차적으로 청크 응답을 보내지 않는 이유는 무엇입니까?

HTTP 서버가 점차적으로 청크 응답을 보내지 않는 이유는 무엇입니까?

2025-04-14에 게시되었습니다
검색:150

Why Doesn't My Go HTTP Server Send Chunked Responses Progressively?

http chunks 응답

func HandlePost(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Connection", "Keep-Alive")
    w.Header().Set("Transfer-Encoding", "chunked")
    w.Header().Set("X-Content-Type-Options", "nosniff")

    ticker := time.NewTicker(time.Second)
    go func() {
        for t := range ticker.C {
            io.WriteString(w, "Chunk")
            fmt.Println("Tick at", t)
        }
    }()
    time.Sleep(time.Second * 5)
    ticker.Stop()
    fmt.Println("Finished: should return Content-Length: 0 here")
    w.Header().Set("Content-Length", "0")
}

    클라이언트는 의도 한대로 점진적으로 한 번에 모든 청크를 한 번에 받고 있습니다.
  1. 콘텐츠 길이 헤더는 자동으로 GO에 의해 설정되어 있습니다. 제공 서버 코드는 다음과 같습니다.
  2. func handlepost (w http.responsewriter, r *http.request) { w.header (). set ( "Connection", "Keep-Alive") w.header (). set ( "송환", "청크") w.header (). set ( "x-content-type-options", "nosniff") 시세 : = time.newticker (time.second) go func () { t : = Range Ticker.c { io.writestring (w, "chunk") fmt.println ( "tick at", t) } } () Time.sleep (Time.second * 5) Ticker.stop () fmt.println ( "완료 : 컨텐츠 길이를 반환해야합니다 : 0 HERE") w.header (). set ( "컨텐츠 길이", "0") }

솔루션

func HandlePost(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Connection", "Keep-Alive")
    w.Header().Set("Transfer-Encoding", "chunked")
    w.Header().Set("X-Content-Type-Options", "nosniff")

    ticker := time.NewTicker(time.Second)
    go func() {
        for t := range ticker.C {
            io.WriteString(w, "Chunk")
            fmt.Println("Tick at", t)
        }
    }()
    time.Sleep(time.Second * 5)
    ticker.Stop()
    fmt.Println("Finished: should return Content-Length: 0 here")
    w.Header().Set("Content-Length", "0")
}
문제를 해결하려면 :

$ telnet localhost 8080
...
HTTP/1.1 200 OK
Date: ...
Content-Type: text/plain; charset=utf-8
Transfer-Encoding: chunked

9
Chunk #1

9
Chunk #2

...

전송 인코딩 헤더는 HTTP 작가가 자동으로 관리하므로 명시 적으로 설정하지 않습니다.

Why Doesn't My Go HTTP Server Send Chunked Responses Progressively?

"FMT" "io" "통나무" "net/http" "시간" )) func main () { http.handlefunc ( "/", func (w http.responsewriter, r *http.request) { Flusher, OK : = w. (http.flusher) IF! OK { panic ( "예상 http.responsewriter가 http.flusher가 될 것으로 예상됩니다") } w.header (). set ( "x-content-type-options", "nosniff") i : = 1; I
    verification
Telnet을 사용하여 서버에 연결하십시오 :

$ telnet localhost 8080 ... HTTP/1.1 200 OK 날짜: ... 내용 유형 : 텍스트/일반; charset = utf-8 전송 인코딩 : 청크 9 청크 #1 9 청크 #2 ...

각 청크는 서버가 보내면서 점진적으로 수신됩니다.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3