Skip to content

Instantly share code, notes, and snippets.

@slawosz
Created September 22, 2014 13:40
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 slawosz/fc1d3c4159474e24e6ff to your computer and use it in GitHub Desktop.
Save slawosz/fc1d3c4159474e24e6ff to your computer and use it in GitHub Desktop.
package main
import (
"net/http"
"net/http/httptest"
)
type FooRequest struct {
Payload string
}
type ModifierMiddleware struct {
handler *FooRequest
}
func (m *ModifierMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rec := httptest.NewRecorder()
// passing a ResponseRecorder instead of the original RW
foo := m.handler
foo.Payload = "payload from middleware"
m.handler.ServeHTTP(rec, r)
// after this finishes, we have the response recorded
// and can modify it before copying it to the original RW
// we copy the original headers first
for k, v := range rec.Header() {
w.Header()[k] = v
}
// and set an additional one
w.Header().Set("X-We-Modified-This", "Yup")
w.Header().Set("X-Payload", foo.Payload)
// only then the status code, as this call writes the headers as well
w.WriteHeader(418)
// the body hasn't been written yet, so we can prepend some data.
w.Write([]byte("Middleware says hello again. "))
// then write out the original body
w.Write(rec.Body.Bytes())
}
func (self *FooRequest) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(self.Payload))
self.Payload = "bla bla bla"
}
func barHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("bar!"))
}
func main() {
foo := &FooRequest{}
mid := &ModifierMiddleware{foo}
println("Listening on port 7080")
http.ListenAndServe(":7080", mid)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment