Exemplo n.º 1
0
Arquivo: server.go Projeto: ab22/abcd
// createStaticFilesServer creates a static file server to server all of the
// frontend files (html, js, css, etc).
func (s *Server) createStaticFilesServer() {
	var (
		adminAppPath    = s.cfg.App.Frontend.Admin
		staticFilesPath = path.Join(adminAppPath, "static")
	)

	contextHandler := func(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
		file := path.Join(staticFilesPath, req.URL.Path)

		http.ServeFile(w, req, file)
		return nil
	}

	contextHandler = handlers.HandleHTTPError(contextHandler)
	contextHandler = handlers.GzipContent(contextHandler)
	contextHandler = handlers.NoDirListing(contextHandler)

	handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := context.Background()
		err := contextHandler(ctx, w, req)

		if err != nil {
			log.Printf("static file handler [%s][%s] returned error: %s", req.Method, req.URL.Path, err)
		}
	})

	s.router.
		PathPrefix("/static/").
		Handler(http.StripPrefix("/static/", handler))
}
Exemplo n.º 2
0
Arquivo: server.go Projeto: ab22/abcd
// handleWithMiddlewares applies all middlewares to the specified route. Some
// middleware functions are applied depending on the route's properties, such
// as ValidateAuth and Authorize middlewares. These last 2 functions require
// that the route RequiresAuth() and that RequiredRoles() > 0.
func (s *Server) handleWithMiddlewares(route routes.Route) httputils.ContextHandler {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		serverCtx := context.WithValue(ctx, "cookieStore", s.cookieStore)
		serverCtx = context.WithValue(serverCtx, "route", route)
		serverCtx = context.WithValue(serverCtx, "config", s.cfg)

		h := route.HandlerFunc()
		h = handlers.HandleHTTPError(h)
		h = handlers.GzipContent(h)

		if route.RequiresAuth() {
			if requiredRoles := route.RequiredRoles(); len(requiredRoles) > 0 {
				h = handlers.Authorize(h)
			}

			h = handlers.ValidateAuth(h)
		}

		return h(serverCtx, w, r)
	}
}