Created
February 17, 2020 16:09
-
-
Save xeoncross/d99fc3631fbf99a302e8d1e700ceda2d to your computer and use it in GitHub Desktop.
Example of using https://github.com/peterbourgon/ctxdata as a middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure to use .From() not .New(): https://play.golang.org/p/NyeM3HU_jf5