Example #1
0
func TestWrapC(t *testing.T) {
	t.Parallel()

	ctrl, err := auth.New(apptest.TestSecret)
	if err != nil {
		t.Fatal(err)
	}

	var ctx, lastCtx context.Context

	handler := ctrl.WrapC(goji.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		lastCtx = ctx
		w.WriteHeader(http.StatusOK)
	}))

	lastCtx = nil
	ctx = context.TODO()

	testCases := map[string]int{
		"":                    http.StatusUnauthorized,
		"invalid":             http.StatusUnauthorized,
		apptest.TestValidUser: http.StatusOK,
	}

	for user, expect := range testCases {
		req, err := http.NewRequest("", "", nil)
		if err != nil {
			t.Fatal(err)
		}

		if user != "" {
			req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", user))
		}

		rr := httptest.NewRecorder()
		handler.ServeHTTPC(ctx, rr, req)

		if rr.Code != expect {
			t.Errorf("With authorization %q, expected status %d but got %d",
				user, expect, rr.Code)
		}
	}
}
Example #2
0
File: app.go Project: metcalf/saypi
// New creates an App for the given configuration.
func New(config *Configuration) (*App, error) {
	var app App

	db, err := buildDB(config.DBDSN, config.DBMaxIdle, config.DBMaxOpen)
	if err != nil {
		defer app.Close()
		return nil, err
	}
	app.closers = append(app.closers, db)

	ipQuota := throttled.RateQuota{throttled.PerMin(config.IPPerMinute), config.IPRateBurst}
	ipLimiter, err := buildLimiter(ipQuota)

	authCtrl, err := auth.New(config.UserSecret)
	if err != nil {
		defer app.Close()
		return nil, err
	}

	sayCtrl, err := say.New(db)
	if err != nil {
		defer app.Close()
		return nil, err
	}
	app.closers = append(app.closers, sayCtrl)

	// TODO: Proper not found handler
	privMux := goji.NewMux()
	privMux.UseC(metrics.WrapSubmuxC)
	privMux.UseC(authCtrl.WrapC)

	privMux.HandleFuncC(Routes.GetAnimals, sayCtrl.GetAnimals)

	privMux.HandleFuncC(Routes.ListMoods, sayCtrl.ListMoods)
	privMux.HandleFuncC(Routes.SetMood, sayCtrl.SetMood)
	privMux.HandleFuncC(Routes.GetMood, sayCtrl.GetMood)
	privMux.HandleFuncC(Routes.DeleteMood, sayCtrl.DeleteMood)

	privMux.HandleFuncC(Routes.ListConversations, sayCtrl.ListConversations)
	privMux.HandleFuncC(Routes.CreateConversation, sayCtrl.CreateConversation)
	privMux.HandleFuncC(Routes.GetConversation, sayCtrl.GetConversation)
	privMux.HandleFuncC(Routes.DeleteConversation, sayCtrl.DeleteConversation)

	privMux.HandleFuncC(Routes.CreateLine, sayCtrl.CreateLine)
	privMux.HandleFuncC(Routes.GetLine, sayCtrl.GetLine)
	privMux.HandleFuncC(Routes.DeleteLine, sayCtrl.DeleteLine)

	mainMux := goji.NewMux()
	mainMux.HandleFuncC(Routes.CreateUser, authCtrl.CreateUser)
	mainMux.HandleFuncC(Routes.GetUser, authCtrl.GetUser)
	mainMux.HandleC(pat.New("/*"), privMux)

	mainMux.UseC(reqlog.WrapC)
	mainMux.UseC(respond.WrapPanicC)
	mainMux.UseC(metrics.WrapC)
	mainMux.Use(ipLimiter.RateLimit)

	app.srv = mainMux

	return &app, nil
}