http package stuff

HTTP Status Code

Do not use number directly.

Don't do this

w.WriteHeader(404)

Do this

w.WriteHeader(http.StatusNotFound)

Error message

http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)

Flusher

A Flusher can be used to allow an HTTP handler to flush buffered data to the client.

package main

import (
    "fmt"
    "io"
    "net/http"
    "time"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        ended := make(chan bool)
        f, flushable := w.(http.Flusher)
        if flushable {
            go func() {
                ticker := time.NewTicker(1 * time.Second)
                for {
                    select {
                    case <-ticker.C:
                        fmt.Println("debug")
                        io.WriteString(w, "#")
                        f.Flush()
                    case <-ended:
                        return
                    case <-r.Context().Done():
                        return
                    }
                }
            }()
        }
        time.Sleep(5 * time.Second)
        ended <- true
        w.Write([]byte("ok"))
    })

    http.ListenAndServe(":8080", nil)
}