Skip to content

Instantly share code, notes, and snippets.

@mayankcpdixit
Last active March 30, 2019 10:58
Show Gist options
  • Save mayankcpdixit/37e5533992ad7287b67d62256b8bb70e to your computer and use it in GitHub Desktop.
Save mayankcpdixit/37e5533992ad7287b67d62256b8bb70e to your computer and use it in GitHub Desktop.
Setting up http trailers in Golang

Setting up http trailers in Golang

  1. Trailers are of header type in go.
  2. You can only read trailer after reading body
package main

import (
	"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

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