Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created February 17, 2020 16:09
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 xeoncross/d99fc3631fbf99a302e8d1e700ceda2d to your computer and use it in GitHub Desktop.
Save xeoncross/d99fc3631fbf99a302e8d1e700ceda2d to your computer and use it in GitHub Desktop.
Example of using https://github.com/peterbourgon/ctxdata as a middleware
package contextmiddleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/peterbourgon/ctxdata/v2"
)
type controller struct {
Error string
}
func (c *controller) logMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, d := ctxdata.New(r.Context())
defer func() {
if msg, ok := d.Get("error"); ok {
c.Error = msg
}
}()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
d := ctxdata.From(r.Context())
d.Set("error", "problem here")
})
func TestMiddleware(t *testing.T) {
// Create the request and call the HTTP handler
req, err := http.NewRequest("POST", "ABC", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
resp := httptest.NewRecorder()
c := &controller{}
h := c.logMiddleware(handler)
h.ServeHTTP(resp, req)
if c.Error == "" {
t.Error("Context does not hold error")
}
t.Log("error", c.Error)
}
@xeoncross
Copy link
Author

Make sure to use .From() not .New(): https://play.golang.org/p/NyeM3HU_jf5

@xeoncross
Copy link
Author

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