Example #1
0
func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}
	host := os.Getenv("HOST")

	templates.Init("templates")
	// models.InitDb(os.Getenv("DATABASE_URL"))
	// addon.Init(os.Getenv("HEROKU_ID"), os.Getenv("HEROKU_API_PASSWORD"), os.Getenv("HEROKU_SSO_SALT"))

	r := mux.NewRouter()

	// new(controllers.AccountsController).Init(r)
	// new(controllers.HerokuResourcesController).Init(r)
	new(controllers.HomeController).Init(r)
	// new(controllers.ImagesController).Init(r)
	new(controllers.TestController).Init(r)
	// new(controllers.SessionsController).Init(r)
	// new(controllers.SsoSessionsController).Init(r)

	r.PathPrefix("/").Handler(http.FileServer(http.Dir("static")))

	n := negroni.Classic()
	n.UseHandler(r)
	n.Run(host + ":" + port)
}
Example #2
0
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", IndexController)
	n := negroni.Classic()
	n.UseHandler(mux)
	n.Run(fmt.Sprintf(":%s", os.Getenv("PORT")))
}
Example #3
0
func Start(port int, fileLocation string) {

	var router routers.Router
	var graph inject.Graph

	// Create database
	db := data.NewJsonDB(fileLocation)

	// Setup DI
	if err := graph.Provide(
		&inject.Object{Value: db},
		&inject.Object{Value: repositories.NewCharacterRepository()},
		&inject.Object{Value: &router}); err != nil {
		log.Fatalf("Error providing dependencies: ", err.Error())
	}

	if err := graph.Populate(); err != nil {
		log.Fatalf("Error populating dependencies: ", err.Error())
	}

	n := negroni.Classic()
	n.UseHandler(router.NewRouter())

	err := http.ListenAndServe(fmt.Sprintf(":%v", port), n)

	if err != nil {
		panic("Error: " + err.Error())
	}
}
Example #4
0
// Serve set the route handlers and serve
func Serve() {
	// Setup middleware
	middle := negroni.Classic()
	store := cookiestore.New([]byte("keyboard cat"))
	middle.Use(sessions.Sessions("hugoku", store))

	router := httprouter.New()
	router.GET("/", routes.Index)
	router.GET("/auth/login", routes.GithubLogin)
	router.GET("/auth/logout", routes.GithubLogout)
	router.GET("/auth/callback", routes.GithubLoginCallback)
	router.GET("/project/:id", routes.GetProject)
	router.POST("/project", routes.PostProject)
	router.DELETE("/project/:id", routes.DeleteProject)
	router.GET("/about", routes.About)
	router.GET("/faq", routes.FAQ)

	// Apply middleware to the router
	middle.UseHandler(router)

	log.Println("Started running on http://127.0.0.1:8080")

	// TODO: Get the port from flag, config file or environment var
	log.Fatal(http.ListenAndServe(":8080", middle))
}
Example #5
0
func New(tug *tugboat.Tugboat, config Config) http.Handler {
	r := mux.NewRouter()

	// auth is a function that can wrap an http.Handler with authentication.
	auth := newAuthenticator(config)

	// Mount GitHub webhooks
	g := github.New(tug, config.GitHub.Secret)
	r.MatcherFunc(githubWebhook).Handler(g)

	// Mount the API.
	a := api.New(tug, api.Config{
		Auth:   auth,
		Secret: config.GitHub.Secret,
	})
	r.Headers("Accept", api.AcceptHeader).Handler(a)

	// Pusher authentication.
	p := auth(&pusherauth.Handler{
		Key:    config.Pusher.Key,
		Secret: []byte(config.Pusher.Secret),
	})
	r.Handle("/pusher/auth", p)

	// Fallback to serving the frontend.
	f := frontend.New("")
	f.PusherKey = config.Pusher.Key
	r.NotFoundHandler = auth(f)

	n := negroni.Classic()
	n.UseHandler(r)

	return n
}
Example #6
0
func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}
	host := os.Getenv("HOST")

	templates.Init("templates")
	models.InitDb(os.Getenv("DATABASE_URL"))
	addon.Init(os.Getenv("HEROKU_ID"), os.Getenv("HEROKU_API_PASSWORD"), os.Getenv("HEROKU_SSO_SALT"))

	rand.Seed(time.Now().UTC().UnixNano())

	r := mux.NewRouter()
	r.SkipClean(true) // have to use whatupdave/mux until Gorilla supports this

	new(controllers.AccountsController).Init(r)
	new(controllers.HerokuResourcesController).Init(r)
	new(controllers.HomeController).Init(r)
	new(controllers.ImagesController).Init(r)
	new(controllers.RegistrationsController).Init(r)
	new(controllers.SessionsController).Init(r)
	new(controllers.SsoSessionsController).Init(r)

	r.PathPrefix("/").Handler(http.FileServer(http.Dir("static")))

	n := negroni.Classic()
	n.UseHandler(r)
	n.Run(host + ":" + port)
}
func StartNegroniServer() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", index)
	n := negroni.Classic()
	n.UseHandler(mux)
	n.Run(":8080")
}
Example #8
0
func Test_LogoutOnAccessTokenExpiration(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := sessions.NewCookieStore([]byte("secret123"))

	n := negroni.Classic()
	n.Use(sessions.Sessions("my_session", s))
	n.Use(Google(
		goauth2.Client("foo", "foo"),
		goauth2.RedirectURL("foo"),
	))

	mux := http.NewServeMux()
	mux.HandleFunc("/addtoken", func(w http.ResponseWriter, req *http.Request) {
		SetToken(req, "dummy token")
		fmt.Fprintf(w, "OK")
	})

	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		tok := GetToken(req)
		if tok != nil {
			t.Errorf("User not logged out although access token is expired. %v\n", tok)
		}
	})
	n.UseHandler(mux)
	addtoken, _ := http.NewRequest("GET", "/addtoken", nil)
	index, _ := http.NewRequest("GET", "/", nil)
	n.ServeHTTP(recorder, addtoken)
	n.ServeHTTP(recorder, index)
}
func Test_SessionsDeleteValue(t *testing.T) {
	n := negroni.Classic()

	store := cookiestore.New([]byte("secret123"))
	n.Use(sessions.Sessions("my_session", store))

	mux := http.NewServeMux()

	mux.HandleFunc("/testsession", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		session.Set("hello", "world")
		session.Delete("hello")
		fmt.Fprintf(w, "OK")
	})

	mux.HandleFunc("/show", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		if session.Get("hello") == "world" {
			t.Error("Session value deleting failed")
		}
		fmt.Fprintf(w, "OK")
	})

	n.UseHandler(mux)

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/testsession", nil)
	n.ServeHTTP(res, req)

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/show", nil)
	req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
	n.ServeHTTP(res2, req2)
}
Example #10
0
File: main.go Project: Ell/uploader
func main() {
	configMiddleware, err := NewConfigMiddleware("config.toml")
	if err != nil {
		panic("Unable to open config file. Please check its path.")
	}

	dbMiddleware, err := NewDatabaseMiddleware("sqlite3", "database.db")
	if err != nil {
		panic("Unable to open database. Please check its path.")
	}

	host := configMiddleware.Host + ":" + strconv.Itoa(configMiddleware.Port)

	r := mux.NewRouter()
	r.HandleFunc("/", indexHandler)
	r.HandleFunc("/upload", uploadHandler)

	n := negroni.Classic()

	n.Use(configMiddleware)
	n.Use(dbMiddleware)

	n.UseHandler(r)

	n.Run(host)
}
Example #11
0
File: main.go Project: Xe/splattus
func main() {
	mux := http.NewServeMux()

	mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
		sd, err := splattus.Lookup()
		if err != nil {
			http.Error(rw, err.Error(), 500)
			return
		}

		data, err := json.Marshal([]string{
			splattus.Englishify(sd[0].Stages[0]),
			splattus.Englishify(sd[0].Stages[1]),
		})
		if err != nil {
			http.Error(rw, err.Error(), 500)
			return
		}

		rw.Write(data)
	})

	n := negroni.Classic()

	n.UseHandler(mux)

	http.ListenAndServe(":5000", n)
}
Example #12
0
func main() {
	// Instantiate a new router
	r := httprouter.New()
	n := negroni.Classic()

	// Get a UserController instance
	//	uc := controllers.NewUserController(getSession())
	//	cc := controllers.NewCustomerController(getSession())
	//
	//	// Get a user resource
	//	r.GET("/user/:id", uc.GetUser)
	//	r.GET("/customer/:id",cc.GetCustomer)
	//
	//	// Create a new user
	//	r.POST("/user", uc.CreateUser)
	//	r.POST("/customer",cc.CreateCustomer)
	//
	//	r.PUT("/customer/:id",cc.UpdateCustomer)
	//
	//	// Remove an existing user
	//	r.DELETE("/user/:id", uc.RemoveUser)
	//	r.DELETE("/customer/:id",cc.RemoveCustomer)

	// Fire up the server
	r.HandlerFunc("GET", "/login", getToken)
	r.Handler("GET", "/api",
		negroni.New(negroni.HandlerFunc(AuthMiddleware1), negroni.HandlerFunc(APIHandler1), negroni.Handler(CreateCustomer1)))
	//	r.Handler("POST","/customer",
	//		negroni.New(negroni.HandlerFunc(AuthMiddleware1),negroni.HandlerFunc(APIHandler1),cc.CreateCustomer))
	n.UseHandler(r)
	http.ListenAndServe("localhost:8080", n)
}
Example #13
0
func main() {
	resolver, err := NewServiceResolver("192.168.99.100:8500")
	if err != nil {
		panic(err)
	}

	fmt.Printf("Starting Colour service....")

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		url, err := resolver.ResolveHttpUrl("name", "")
		if err != nil {
			panic(err)
		}
		resp, err := http.Get(url)
		if err == nil {
			defer resp.Body.Close()
			body, err := ioutil.ReadAll(resp.Body)
			if err == nil {
				svcName := os.Getenv("service-name")
				fmt.Fprintf(w, "Hello, %s! from %s", body, svcName)
				return
			}
		}
		fmt.Fprintf(w, "Hello, unknown!")
	})

	n := negroni.Classic()
	n.UseHandler(mux)
	n.Run(":3000")
}
Example #14
0
func main() {
	mux := http.NewServeMux()
	renderer := render.New(render.Options{
		IndentJSON:    true,
		IsDevelopment: true,
		Funcs:         []template.FuncMap{prepareTemplateMap()},
	})

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			TorrentHandler(w, r, renderer)
		}
	})

	mux.HandleFunc("/showDiskSpace", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			ShowDiskSpaceHandler(w, r)
		}
	})

	mux.HandleFunc("/listDownloads", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			ListDownloadsHandler(w, r, renderer)
		}
	})

	n := negroni.Classic()

	n.UseHandler(mux)
	//n.Run(":3001")
	go func() {
		log.Fatal(http.ListenAndServe(plainPort, http.HandlerFunc(redirectToHTTPS)))
	}()
	log.Fatal(http.ListenAndServeTLS(sslPort, "cert_dietpi.pem", "key_dietpi.pem", n))
}
Example #15
0
func main() {
	if len(os.Args) != 3 {
		fmt.Println("usage: copyweb [dir] [http://weburl(client) or port number(server)]")
		os.Exit(1)
	}
	path := "./" + os.Args[1]
	if strings.HasPrefix(os.Args[2], "http://") {
		if _, err := os.Stat(path); os.IsNotExist(err) {
			os.MkdirAll(path, 0666)
		}
		GetWeb()
	} else {
		if _, err := os.Stat(path); os.IsNotExist(err) {
			fmt.Println("dir ", os.Args[1], " does not exist")
			os.Exit(1)
		}
		port, err := strconv.Atoi(os.Args[2])
		if err != nil || port < 1 || port > 65535 {
			fmt.Println("port number wrong.")
			os.Exit(1)
		}
		if jd, err := ioutil.ReadFile(os.Args[1] + ".map"); err == nil {
			if json.Unmarshal(jd, &mapData) != nil {
				fmt.Println("Loading map file failed")
			}
		}
		var r = mux.NewRouter()
		r.HandleFunc("/{url:.*}", SetWeb)
		n := negroni.Classic()
		n.UseHandler(r)
		n.Run(":" + strconv.Itoa(port))
	}
}
Example #16
0
func NewServer(c *structs.Config) (*Server, error) {

	s := Server{negroni.Classic()}

	session, err := myradio.NewSessionFromKeyFile()

	if err != nil {
		return &s, err
	}

	router := mux.NewRouter()

	getRouter := router.Methods("GET").Subrouter()

	// Routes go in here
	nfc := controllers.NewNotFoundController(c)
	router.NotFoundHandler = http.HandlerFunc(nfc.Get)

	ic := controllers.NewIndexController(session, c)
	getRouter.HandleFunc("/", ic.Get)

	sc := controllers.NewSearchController(session, c)
	getRouter.HandleFunc("/search/", sc.Get)

	showC := controllers.NewShowController(session, c)
	//	getRouter.HandleFunc("/schedule/shows", showC.Get) // @TODO: Implement this
	getRouter.HandleFunc("/schedule/shows/{id:[0-9]+}/", showC.GetShow)

	// End routes

	s.UseHandler(router)

	return &s, nil

}
Example #17
0
func runServer(cnf *config.Config, db *gorm.DB) {
	// Initialise the oauth service
	oauthService := oauth.NewService(cnf, db)

	// Initialise the accounts service
	_ = accounts.NewService(cnf, db, oauthService)

	// Initialise the web service
	_ = web.NewService(cnf, oauthService)

	// Start a classic negroni app
	webApp := negroni.Classic()

	// Create a router instance
	router := mux.NewRouter().StrictSlash(true)

	// Add routes for the oauth package (REST tokens endpoint)
	routes.AddRoutes(oauth.Routes, router.PathPrefix("/api/v1/oauth").Subrouter())

	// Add routes for the web package (register, login authorize web pages)
	routes.AddRoutes(web.Routes, router.PathPrefix("/web").Subrouter())

	// Set the router
	webApp.UseHandler(router)

	// Run the server on port 8080
	webApp.Run(":8080")
}
Example #18
0
func main() {
	n := negroni.Classic()

	n.Use(adapters.NegroniVendorAdapter(routingAPI))
	n.UseHandler(routingAPI.DispatchVersion())
	n.Run(":" + os.Getenv("PORT"))
}
Example #19
0
// Set up the paths and handlers then start serving.
func main() {
	fmt.Println("onthefly ", onthefly.Version)

	// Create a Negroni instance and a ServeMux instance
	n := negroni.Classic()
	mux := http.NewServeMux()

	// Publish the generated SVG as "/circles.svg"
	svgurl := "/circles.svg"
	mux.HandleFunc(svgurl, func(w http.ResponseWriter, req *http.Request) {
		w.Header().Add("Content-Type", "image/svg+xml")
		fmt.Fprint(w, svgPage())
	})

	// Generate a Page that includes the svg image
	page := indexPage(svgurl)
	// Publish the generated Page in a way that connects the HTML and CSS
	page.Publish(mux, "/", "/style.css", false)

	// Handler goes last
	n.UseHandler(mux)

	// Listen for requests at port 3000
	n.Run(":3000")
}
Example #20
0
func main() {
	flag.Parse()

	r := mux.NewRouter()

	r.HandleFunc("/hackernews", func(w http.ResponseWriter, req *http.Request) {
		feed, err := hackernews.GetRssFeed()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		js, err := json.MarshalIndent(feed, " ", " ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.Write(js)
	})

	r.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Dude, it's an API.")
	})

	n := negroni.Classic()
	n.UseHandler(r)
	n.Run(fmt.Sprintf(":%d", *listenAddr))
}
Example #21
0
func main() {
	middleware := stats.New()

	mux := http.NewServeMux()

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("{\"hello\": \"world\"}"))
	})

	mux.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")

		stats := middleware.Data()

		b, _ := json.Marshal(stats)

		w.Write(b)
	})

	n := negroni.Classic()
	n.Use(middleware)
	n.UseHandler(mux)
	n.Run(":3000")
}
Example #22
0
func initiateTests() {
	var router routers.Router
	var graph inject.Graph

	setupTestData()

	db := data.NewJsonDB("../data/testing/testingDB.json")

	if err := graph.Provide(
		&inject.Object{Value: db},
		&inject.Object{Value: repositories.NewCharacterRepository()},
		&inject.Object{Value: &router}); err != nil {
		log.Fatalf("Error providing dependencies: ", err.Error())
	}

	if err := graph.Populate(); err != nil {
		log.Fatalf("Error populating dependencies: ", err.Error())
	}

	n := negroni.Classic()

	n.UseHandler(router.NewRouter())

	ts = httptest.NewServer(n)
}
Example #23
0
func websocketServer() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", websocketHandler)
	n := negroni.Classic()
	n.UseHandler(mux)
	n.Run(baseURL + wsPort)
}
Example #24
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	dbSession := DBConnect(MONGODB_URL)
	DBEnsureIndices(dbSession)

	router := mux.NewRouter().StrictSlash(true)

	api := router.PathPrefix("/api").Subrouter()
	api.HandleFunc("/me", Me).Methods("GET")
	api.HandleFunc("/me", UpdateAccount).Methods("PUT")

	authApi := router.PathPrefix("/auth").Subrouter()
	authApi.HandleFunc("/login", Login).Methods("POST")
	authApi.HandleFunc("/signup", SignUp).Methods("POST")
	authApi.HandleFunc("/facebook", LoginWithFacebook).Methods("POST")
	authApi.HandleFunc("/twitter", LoginWithTwitter).Methods("POST")
	authApi.HandleFunc("/google", LoginWithGoogle).Methods("POST")

	n := negroni.Classic()
	n.Use(JWTMiddleware())
	n.Use(DBMiddleware(dbSession))
	n.Use(ParseFormMiddleware())
	n.UseHandler(router)

	static := router.PathPrefix("/").Subrouter()
	static.Methods("GET").Handler(http.FileServer(http.Dir("../../client")))

	fmt.Println("Launching server at http://localhost" + PORT)
	err := http.ListenAndServe(PORT, n)
	if err != nil {
		fmt.Println(err)
	}
}
Example #25
0
func runServer(cnf *config.Config, db *gorm.DB) {
	// Initialise the health service
	healthService := health.NewService(db)

	// Initialise the oauth service
	oauthService := oauth.NewService(cnf, db)

	// Initialise the web service
	webService := web.NewService(cnf, oauthService)

	// Start a classic negroni app
	app := negroni.Classic()

	// Create a router instance
	router := mux.NewRouter()

	// Add routes for the health service (healthcheck endpoint)
	health.RegisterRoutes(router, healthService)

	// Add routes for the oauth service (REST tokens endpoint)
	oauth.RegisterRoutes(router, oauthService)

	// Add routes for the web package (register, login authorize web pages)
	web.RegisterRoutes(router, webService)

	// Set the router
	app.UseHandler(router)

	// Run the server on port 8080
	app.Run(":8080")
}
Example #26
0
func main() {
	fmt.Println("Starting sample auth...")

	n := negroni.Classic()

	n.Use(sessions.Sessions("mysession", cookiestore.New([]byte("secret12"))))

	n.Use(KeyCloak(&oauth2.Config{
		ClientID:     "grafana",
		ClientSecret: "10b54f7c-a8ed-4a61-abd7-eb993d12367b",
		RedirectURL:  "http://127.0.0.1:8090/oauth2callback",
		Scopes:       []string{"name", "email"}}))

	router := mux.NewRouter()

	router.HandleFunc("/", Home)
	router.HandleFunc("/version", Version)

	router.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "World !")
	})

	n.Use(oauth2.LoginRequired())

	n.UseHandler(router)
	n.Run(":8090")
}
Example #27
0
func newServer(cy *conveyor.Conveyor, c *cli.Context) http.Handler {
	var apiAuth func(http.Handler) http.Handler

	if auth := c.String("auth"); auth != "" {
		parts := strings.Split(auth, ":")
		apiAuth = httpauth.SimpleBasicAuth(parts[0], parts[1])
	} else {
		apiAuth = func(h http.Handler) http.Handler { return h }
	}

	r := mux.NewRouter()
	r.NotFoundHandler = server.NewServer(cy, server.Config{
		APIAuth:      apiAuth,
		GitHubSecret: c.String("github.secret"),
	})

	// Slack webhooks
	if c.String("slack.token") != "" {
		r.Handle("/slack", newSlackServer(cy, c))
	}

	n := negroni.Classic()
	n.UseHandler(r)

	return n
}
Example #28
0
func main() {
	// Render engine
	r := render.New(render.Options{
		Layout: "layout",
	})

	// Handlers
	router := mux.NewRouter()
	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		r.HTML(w, http.StatusOK, "home", nil)
	})
	router.HandleFunc("/about", func(w http.ResponseWriter, req *http.Request) {
		r.HTML(w, http.StatusOK, "about", nil)
	})
	router.HandleFunc("/start", func(w http.ResponseWriter, req *http.Request) {
		time := req.FormValue("time")
		stepsPerMinute, _ := strconv.Atoi(req.FormValue("steps"))
		var hours, minutes, seconds int
		fmt.Sscanf(time, "%d:%d:%d", &hours, &minutes, &seconds)
		fmt.Println(hours, minutes, seconds)
		go startLapse((hours*3600)+(minutes*60)+seconds, stepsPerMinute)
		r.HTML(w, http.StatusOK, "home", nil)
	}).Methods("POST")

	// HTTP Server
	n := negroni.Classic()
	n.UseHandler(router)
	n.Run(":3000")
}
func main() {
	settings.Init()
	router := routers.InitRoutes()
	n := negroni.Classic()
	n.UseHandler(router)
	http.ListenAndServe(":5000", n)
}
Example #30
0
File: main.go Project: Xe/gurren
func main() {
	sl, err := gurren.New([]string{"http://127.0.0.1:9200"}, "test", runtime.NumCPU())
	if err != nil {
		panic(err)
	}

	mux := routes.New()

	// Do handling here

	mux.Get("/", func(rw http.ResponseWriter, r *http.Request) {
		tpl, err := ace.Load("views/layout", "views/index", nil)
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		if err := tpl.Execute(rw, nil); err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}
	})

	n := negroni.Classic()

	middleware.Inject(n)
	n.Use(sl)
	n.UseHandler(mux)

	n.Run(":3000")
}