예제 #1
0
파일: routes.go 프로젝트: gernest/utron
// add registers controller ctrl, using activeRoute. If middlewares are provided, utron uses
// alice package to chain middlewares.
func (r *Router) add(activeRoute *route, ctrlfn func() controller.Controller, middlewares ...interface{}) error {
	var m []*Middleware
	if len(middlewares) > 0 {
		for _, v := range middlewares {
			switch v.(type) {
			case func(http.Handler) http.Handler:
				m = append(m, &Middleware{
					Type:  PlainMiddleware,
					value: v,
				})
			case func(*base.Context) error:
				m = append(m, &Middleware{
					Type:  CtxMiddleware,
					value: v,
				})

			default:
				return fmt.Errorf("unsupported middleware %v", v)
			}
		}
	}
	// register methods if any
	if len(activeRoute.methods) > 0 {
		r.HandleFunc(activeRoute.pattern, func(w http.ResponseWriter, req *http.Request) {
			ctx := base.NewContext(w, req)
			r.prepareContext(ctx)
			chain := chainMiddleware(ctx, m...)
			chain.ThenFunc(r.wrapController(ctx, activeRoute.fn, ctrlfn())).ServeHTTP(w, req)
		}).Methods(activeRoute.methods...)
		return nil
	}
	r.HandleFunc(activeRoute.pattern, func(w http.ResponseWriter, req *http.Request) {
		ctx := base.NewContext(w, req)
		r.prepareContext(ctx)
		chain := chainMiddleware(ctx, m...)
		chain.ThenFunc(r.wrapController(ctx, activeRoute.fn, ctrlfn())).ServeHTTP(w, req)
	})

	return nil
}
예제 #2
0
func TestBaseController(t *testing.T) {
	req, _ := http.NewRequest("GET", "/", nil)
	w := httptest.NewRecorder()

	ctx := base.NewContext(w, req)

	ctrl := BaseController{}

	if ctrl.New(ctx); ctrl.Ctx == nil {
		t.Error("expected Ctx to be set")
	}

	// HTML response
	ctrl.HTML(http.StatusOK)
	cTyp := w.Header().Get(base.Content.Type)
	if cTyp != base.Content.TextHTML {
		t.Errorf("expecetd %s got %s", base.Content.TextHTML, cTyp)
	}

	// JSON response
	ctrl.JSON(http.StatusOK)
	cTyp = w.Header().Get(base.Content.Type)
	if cTyp != base.Content.Application.JSON {
		t.Errorf("expected %s got %s", base.Content.Application.JSON, cTyp)
	}

	// Plain text response
	ctrl.String(http.StatusOK)
	cTyp = w.Header().Get(base.Content.Type)
	if cTyp != base.Content.TextPlain {
		t.Errorf("expected %s got %s", base.Content.TextPlain, cTyp)
	}

	err := ctrl.Render()
	if err != nil {
		t.Errorf("expected nil got %v", err)
	}

	err = ctrl.Render()
	if err == nil {
		t.Error("expected error got nil")
	}

}