Setting up http trailers in Golang

Mayank dixit
Average problems quick solutions
1 min readMar 30, 2019
  1. Trailers are of header type in go.
  2. You can only read trailer after reading body
package mainimport (
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/sendTrailer", func(w http.ResponseWriter, req *http.Request) {
w.Header().Add("Trailer", "AtEnd1")
w.WriteHeader(http.StatusOK)
w.Header().Set("AtEnd1", "value 1")
})
ts := httptest.NewServer(mux)
defer ts.Close()
req, _ := http.NewRequest("GET", ts.URL+"/sendTrailer", nil)
res, _ := http.DefaultClient.Do(req)
ioutil.ReadAll(res.Body) // reading for sake of receiving trailer
defer res.Body.Close()
log.Printf("%+v", res.Trailer)
}

example: https://goplay.space/#DcjchhxYBSy

PS: gist

--

--

Mayank dixit
Average problems quick solutions

Web & open source enthusiast. Interested in #code #comedy #music and #kitchen. Learns, writes and shares tech stuff. Wannabe product guy.