// UserError returns a JSON response for the provided UserError and // HTTP status code. func UserError(ctx context.Context, w http.ResponseWriter, status int, uerr usererrors.UserError) { content, err := usererrors.MarshalJSON(uerr) if err != nil { panic(err) } reqlog.SetContext(ctx, "error_code", uerr.Code()) msg := json.RawMessage(content) Data(ctx, w, status, &msg) }
// WrapC wraps a handler and only passes requests with valid Bearer authorization. func (c *Controller) WrapC(inner goji.Handler) goji.Handler { return goji.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { auth := r.Header.Get("Authorization") if !strings.HasPrefix(auth, "Bearer ") { respond.Error(ctx, w, http.StatusUnauthorized, usererrors.BearerAuthRequired{}) return } auth = strings.TrimPrefix(auth, "Bearer ") if user := c.getUser(auth); user != nil { ctx = context.WithValue(ctx, ctxKey, user) reqlog.SetContext(ctx, "user_id", user.ID) inner.ServeHTTPC(ctx, w, r) } else { respond.Error(ctx, w, http.StatusUnauthorized, usererrors.AuthInvalid{}) } }) }
func TestWrapC(t *testing.T) { var buf bytes.Buffer logger := log.New(&buf, "", 0) reqlog.SetLogger(logger) var setOK bool bare := goji.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { setOK = reqlog.SetContext(ctx, "hey", "oh") w.Write([]byte("foo")) }) wrapped := reqlog.WrapC(bare) req, err := http.NewRequest("FOO", "/bar", nil) if err != nil { t.Fatal(err) } wrapped.ServeHTTPC(context.Background(), httptest.NewRecorder(), req) logged := buf.String() t.Log(logged) if !strings.Contains(logged, `http_status=200`) { t.Errorf("Expected http_status in line %s", logged) } if !strings.Contains(logged, `hey="oh"`) { t.Errorf("Expected to say hey oh in line %s", logged) } if !setOK { t.Error("SetContext should have set successfully.") } setOK = true buf.Reset() bare.ServeHTTPC(context.Background(), httptest.NewRecorder(), req) if buf.Len() != 0 { t.Errorf("Nothing should have been logged but got %s", buf.String()) } if setOK { t.Errorf("SetContext should not have set successfully.") } }