Skip to content

Instantly share code, notes, and snippets.

@wlhee
Last active November 23, 2019 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wlhee/ad457e47301f1f4f534258cbaed2459e to your computer and use it in GitHub Desktop.
Save wlhee/ad457e47301f1f4f534258cbaed2459e to your computer and use it in GitHub Desktop.
Example Upstream
package main
import (
"fmt"
"io"
"math"
"net/http"
"net/http/httputil"
"strconv"
"strings"
"time"
)
var (
server *http.Server
)
func handler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "hello, world!!!\n")
}
// By default, it returns 5 chunks, one per second
// /chunked?interval=500ms to change the interval
// /chunked?infinite=true to change to return infinite number of chunks
// /chunked?size_bytes=1000 to change the size of chunk.
func chunkedHandler(w http.ResponseWriter, r *http.Request) {
requestDump, _ := httputil.DumpRequest(r, true)
fmt.Printf("%s", string(requestDump))
flusher, ok := w.(http.Flusher)
if !ok {
panic("expected http.ResponseWriter to be an http.Flusher")
}
interval := time.Second
if in := r.URL.Query().Get("interval"); in != "" {
if d, err := time.ParseDuration(in); err == nil {
interval = d
}
}
var count int64
count = 5
if r.URL.Query().Get("infinite") != "" {
count = math.MaxInt64
}
fixedSizeChunk := ""
if sz := r.URL.Query().Get("size_bytes"); sz != "" {
if i, err := strconv.Atoi(sz); err == nil {
fixedSizeChunk = strings.Repeat("a", i)
}
}
fmt.Printf("[%v] send a chunk every %v for %d times\n", time.Now(), interval, count)
if fixedSizeChunk != "" {
fmt.Printf("[%v] fixed size chunk is set to %d\n", time.Now(), len(fixedSizeChunk))
}
var i int64
for ; i < count; i++ {
chunk := fmt.Sprintf("[%v] Chunk #%d\n", time.Now(), i)
if fixedSizeChunk != "" {
chunk = fixedSizeChunk
}
//fmt.Printf("%s", chunk)
if _, err := fmt.Fprintf(w, "%s", chunk); err != nil {
fmt.Printf("failed to flush the chunk: %s\n", chunk)
return
}
flusher.Flush() // Trigger "chunked" encoding and send a chunk...
time.Sleep(interval)
}
fmt.Printf("[%v] %d chunks were sent.\n", time.Now(), count)
}
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/chunked", chunkedHandler)
server = &http.Server{Addr: ":8080"}
fmt.Printf("[%v] Start listening ...\n", time.Now())
server.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment