Skip to content

Instantly share code, notes, and snippets.

@sago35
Created December 24, 2022 02:00
Show Gist options
  • Save sago35/578ff2b74a6b331c7be5e2db89bcb8fe to your computer and use it in GitHub Desktop.
Save sago35/578ff2b74a6b331c7be5e2db89bcb8fe to your computer and use it in GitHub Desktop.
net/http server (chunked)
package main
import (
"io"
"log"
"net/http"
)
func main() {
err := run()
if err != nil {
log.Fatal(err)
}
}
func handlerChunked(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Transfer-Encoding", "chunked")
flusher, ok := w.(http.Flusher)
if !ok {
log.Fatal("error")
}
io.WriteString(w, "Chunk1\n")
flusher.Flush()
io.WriteString(w, "Chunk2Chunk2\n")
flusher.Flush()
//w.Header().Set("Content-Length", "0")
}
func handler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Chunk1\n")
}
func run() error {
http.HandleFunc("/chunked", handlerChunked)
http.HandleFunc("/", handler)
return http.ListenAndServe(":8080", nil)
}
@sago35
Copy link
Author

sago35 commented Dec 24, 2022

httputil.DumpResponse() した結果は以下。
14 とか 0 とかが余分に追加される。
14 は 16 進数なので 0x14 で 20 であることに注意。

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Date: Sat, 24 Dec 2022 02:00:53 GMT

14
Chunk1
Chunk2Chunk2

0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment