Beispiel #1
0
func main() {
	var err error
	db, err = sqlx.Connect("postgres", "user=postgres password=postgres dbname=messenger sslmode=disable")
	if err != nil {
		log.Fatalln(err)
	}
	CreateSchema(false)

	r := mux.NewRouter()
	authBase := mux.NewRouter()
	apiBase := mux.NewRouter()
	auth := authBase.PathPrefix("/auth").Subrouter()
	api := apiBase.PathPrefix("/api").Subrouter()

	r.PathPrefix("/auth").Handler(negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.Wrap(authBase),
	))

	jwtSecret = "a very secret string"
	// must be authenticated to  use api routes
	jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return []byte(jwtSecret), nil
		},
		SigningMethod: jwt.SigningMethodHS256,
		UserProperty:  "jwt_user",
	})
	r.PathPrefix("/api").Handler(negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
		negroni.Wrap(apiBase),
	))

	// used to check if server is live
	auth.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "pong")
	}).Methods("POST")

	auth.Path("/signup").HandlerFunc(Signup).Methods("POST")
	auth.Path("/login").HandlerFunc(Login).Methods("POST")

	api.Path("/messages").HandlerFunc(NewMessage).Methods("POST")
	api.HandleFunc("/{user}/messages", GetUsersMessages).Methods("GET")

	log.Fatal(http.ListenAndServe(":8080", r))

}
Beispiel #2
0
func main() {

	router := mux.NewRouter()
	router.HandleFunc(xmlEndpoint+"/alerts", func(res http.ResponseWriter, req *http.Request) {
		res.Header().Set("Access-Control-Allow-Origin", "*")
	}).Methods("OPTIONS")

	//router.HandleFunc(xmlEndpoint+"/alerts", alertPost).Methods("POST")
	//router.HandleFunc(xmlEndpoint+"/alerts", alertsGet).Methods("GET")
	router.HandleFunc(xmlEndpoint+"/alerts/{id}", alertGet).Methods("GET")
	router.HandleFunc(jsonEndpoint+"/alerts", alertPostJson).Methods("POST")
	router.HandleFunc(jsonEndpoint+"/alerts", alertsGetJson).Methods("GET")
	router.HandleFunc(jsonEndpoint+"/alerts/{id}", alertGetJson).Methods("GET")
	// router.HandleFunc("/alerts/{id}", alertPost).Methods("POST")

	router.HandleFunc(xmlEndpoint+"/feed", getAtomFeed)

	//router.HandleFunc("/mdc", DrgHandler).Methods("GET")
	// router.HandleFunc("/", HomeHandler)

	n := negroni.New(negroni.NewRecovery(), NewLogger(), negroni.NewStatic(http.Dir("dist")))

	n.UseHandler(router)
	n.Run(qcapListen)
}
Beispiel #3
0
func main() {
	// render
	r := render.New(render.Options{})

	// middleware
	n := negroni.New(
		negroni.NewLogger(),
		negroni.NewRecovery(),
	)

	// database
	sess, err := db.Open(sqlite.Adapter, sqlite.ConnectionURL{
		Database: "test.db",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer sess.Close()

	// router
	router := httprouter.New()

	groupsController := controllers.NewGroupsController(r, sess)
	router.GET("/api/v1/groups.json", groupsController.Index)
	router.POST("/api/v1/groups.json", groupsController.Create)

	n.UseHandler(router)
	n.Run(":" + strconv.Itoa(getPort()))
}
Beispiel #4
0
func (self *API) Serve() error {
	self.router = httprouter.New()

	if err := self.loadRoutes(); err != nil {
		return err
	}

	go func() {
		dc := diecast.NewServer()
		dc.Address = self.Address
		dc.Port = self.Port + 1
		dc.LogLevel = `debug`

		if err := dc.Initialize(); err == nil {
			dc.Serve()
		}
	}()

	self.cors = cors.New(cors.Options{
		AllowedOrigins: []string{`*`},
		AllowedHeaders: []string{`*`},
	})

	self.server = negroni.New()
	self.server.Use(negroni.NewRecovery())
	self.server.Use(self.cors)
	self.server.UseHandler(self.router)

	self.server.Run(fmt.Sprintf("%s:%d", self.Address, self.Port))

	return nil
}
Beispiel #5
0
func main() {
	fmt.Printf("hyperion-dashboard%s\n", buildVersion)

	httpAddr := flag.String("http-address", "127.0.0.1:12300", "<addr>:<port> to listen on")
	dsn := flag.String("db", "", "Database source name")
	flag.Parse()

	dataSource := *dsn
	if dataSource == "" {
		if os.Getenv("HYPERION_DB") != "" {
			dataSource = os.Getenv("HYPERION_DB")
		}
	}

	if dataSource == "" {
		flag.Usage()
		log.Fatal("--db or HYPERION_DB not found")
	}

	db, err := NewDBConn(dataSource)
	if err != nil {
		log.Fatal(err.Error())
	}

	router := mux.NewRouter()
	router.HandleFunc("/", db.RecordsHandler)

	recovery := negroni.NewRecovery()
	logger := negroni.NewLogger()

	n := negroni.New(recovery, logger)
	n.UseHandler(router)
	n.Run(*httpAddr)
}
Beispiel #6
0
func StartServer() {
	rest.P()
	// Log to file
	f, err := os.OpenFile("logs/arkeogis.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalf("Error opening log file: %v", err)
	}
	defer f.Close()
	log.SetOutput(f)
	// Configure Negroni and start server
	Negroni := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(crossDomainMiddleware),
		NewLogger(),
		negroni.NewStatic(http.Dir(config.WebPath)),
	)
	Negroni.UseHandler(routes.MuxRouter)
	/* DEBUG SENDING MAIL
	fmt.Println("SENDING MAIL")
	errrr := mail.Send([]string{"*****@*****.**"}, "pouet", "poeut", "fr")
	if errrr != nil {
		log.Println(errors.ErrorStack(errrr))
	}
	fmt.Println("starting web server...")
	*/
	Negroni.Run(":" + strconv.Itoa(config.Main.Server.Port))
}
Beispiel #7
0
func main() {
	c, err := myrpc.Dial("tcp", checkEnv("VEIL_LISTENER"))
	check(err)
	h := handlers.New(&handlers.H{C: c})
	r := mux.NewRouter()
	r.HandleFunc("/api/version", h.Version).Methods("GET")
	r.HandleFunc("/api/payloads", h.Payloads).Methods("GET")
	r.HandleFunc("/api/options", h.PayloadOptions).Methods("GET")
	r.HandleFunc("/api/generate", h.Generate).Methods("POST")
	n := negroni.New()
	n.Use(negroni.NewLogger())
	n.Use(negroni.NewRecovery())
	n.Use(negroni.NewStatic(http.Dir(checkEnv("VEIL_OUTPUT_DIR"))))
	n.Use(auth.Basic(checkEnv("ADMIN_USER"), checkEnv("ADMIN_PASS")))
	n.Use(negroni.NewStatic(http.Dir("public")))
	n.Use(negroni.HandlerFunc(func(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
		if req.Method != "POST" {
			next(w, req)
			return
		}
		if !strings.Contains(req.Header.Get("content-type"), "application/json") {
			h.JSON400(w, errors.New("Content-Type must be application/json"))
			return
		}
		next(w, req)
	}))
	n.UseHandler(r)
	n.Run(checkEnv("SERVER_LISTENER"))
}
Beispiel #8
0
// New creates a REST API server with a given config
func New(cfg *Config) (*Server, error) {
	// pull a few parameters from the configuration passed in by snapd
	https := cfg.HTTPS
	cpath := cfg.RestCertificate
	kpath := cfg.RestKey
	s := &Server{
		err:        make(chan error),
		killChan:   make(chan struct{}),
		addrString: cfg.Address,
	}
	if https {
		var err error
		s.snapTLS, err = newtls(cpath, kpath)
		if err != nil {
			return nil, err
		}
		protocolPrefix = "https"
	}

	restLogger.Info(fmt.Sprintf("Configuring REST API with HTTPS set to: %v", https))
	s.n = negroni.New(
		NewLogger(),
		negroni.NewRecovery(),
		negroni.HandlerFunc(s.authMiddleware),
	)
	s.r = httprouter.New()
	// Use negroni to handle routes
	s.n.UseHandler(s.r)
	return s, nil
}
Beispiel #9
0
func main() {

	// Config
	// ----------------------------

	// Set the port.
	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}

	// Object Graph
	// ----------------------------
	app := app.Ioc{}
	app.ConfigService = services.NewConfigService()
	app.DatabaseService = services.NewDatabaseService(&app)
	app.DaysController = controllers.NewDaysController(&app)

	// Router
	// ----------------------------
	router := routes.NewRouter(&app)

	// Do we want to use negroni again? Meh ... what about another way to do recovery
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
	)
	n.UseHandler(router)

	// Server
	// ----------------------------
	n.Run(":" + port)

}
Beispiel #10
0
func main() {
	// Setup Routes
	router := httprouter.New()
	router.RedirectTrailingSlash = false
	router.RedirectFixedPath = false

	router.POST("/", func(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
		// simulate API calls, etc...
		time.Sleep(300 * time.Millisecond)
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.Write([]byte("{ \"code\":3.14159265359, \"description\":\"HI!\" }"))
	})

	// Setup Server
	n := negroni.New()
	n.Use(negroni.NewRecovery())
	n.UseHandler(router)

	// start server
	port := os.Getenv("PORT")

	if port == "" {
		port = "3000"
	}

	n.Run(":" + port)
}
Beispiel #11
0
func configureHttpAndListen(config *AppConfig, db gorm.DB) {
	// register routes
	r := render.New(render.Options{})
	h := DBHandler{db: &db, r: r}

	router := mux.NewRouter()

	router.HandleFunc("/api/schedules", h.schedulesIndexHandler).Methods("GET")
	router.HandleFunc("/api/schedules", h.scheduleCreateHandler).Methods("POST")
	router.HandleFunc("/api/schedules/{id:[0-9]+}", h.scheduleShowHandler).Methods("GET")
	router.HandleFunc("/api/schedules/{id:[0-9]+}", h.scheduleUpdateHandler).Methods("PUT", "PATCH")
	router.HandleFunc("/api/schedules/{id:[0-9]+}", h.scheduleDeleteHandler).Methods("DELETE")

	router.HandleFunc("/api/cards", h.cardsIndexHandler).Methods("GET")
	router.HandleFunc("/api/cards", h.cardCreateHandler).Methods("POST")
	router.HandleFunc("/api/cards/{id:[0-9]+}", h.cardShowHandler).Methods("GET")
	router.HandleFunc("/api/cards/{id:[0-9]+}", h.cardUpdateHandler).Methods("PUT", "PATCH")
	router.HandleFunc("/api/cards/{id:[0-9]+}", h.cardDeleteHandler).Methods("DELETE")

	router.HandleFunc("/api/logs", h.logsIndexHandler).Methods("GET")

	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewStatic(http.Dir(config.AssetPath)),
	)

	n.Use(auth.Basic(config.Authentication.Username, config.Authentication.Password))
	n.UseHandler(router)
	n.Run(":" + config.Port)
}
Beispiel #12
0
func NewApp() *App {
	db := newDB()

	// Use negroni for middleware
	ne := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir("public")),
	)

	// Use gorilla/mux for routing
	ro := mux.NewRouter()

	// Set StrictSlash to allow /things/ to automatically redirect to /things
	ro.StrictSlash(true)

	// Use Render for template. Pass in path to templates folder
	// as well as asset helper functions.
	re := render.New(render.Options{
		Layout:     "layouts/layout",
		Extensions: []string{".html"},
	})

	ne.UseHandler(ro)

	return &App{ne, ro, re, db}
}
Beispiel #13
0
Datei: api.go Projekt: DanLB/kala
func StartServer(listenAddr string, cache job.JobCache, db job.JobDB) error {
	r := mux.NewRouter()
	SetupApiRoutes(r, cache, db)
	n := negroni.New(negroni.NewRecovery(), &middleware.Logger{log})
	n.UseHandler(r)
	return http.ListenAndServe(listenAddr, n)
}
Beispiel #14
0
func main() {
	m := martini.Classic()
	m.Get("/", func() string {
		return "Hello world!\n"
	})
	go m.Run()

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Hello world!\n")
	})

	// Use the default middleware.
	n := negroni.New(negroni.NewRecovery())
	// ... Add any other middlware here

	// add the router as the last handler in the stack
	n.UseHandler(mux)
	go n.Run(":3001")

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello world!\n")
	})

	log.Fatal(http.ListenAndServe(":3002", nil))
}
Beispiel #15
0
func main() {
	cfg.MustLoad()
	listeningAddr := ":" + cfg.Server.Port

	router := mux.NewRouter().PathPrefix(cfg.Server.API.Prefix).Subrouter()

	db, err := pg.NewSession(cfg.DB.ConnectionURL())
	if err != nil {
		log.Fatalf("Unable to connect to database: %s", err)
	}

	vars := map[string]interface{}{"db": db}

	err = ctx.Init(router, cfg.Server.API.PrivKey, cfg.Server.API.PubKey, vars)
	if err != nil {
		log.Fatalf("Unable to configure API: %s", err)
	}

	server := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(WebLogger),
		negroni.NewStatic(http.Dir(cfg.Server.Frontend.Path)),
	)
	server.UseHandler(router)

	log.Infof("Listening on address: %s", listeningAddr)
	log.Fatal(http.ListenAndServe(listeningAddr, server))
}
Beispiel #16
0
func main() {

	//init datasotre
	datastore.Connect(true, false)
	defer datastore.Close()

	//define routes
	m := http.NewServeMux()
	m.Handle("/api/", http.StripPrefix("/api", handlers.HandleAPI()))
	m.Handle("/", handlers.HandleWEB())

	//create negroni middleware
	n := negroni.New()
	n.Use(negroni.NewRecovery())
	n.Use(negroni.NewLogger())

	//add security
	n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext))

	//add static content from public folder, index.html, seo files and favicon
	//n.Use(negroni.NewStatic(http.Dir("public")))

	//add application handlers
	n.UseHandler(m)

	//running the server
	n.Run(":8000")
}
Beispiel #17
0
// LaunchServer launches HTTP server
func LaunchServer() {
	router := httprouter.New()
	router.HandlerFunc("GET", "/ping", func(w http.ResponseWriter, req *http.Request) {
		httpWriteJson(w, []byte(`{"msg": "pong"}`))
	})

	// Users handlers
	addUsersHandlers(router)
	// Queue
	addQueueHandlers(router)

	// Microservice data handler
	router.Handler("GET", "/msdata/:id", http.StripPrefix("/msdata/", http.FileServer(http.Dir(core.Cfg.GetTempDir()))))

	// Server
	n := negroni.New(negroni.NewRecovery(), NewLogger())
	n.UseHandler(router)
	addr := fmt.Sprintf("%s:%d", core.Cfg.GetRestServerIp(), core.Cfg.GetRestServerPort())

	// TLS
	if core.Cfg.GetRestServerIsTls() {
		core.Log.Info("httpd " + addr + " TLS launched")
		log.Fatalln(http.ListenAndServeTLS(addr, path.Join(getBasePath(), "ssl/web_server.crt"), path.Join(getBasePath(), "ssl/web_server.key"), n))
	} else {
		core.Log.Info("httpd " + addr + " launched")
		log.Fatalln(http.ListenAndServe(addr, n))
	}
}
Beispiel #18
0
// This function is called from main.go and from the tests
// to create a new application.
func NewApp(root string) *App {

	CheckEnv()

	// Use negroni for middleware
	ne := negroni.New()

	// Use gorilla/mux for routing
	ro := mux.NewRouter()

	// Use Render for template. Pass in path to templates folder
	// as well as asset helper functions.
	re := render.New(render.Options{
		Directory:  filepath.Join(root, "templates"),
		Layout:     "layouts/layout",
		Extensions: []string{".html"},
		Funcs:      []template.FuncMap{AssetHelpers(root)},
	})

	// Establish connection to DB as specificed in database.go
	db := NewDB()

	// Add middleware to the stack
	ne.Use(negroni.NewRecovery())
	ne.Use(negroni.NewLogger())
	ne.Use(NewAssetHeaders())
	ne.Use(negroni.NewStatic(http.Dir("public")))
	ne.UseHandler(ro)

	// Return a new App struct with all these things.
	return &App{ne, ro, re, db}
}
Beispiel #19
0
func New(https bool, cpath, kpath string) (*Server, error) {
	s := &Server{
		err: make(chan error),
	}

	if https {
		var err error
		s.tls, err = newtls(cpath, kpath)
		if err != nil {
			return nil, err
		}
		protocolPrefix = "https"
	}

	restLogger.Info(fmt.Sprintf("Configuring REST API with HTTPS set to: %v", https))

	s.n = negroni.New(
		NewLogger(),
		negroni.NewRecovery(),
	)
	s.r = httprouter.New()
	// Use negroni to handle routes
	s.n.UseHandler(s.r)
	return s, nil
}
Beispiel #20
0
func (s *Server) Start() error {
	n := negroni.New()
	n.Use(cors.New(cors.Options{
		AllowCredentials: true,
	}))
	/*
		n.Use(&rest.CorsMiddleware{
			RejectNonCorsRequests: false,
			OriginValidator: func(origin string, request *rest.Request) bool {
				return true
			},
			AllowedMethods: []string{"GET", "POST"},
			AllowedHeaders: []string{
				"Accept", "Content-Type", "X-Custom-Header", "Origin"},
			AccessControlAllowCredentials: true,
			AccessControlMaxAge:           3600,
		})
	*/
	n.Use(negroni.NewRecovery())
	n.Use(NewLogger())
	n.UseFunc(s.Auth.LoginRequired)
	n.UseHandler(s.Api.Handler())

	s.server = &graceful.Server{
		Timeout: 10 * time.Second,
		Server: &http.Server{
			Addr:    s.Config.BindAddress,
			Handler: n,
		},
	}

	s.listenAndGoServe()

	return nil
}
Beispiel #21
0
// RunServer starts vertice httpd server.
func NewNegHandler() *negroni.Negroni {
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
	})

	m := &delayedRouter{}
	for _, handler := range megdHandlerList {
		m.Add(handler.method, handler.path, handler.h)
	}

	m.Add("Get", "/", Handler(index))
	m.Add("Get", "/logs", Handler(logs))
	m.Add("Get", "/ping", Handler(ping))
	//we can use this as a single click Terminal launch for docker.
	//m.Add("Get", "/apps/{appname}/shell", websocket.Handler(remoteShellHandler))
	n := negroni.New()
	n.Use(negroni.NewRecovery())
	n.Use(c)
	n.Use(newLoggerMiddleware())
	n.UseHandler(m)
	n.Use(negroni.HandlerFunc(contextClearerMiddleware))
	n.Use(negroni.HandlerFunc(flushingWriterMiddleware))
	n.Use(negroni.HandlerFunc(errorHandlingMiddleware))
	n.Use(negroni.HandlerFunc(authTokenMiddleware))
	n.UseHandler(http.HandlerFunc(runDelayedHandler))
	return n
}
// initialize Negroni (middleware, handler)
func initNegroni(handler http.Handler) *negroni.Negroni {
	n := negroni.New()
	n.Use(negroni.NewRecovery())
	n.Use(negroni.NewLogger())
	n.Use(ContentTypeMiddleware())
	n.UseHandler(handler)
	return n
}
Beispiel #23
0
func (a *Context) middlewares() {
	// logger should be first middleware
	a.Negroni.Use(negroni.HandlerFunc(a.reqLog))
	// a.Negroni.Use(h.NewRecovery(log))
	// a.Negroni.Use(negroni.HandlerFunc(cors))
	a.Negroni.Use(negroni.HandlerFunc(options))
	a.Negroni.Use(negroni.NewRecovery())
}
Beispiel #24
0
func (srv *Server) setupNegroni() {
	srv.log.Debug("setting up negroni")
	srv.n = negroni.New()
	srv.n.Use(negroni.NewRecovery())
	srv.n.Use(negronilogrus.NewMiddleware())
	srv.n.Use(negroni.NewStatic(http.Dir("public")))
	srv.n.UseHandler(srv.Router)
}
Beispiel #25
0
// Make sure all global variable prepared
func init() {
	Version = "0.1.0"
	Mode = DebugMode // Default engine mode if not define
	Router = mux.NewRouter()
	Server = negroni.New(negroni.NewRecovery()) // By default recovery included
	Response = NewResponse()
	Bind = NewBind()
}
Beispiel #26
0
func main() {
	// Load the configuration.
	err := envconfig.Process("elwinar", &configuration)
	if err != nil {
		log.Fatalln("unable to read the configuration from env:", err)
	}

	// Open the database connection.
	database, err = sqlx.Connect("sqlite3", configuration.Database)
	if err != nil {
		log.Fatalln("unable to open the database:", err)
	}

	// Initialize the router.
	router := httprouter.New()

	// Add the front-office handlers.
	router.GET("/", Index)
	router.GET("/read", List)
	router.GET("/article/:slug", View)
	router.GET("/fortune", Fortune)
	router.GET("/sitemap.xml", Sitemap)

	// Add the back-office handlers.
	router.GET("/login", Login)
	router.POST("/login", Authenticate)
	router.GET("/logout", Logout)
	router.GET("/write", Write)
	router.POST("/write", Create)
	router.GET("/article/:slug/edit", Edit)
	router.POST("/article/:slug/edit", Update)
	router.GET("/article/:slug/delete", Delete)
	router.GET("/article/:slug/publish", Publish)
	router.GET("/article/:slug/unpublish", Unpublish)

	// Initialize the server middleware stack.
	stack := negroni.New()
	stack.Use(gzip.Gzip(gzip.DefaultCompression))
	stack.Use(negroni.NewRecovery())
	stack.Use(negroni.NewStatic(http.Dir(configuration.Public)))
	stack.Use(sessions.Sessions("elwinar", cookiestore.New([]byte(configuration.Secret))))
	stack.UseHandler(router)

	// Initialize the HTTP server.
	server := &graceful.Server{
		Timeout: 1 * time.Second,
		Server: &http.Server{
			Addr:    fmt.Sprintf(":%d", configuration.Port),
			Handler: stack,
		},
	}

	// Run the server.
	err = server.ListenAndServe()
	if err != nil {
		log.Fatalln("unable to run the server:", err)
	}
}
Beispiel #27
0
func NewApi(store account.Storable, pubsub account.PubSub) *Api {
	api := &Api{router: NewRouter(), auth: auth.NewAuth(store), Events: make(chan Event, DEFAULT_EVENTS_CHANNEL_LEN)}
	api.Storage(store)
	api.PubSub(pubsub)

	api.router.NotFoundHandler(http.HandlerFunc(api.notFoundHandler))
	api.router.AddHandler(RouterArguments{Path: "/", Methods: []string{"GET"}, Handler: homeHandler})

	//  Auth (login, logout, signup)
	api.router.AddHandler(RouterArguments{Path: "/auth/login", Methods: []string{"POST"}, Handler: api.userLogin})
	api.router.AddHandler(RouterArguments{Path: "/auth/logout", Methods: []string{"DELETE"}, Handler: api.userLogout})
	api.router.AddHandler(RouterArguments{Path: "/auth/signup", Methods: []string{"POST"}, Handler: api.userSignup})
	api.router.AddHandler(RouterArguments{Path: "/auth/password", Methods: []string{"PUT"}, Handler: api.userChangePassword})

	// Middlewares
	private := api.router.AddSubrouter("/api")
	api.router.AddMiddleware("/api", negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(api.errorMiddleware),
		negroni.HandlerFunc(api.requestIdMiddleware),
		negroni.HandlerFunc(api.authorizationMiddleware),
		negroni.HandlerFunc(api.contextClearerMiddleware),
		negroni.Wrap(private),
	))

	// Users
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/users", Methods: []string{"DELETE"}, Handler: api.userDelete})

	// Teams
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams", Methods: []string{"POST"}, Handler: authorizationRequiredHandler(api.teamCreate)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams", Methods: []string{"GET"}, Handler: authorizationRequiredHandler(api.teamList)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams/{alias}", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.teamUpdate)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams/{alias}", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.teamDelete)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams/{alias}", Methods: []string{"GET"}, Handler: authorizationRequiredHandler(api.teamInfo)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams/{alias}/users", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.teamAddUsers)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams/{alias}/users", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.teamRemoveUsers)})

	// Services
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services", Methods: []string{"POST"}, Handler: authorizationRequiredHandler(api.serviceCreate)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services", Methods: []string{"GET"}, Handler: authorizationRequiredHandler(api.serviceList)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services/{subdomain}", Methods: []string{"GET"}, Handler: authorizationRequiredHandler(api.serviceInfo)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services/{subdomain}", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.serviceDelete)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services/{subdomain}", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.serviceUpdate)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services/{subdomain}/plugins", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.pluginSubsribe)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services/{subdomain}/plugins/{plugin_name}", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.pluginUnsubsribe)})

	// Apps
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/apps", Methods: []string{"POST"}, Handler: authorizationRequiredHandler(api.appCreate)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/apps/{client_id}", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.appDelete)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/apps/{client_id}", Methods: []string{"GET"}, Handler: authorizationRequiredHandler(api.appInfo)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/apps/{client_id}", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.appUpdate)})

	// Hooks
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/hooks", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.hookSave)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/hooks/{name}", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.hookDelete)})

	return api
}
Beispiel #28
0
func StartServer(listenAddr string, cache job.JobCache, db job.JobDB) error {
	r := mux.NewRouter()
	// Allows for the use for /job as well as /job/
	r.StrictSlash(true)
	SetupApiRoutes(r, cache, db)
	n := negroni.New(negroni.NewRecovery(), &middleware.Logger{log})
	n.UseHandler(r)
	return http.ListenAndServe(listenAddr, n)
}
Beispiel #29
0
func main() {
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(MyMiddleware),
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir("public")),
	)
	n.Run(":8080")
}
Beispiel #30
0
func main() {
	log.Println("Starting...")
	runtime.GOMAXPROCS(runtime.NumCPU())

	r := mux.NewRouter()

	r.HandleFunc("/socket", func(w http.ResponseWriter, req *http.Request) {
		conn, err := upgrader.Upgrade(w, req, nil)
		if err != nil {
			log.Println(err)
			return
		}

		conns = append(conns, conn)
	})

	r.Methods("POST").Path("/switch-mode").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		var post PostBodySwitchMode
		dec := json.NewDecoder(req.Body)
		err := dec.Decode(&post)

		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		switchMode(post.Mode, post.Address)
	})

	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.NewStatic(rice.MustFindBox("public").HTTPBox()),
	)
	n.UseHandler(r)
	listen := os.Getenv("LISTEN")
	if listen == "" {
		listen = ":3000"
	}

	lineCh = make(chan string, 32)

	go func() {
		for line := range lineCh {
			for _, conn := range conns {
				err := conn.WriteMessage(websocket.TextMessage, []byte(line))
				if nil != err {
					log.Println(err)
				}
			}
		}
	}()

	n.Run(listen)
}