Example #1
0
// AddRoutes adds routes to a router instance. If there are middlewares defined
// for a route, a new negroni app is created and wrapped as a http.Handler
func AddRoutes(routes []Route, router *mux.Router) {
	var (
		handler http.Handler
		n       *negroni.Negroni
	)

	for _, route := range routes {
		// Add any specified middlewares
		if len(route.Middlewares) > 0 {
			n = negroni.New()

			for _, middleware := range route.Middlewares {
				n.Use(middleware)
			}

			// Wrap the handler in the negroni app with middlewares
			n.Use(negroni.Wrap(route.HandlerFunc))
			handler = n
		} else {
			handler = route.HandlerFunc
		}

		router.Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(handler)
	}
}
Example #2
0
func Create(port string, env string) http.Handler {
	serverPort = port

	r := mux.NewRouter().PathPrefix("/v1").Subrouter()
	r.Methods("GET").Path("/ws/app/{key}").HandlerFunc(controllers.Join)

	appsRouter := mux.NewRouter().PathPrefix("/v1/apps/{appId}").Subrouter()
	appsRouter.Methods("POST").Path("/events").HandlerFunc(controllers.CreateEvent)

	r.PathPrefix("/apps/{appId}").Handler(negroni.New(
		negroni.HandlerFunc(AuthMiddleware),
		negroni.Wrap(appsRouter),
	))

	n := negroni.New(negroni.HandlerFunc(BaseMiddleware))
	if env == "dev" {
		n.Use(negroni.HandlerFunc(LoggerMiddleware))
	}

	n.UseHandler(r)

	return n
}
Example #3
0
func NewServer(sh chan bool) {
	serverOnce.Do(func() {
		shutdownCh = sh
		flag.Parse()
		go hub.run()
		r := mux.NewRouter()

		var buffer bytes.Buffer
		buffer.WriteString(":")
		buffer.WriteString(core.NewConfig().HttpConfig.Port)

		jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
			ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
				return []byte(core.NewConfig().JWTConfig.Secret), nil
			},
			Debug: true,
			Extractor: jwtmiddleware.FromFirst(jwtmiddleware.FromAuthHeader,
				func(r *http.Request) (string, error) {
					c, err := r.Cookie("Authentication")
					if err != nil {
						return "", err
					}
					authHeaderParts := strings.Split(c.Value, " ")
					if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
						return "", fmt.Errorf("Authorization header format must be Bearer {token}")
					}
					return authHeaderParts[1], nil
				}),

			SigningMethod: jwt.SigningMethodHS256,
		})

		n := negroni.Classic()
		for _, v := range routes {
			if v.auth {
				r.Handle(v.path, negroni.New(
					negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
					negroni.Wrap(http.HandlerFunc(v.handleFunc)),
				)).Methods(v.method)
			} else {
				r.HandleFunc(v.path, v.handleFunc).Methods(v.method)
			}
		}

		n.UseHandler(r)
		server = &graceful.Server{
			Timeout: 10 * time.Second,
			Server: &http.Server{
				Addr:    buffer.String(),
				Handler: n,
			},
			BeforeShutdown: func() bool {
				log.Println("bye")
				return true
			},
		}

		err := server.ListenAndServe()
		if err != nil {
			log.Fatal("ListenAndServe: ", err)
		}
	})
}