Ejemplo n.º 1
0
func main() {
	middle := interpose.New()

	router := mux.NewRouter()
	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, `<h1>Welcome to the public page!</h1><p><a href="/protected/">Rabbit hole</a></p>`)
	})

	middle.UseHandler(router)

	// Now we will define a sub-router that uses the BasicAuth middleware
	// When you call any url starting with the path /protected, you will need to authenticate
	protectedRouter := mux.NewRouter().Methods("GET").PathPrefix("/protected").Subrouter()
	protectedRouter.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the protected page!")
	})

	// Define middleware that pertains to the part of the site protected behind HTTP Auth
	// and add the protected router to the protected middleware
	protectedMiddlew := interpose.New()
	protectedMiddlew.Use(middleware.BasicAuth("john", "doe"))
	protectedMiddlew.UseHandler(protectedRouter)

	// Add the protected middleware and its router to the main router
	router.Methods("GET").PathPrefix("/protected").Handler(protectedMiddlew)

	http.ListenAndServe(":3001", middle)
}
Ejemplo n.º 2
0
func main() {
	configuration := readConfiguration()
	dbSession := DBConnect(configuration.MongodbUrl)
	DBEnsureIndicesAndDefaults(dbSession, configuration.MongodbDatabaseName)

	// handle all requests by serving a file of the same name
	fs := http.Dir(configuration.Webapp)
	fileHandler := http.FileServer(fs)

	// setup routes
	router := mux.NewRouter()

	router.Handle("/", http.RedirectHandler("/webapp/index.html", 302))
	router.PathPrefix("/webapp").Handler(http.StripPrefix("/webapp", fileHandler))

	authRouterBase := mux.NewRouter()
	router.PathPrefix("/auth").Handler(negroni.New(DBMiddleware(dbSession, configuration.MongodbDatabaseName), negroni.Wrap(authRouterBase)))
	authRouter := authRouterBase.PathPrefix("/auth").Subrouter()
	authRouter.HandleFunc("/login", Login).Methods("POST")

	apiRouterBase := mux.NewRouter()
	router.PathPrefix("/api").Handler(negroni.New(DBMiddleware(dbSession, configuration.MongodbDatabaseName), JWTMiddleware(), negroni.Wrap(apiRouterBase)))
	apiRouter := apiRouterBase.PathPrefix("/api").Subrouter()
	apiRouter.HandleFunc("/me", Me).Methods("GET")

	http.ListenAndServe(fmt.Sprintf(":%v", configuration.Port), router)
}
Ejemplo n.º 3
0
// BuildRoutes returns the routes for the application.
func BuildRoutes() http.Handler {
	router := mux.NewRouter()

	router.HandleFunc("/", HomeHandler)
	router.HandleFunc("/login-success", LoginSuccessHandler)
	router.HandleFunc("/verify", VerifyHandler)
	router.HandleFunc("/logout", LogoutHandler)
	router.HandleFunc("/game", GameHandler)

	// profile routes with LoginRequiredMiddleware
	profileRouter := mux.NewRouter()
	profileRouter.HandleFunc("/profile", ProfileHandler)

	router.PathPrefix("/profile").Handler(negroni.New(
		negroni.HandlerFunc(LoginRequiredMiddleware),
		negroni.Wrap(profileRouter),
	))

	// apply the base middleware to the main router
	n := negroni.New(
		negroni.HandlerFunc(CsrfMiddleware),
		negroni.HandlerFunc(UserMiddleware),
	)
	n.UseHandler(router)

	return n
}
Ejemplo n.º 4
0
func main() {
	logger := log.NewLogger()
	cfg := config.Default()
	flag.StringVar(&cfg.WSAddress, "ws", cfg.WSAddress, "Websocket address")
	flag.StringVar(&cfg.RESTAddress, "rest", cfg.RESTAddress, "REST address")
	flag.StringVar(&cfg.Origin, "o", cfg.Origin, "Origin URL")
	file := flag.String("config", "", "Config file")
	flag.Parse()
	if *file != "" {
		err := config.FromFile(*file, &cfg)
		if err != nil {
			logger.Err.Fatal(err)
		}
		flag.Parse()
	}
	broker := pubsub.NewBroker()
	go func() {
		wsRouter := mux.NewRouter()
		wsRouter.Handle("/{id}", handlers.WSHandler{Broker: broker, Config: cfg, Logger: logger})
		logger.Out.Println("Listening websockets on", cfg.WSAddress)
		logger.Err.Fatal(http.ListenAndServe(cfg.WSAddress, wsRouter))
	}()
	go func() {
		restRouter := mux.NewRouter()
		restRouter.Handle("/topic", handlers.List{Broker: broker, Logger: logger}).Methods("GET")
		restRouter.Handle("/topic", handlers.Add{Broker: broker, Logger: logger}).Methods("POST")
		restRouter.Handle("/topic/{id}", handlers.Pub{Broker: broker, Logger: logger}).Methods("POST")
		restRouter.Handle("/topic/{id}", handlers.Del{Broker: broker, Logger: logger}).Methods("DELETE")
		restRouter.Handle("/ping", handlers.Ping{Logger: logger}).Methods("GET")
		logger.Out.Println("Listening REST on", cfg.RESTAddress)
		logger.Err.Fatal(http.ListenAndServe(cfg.RESTAddress, restRouter))
	}()
	wait := make(chan struct{})
	<-wait
}
Ejemplo n.º 5
0
func router(config clientConfig) *mux.Router {
	r := mux.NewRouter()
	r.HandleFunc("/", indexHandler(config))
	r.Handle("/favicon.ico", http.NotFoundHandler())

	authMiddleware := negroni.HandlerFunc(ShotgunAuthMiddleware(config))

	entityRoutes := mux.NewRouter()
	entityRoutes.Path("/{entity_type}/{id:[0-9]+}").HandlerFunc(entityGetHandler(config)).Methods("GET")
	entityRoutes.Path("/{entity_type}/{id:[0-9]+}").HandlerFunc(entityUpdateHandler(config)).Methods("PATCH")
	entityRoutes.Path("/{entity_type}/{id:[0-9]+}").
		HandlerFunc(entityDeleteHandler(config)).Methods("DELETE")
	entityRoutes.Path("/{entity_type}/{id:[0-9]+}/revive").
		HandlerFunc(entityReviveHandler(config)).Methods("POST")
	// entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers").
	// 	HandlerFunc(entityGetFollowersHandler(config)).Methods("GET")
	//entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers").
	//             HandlerFunc(entityAddFollowersHandler(config)).Methods("POST")
	//entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers/{user_type}/{user_id:[0-9]+}").
	//		       HandlerFunc(entityDeleteFollowersHandler(config)).Methods("DELETE")
	entityRoutes.Path("/{entity_type}").HandlerFunc(entityGetAllHandler(config)).Methods("GET")
	entityRoutes.Path("/{entity_type}").HandlerFunc(entityCreateHandler(config)).Methods("POST")

	// Adds auth on the sub router so that / can be accessed freely.
	r.PathPrefix("/{entity_type}").Handler(negroni.New(
		authMiddleware,
		negroni.Wrap(entityRoutes),
	))

	return r
}
Ejemplo n.º 6
0
func main() {
	middle := interpose.New()

	router := mux.NewRouter()
	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, `<h1>Welcome to the public page!</h1><p><a href="/protected/">Rabbit hole</a></p>`)
	})

	middle.UseHandler(router)

	// Now we will define a sub-router that uses the BasicAuth middleware
	// When you call any url starting with the path /protected, you will need to authenticate
	protectedRouter := mux.NewRouter().Methods("GET").PathPrefix("/protected").Subrouter()
	protectedRouter.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the protected page, %s!", context.Get(req, authKey))
	})

	protectedMiddlew := interpose.New()
	protectedMiddlew.Use(middleware.BasicAuthFunc(func(user, pass string, req *http.Request) bool {
		if middleware.SecureCompare(user, "admin") && middleware.SecureCompare(pass, "guessme") {
			context.Set(req, authKey, user)
			return true
		} else {
			return false
		}
	}))
	protectedMiddlew.Use(context.ClearHandler)
	protectedMiddlew.UseHandler(protectedRouter)

	router.Methods("GET").PathPrefix("/protected").Handler(protectedMiddlew)

	http.ListenAndServe(":3001", middle)
}
Ejemplo n.º 7
0
func TestTopicsCreateJson(t *testing.T) {
	initTestDB()
	defer closeTestDB()

	// We try to create a topic for the first time.
	body := "{\"name\":\"mssola\"}"
	reader := strings.NewReader(body)
	req, err := http.NewRequest("POST", "/topics", reader)
	if err != nil {
		t.Fatalf("Expected to be nil: %v", err)
	}
	req.Header.Set("Content-Type", "application/json")
	w := httptest.NewRecorder()

	m := mux.NewRouter()
	m.HandleFunc("/topics", TopicsCreate)
	m.ServeHTTP(w, req)

	var topic Topic
	decoder := json.NewDecoder(w.Body)
	err = decoder.Decode(&topic)
	if err != nil {
		t.Fatalf("Expected to be nil: %v", err)
	}

	var t1 Topic
	err = Db.SelectOne(&t1, "select * from topics")
	if err != nil {
		t.Fatalf("Expected to be nil: %v", err)
	}
	if t1.ID != topic.ID {
		t.Fatalf("Got %v; Expected: %v", t1.ID, topic.ID)
	}
	if t1.Name != topic.Name {
		t.Fatalf("Got %v; Expected: %v", t1.Name, topic.Name)
	}

	// Now let's try it with the same name.
	reader2 := strings.NewReader(body)
	req, err = http.NewRequest("POST", "/topics", reader2)
	if err != nil {
		t.Fatalf("Expected to be nil: %v", err)
	}
	req.Header.Set("Content-Type", "application/json")
	w1 := httptest.NewRecorder()

	m = mux.NewRouter()
	m.HandleFunc("/topics", TopicsCreate)
	m.ServeHTTP(w1, req)

	var resp lib.Response
	decoder = json.NewDecoder(w1.Body)
	err = decoder.Decode(&resp)
	if err != nil {
		t.Fatalf("Expected to be nil: %v", err)
	}
	if resp.Error != "Failed!" {
		t.Fatalf("Got %v; Expected: %v", resp.Error, "Failed!")
	}
}
Ejemplo n.º 8
0
Archivo: muxer.go Proyecto: liyu4/home
// MakeMuxer creates a http.Handler to manage all list operations. If
// a prefix is given, that prefix will be the first part of the
// url. This muxer will provide the following handlers and return a
// RESTful 404 on all others.
//
//  GET     prefix + /        Get all lists.
//  POST    prefix + /        Create a new list.
//
//  GET     prefix + /{key}/  Get the list for the given key.
//  PUT     prefix + /{key}/  Update the list with the given key.
//  DELETE  prefix + /{key}/  Delete the list with the given key.
//
// See the functions related to these urls for more details on what
// each one does and the requirements behind it.
func MakeMuxer(prefix string) http.Handler {
	var m *mux.Router

	// Pass through the prefix if we got one.
	if prefix == "" {
		m = mux.NewRouter()
	} else {
		m = mux.NewRouter().PathPrefix(prefix).Subrouter()
	}

	// Get all lists.
	m.HandleFunc("/", GetAllLists).Methods("GET")

	// Make a new list.
	m.HandleFunc("/", PostList).Methods("POST")

	// Singe list operations.
	m.HandleFunc("/{key}/", GetList).Methods("GET")
	m.HandleFunc("/{key}/", PutList).Methods("PUT")
	m.HandleFunc("/{key}/", DeleteList).Methods("DELETE")

	// Everything else fails.
	m.HandleFunc("/{path:.*}", gorca.NotFoundFunc)

	return m
}
Ejemplo n.º 9
0
Archivo: api.go Proyecto: cncodog/shpd
func (a *Api) Run() error {
	globalMux := http.NewServeMux()

	authRouter := mux.NewRouter()
	authRouter.HandleFunc("/auth/login", a.login).Methods("GET")
	authRouter.HandleFunc("/auth/logout", a.logout).Methods("GET")
	authRouter.HandleFunc("/auth/callback", a.authCallback).Methods("GET")

	apiRouter := mux.NewRouter()

	apiRouter.Handle("/api/domains", a.authRequiredMiddleware(http.HandlerFunc(a.domains))).Methods("GET")
	apiRouter.Handle("/api/domains", a.authRequiredMiddleware(http.HandlerFunc(a.addDomain))).Methods("POST")
	apiRouter.Handle("/api/domains/{prefix:.*}", a.authRequiredMiddleware(http.HandlerFunc(a.removeDomain))).Methods("DELETE")
	apiRouter.HandleFunc("/api/ip", a.getIP).Methods("GET")

	//globalMux.Handle("/api/", apiRouter)
	globalMux.Handle("/api/", apiRouter)
	globalMux.Handle("/auth/", authRouter)

	// global handler
	globalMux.Handle("/", http.FileServer(http.Dir("static")))

	s := &http.Server{
		Addr:    a.listenAddr,
		Handler: context.ClearHandler(globalMux),
	}

	if err := s.ListenAndServe(); err != nil {
		return err
	}

	return http.ListenAndServe(a.listenAddr, context.ClearHandler(globalMux))
}
Ejemplo n.º 10
0
func main() {

	finish := make(chan bool)
	router1 := mux.NewRouter()
	router1.HandleFunc("/keys", handleGetAllKey1).Methods("GET")
	router1.HandleFunc("/keys/{key}", handleGetKey1).Methods("GET")
	router1.HandleFunc("/keys/{key}/{value}", handlePutKey1).Methods("PUT")
	go func() {
		http.ListenAndServe(":3000", router1)
	}()

	router2 := mux.NewRouter()
	router2.HandleFunc("/keys", handleGetAllKey2).Methods("GET")
	router2.HandleFunc("/keys/{key}", handleGetKey2).Methods("GET")
	router2.HandleFunc("/keys/{key}/{value}", handlePutKey2).Methods("PUT")
	go func() {
		http.ListenAndServe(":3001", router2)
	}()

	router3 := mux.NewRouter()
	router3.HandleFunc("/keys", handleGetAllKey3).Methods("GET")
	router3.HandleFunc("/keys/{key}", handleGetKey3).Methods("GET")
	router3.HandleFunc("/keys/{key}/{value}", handlePutKey3).Methods("PUT")
	go func() {
		http.ListenAndServe(":3002", router3)
	}()

	<-finish
}
Ejemplo n.º 11
0
// Start the application
func (a *Application) Run() (errChan chan error) {
	errChan = make(chan error)

	clientMux := mux.NewRouter()
	clientMux.HandleFunc("/status/", a.handlers.StatusHandler)
	clientMux.HandleFunc("/realstatus/", a.handlers.RealStatusHandler)
	clientMux.Handle("/", websocket.Server{Handler: a.handlers.PushSocketHandler,
		Handshake: a.checkOrigin})

	endpointMux := mux.NewRouter()
	endpointMux.HandleFunc("/update/{key}", a.handlers.UpdateHandler)
	endpointMux.HandleFunc("/status/", a.handlers.StatusHandler)
	endpointMux.HandleFunc("/realstatus/", a.handlers.RealStatusHandler)
	endpointMux.HandleFunc("/metrics/", a.handlers.MetricsHandler)

	routeMux := mux.NewRouter()
	routeMux.HandleFunc("/route/{uaid}", a.handlers.RouteHandler)

	// Weigh the anchor!
	go func() {
		clientLn := a.server.ClientListener()
		if a.log.ShouldLog(INFO) {
			a.log.Info("app", "Starting WebSocket server",
				LogFields{"addr": clientLn.Addr().String()})
		}
		clientSrv := &http.Server{
			Handler:  &LogHandler{clientMux, a.log},
			ErrorLog: log.New(&LogWriter{a.log.Logger, "worker", ERROR}, "", 0)}
		errChan <- clientSrv.Serve(clientLn)
	}()

	go func() {
		endpointLn := a.server.EndpointListener()
		if a.log.ShouldLog(INFO) {
			a.log.Info("app", "Starting update server",
				LogFields{"addr": endpointLn.Addr().String()})
		}
		endpointSrv := &http.Server{
			Handler:  &LogHandler{endpointMux, a.log},
			ErrorLog: log.New(&LogWriter{a.log.Logger, "endpoint", ERROR}, "", 0)}
		errChan <- endpointSrv.Serve(endpointLn)
	}()

	go func() {
		routeLn := a.router.Listener()
		if a.log.ShouldLog(INFO) {
			a.log.Info("app", "Starting router",
				LogFields{"addr": routeLn.Addr().String()})
		}
		routeSrv := &http.Server{
			Handler:  &LogHandler{routeMux, a.log},
			ErrorLog: log.New(&LogWriter{a.log.Logger, "router", ERROR}, "", 0)}
		errChan <- routeSrv.Serve(routeLn)
	}()

	return errChan
}
Ejemplo n.º 12
0
func Init(apps map[string]interface{}, router *mux.Router) {
	Applications = apps

	// /echo/* Endpoints
	echoRouter := mux.NewRouter()
	// /* Endpoints
	pageRouter := mux.NewRouter()

	for uri, meta := range Applications {
		switch app := meta.(type) {
		case EchoApplication:
			handlerFunc := func(w http.ResponseWriter, r *http.Request) {
				echoReq := r.Context().Value("echoRequest").(*EchoRequest)
				echoResp := NewEchoResponse()

				if echoReq.GetRequestType() == "LaunchRequest" {
					if app.OnLaunch != nil {
						app.OnLaunch(echoReq, echoResp)
					}
				} else if echoReq.GetRequestType() == "IntentRequest" {
					if app.OnIntent != nil {
						app.OnIntent(echoReq, echoResp)
					}
				} else if echoReq.GetRequestType() == "SessionEndedRequest" {
					if app.OnSessionEnded != nil {
						app.OnSessionEnded(echoReq, echoResp)
					}
				} else {
					http.Error(w, "Invalid request.", http.StatusBadRequest)
				}

				json, _ := echoResp.String()
				w.Header().Set("Content-Type", "application/json;charset=UTF-8")
				w.Write(json)
			}

			if app.Handler != nil {
				handlerFunc = app.Handler
			}

			echoRouter.HandleFunc(uri, handlerFunc).Methods("POST")
		case StdApplication:
			pageRouter.HandleFunc(uri, app.Handler).Methods(app.Methods)
		}
	}

	router.PathPrefix("/echo/").Handler(negroni.New(
		negroni.HandlerFunc(validateRequest),
		negroni.HandlerFunc(verifyJSON),
		negroni.Wrap(echoRouter),
	))

	router.PathPrefix("/").Handler(negroni.New(
		negroni.Wrap(pageRouter),
	))
}
Ejemplo n.º 13
0
// NewRouter will return the router specified by the server
// config. If no Router value is supplied, the server
// will default to using Gorilla mux.
func NewRouter(cfg *Config) Router {
	switch cfg.RouterType {
	case "fast", "httprouter":
		return &FastRouter{httprouter.New()}
	case "gorilla":
		return &GorillaRouter{mux.NewRouter()}
	default:
		return &GorillaRouter{mux.NewRouter()}
	}
}
Ejemplo n.º 14
0
func (a *ApiTestSuite) TestSetupApiRoutes() {
	db := &job.MockDB{}
	cache := job.NewMockCache()
	r := mux.NewRouter()

	SetupApiRoutes(r, cache, db)

	a.NotNil(r)
	a.IsType(r, mux.NewRouter())
}
Ejemplo n.º 15
0
func main() {
	ren := render.New(render.Options{
		Layout:        "shared/layout",
		IsDevelopment: true,
	})

	//sessions
	store := cookiestore.New([]byte("secret"))

	//db
	// db, err := sqlx.Connect("postgres", os.Getenv("CONNECTIONSTRING"))
	db, err := sqlx.Connect("postgres", "user=travisjones dbname=cm_app sslmode=disable")
	if err != nil {
		log.Println("Error initializing database...")
		log.Fatalln(err)
	}

	c := ctx{db, ren}

	n := negroni.New()
	nauth := negroni.New()

	//routers
	router := mux.NewRouter()
	authRouter := mux.NewRouter()

	//AUTHORIZED ROUTES
	authRouter.HandleFunc("/", c.Home)
	router.Handle("/", nauth).Methods("GET")

	//OPEN ROUTES
	router.HandleFunc("/account/login", c.Login).Methods("GET")
	router.HandleFunc("/account/login", c.LoginPost).Methods("POST")
	router.HandleFunc("/account/signup", c.Signup).Methods("GET")
	router.HandleFunc("/account/signup", c.SignupPost).Methods("POST")
	router.HandleFunc("/account/logout", c.Logout).Methods("GET")

	//Middleware
	nauth.Use(negroni.HandlerFunc(RequireAuth))
	nauth.UseHandler(authRouter)

	//Sessions
	n.Use(sessions.Sessions("authex", store))

	n.Use(negroni.NewStatic(http.Dir("public")))

	n.UseHandler(router)

	n.Run(
		fmt.Sprint(":", os.Getenv("PORT")),
	)

}
Ejemplo n.º 16
0
func main() {
	flag.Parse()

	store.Init()

	p := func(name string, handler http.HandlerFunc) http.Handler {
		return prometheus.InstrumentHandler(name, handler)
	}

	router := mux.NewRouter()
	router.Handle("/metrics", prometheus.Handler())
	router.Handle("/", p("/", home))
	router.Handle("/login", p("/login", login))
	router.Handle("/verify", p("/verify", verify))

	apiRouter := mux.NewRouter()
	apiRouter.Handle("/api/logout", p("/logout", logout))
	apiRouter.Handle("/api/user", p("/user", user))
	apiRouter.Handle("/api/user/project", p("/user/project", userProject))
	apiRouter.Handle("/api/project", p("/project", project))
	apiRouter.Handle("/api/project/member", p("/task/member", member))
	apiRouter.Handle("/api/task", p("/task", task))
	apiRouter.Handle("/api/task/worker", p("/task/worker", worker))
	apiRouter.Handle("/api/milestone", p("/milestone", milestone))
	apiRouter.Handle("/api/friend", p("/friend", friend))
	apiRouter.Handle("/api/chat", p("/chat", chat))
	apiRouter.HandleFunc("/api/ws", ws)
	router.PathPrefix("/api").Handler(negroni.New(
		negroni.HandlerFunc(apiMiddleware),
		negroni.Wrap(apiRouter),
	))

	adminRouter := mux.NewRouter()
	adminRouter.Handle("/api/admin/user", p("/admin/user", adminUser))
	adminRouter.Handle("/api/admin/project", p("/admin/project", adminProject))
	router.PathPrefix("/api/admin").Handler(negroni.New(
		negroni.HandlerFunc(adminMiddleware),
		negroni.Wrap(adminRouter),
	))

	go h.run()

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

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	n.Run(":" + port)
}
Ejemplo n.º 17
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))

}
Ejemplo n.º 18
0
func main() {
	middle := interpose.New()

	// First call middleware that may manipulate HTTP headers, since
	// they must be called before the HTTP body is manipulated

	// Using Gorilla framework's combined logger
	middle.Use(middleware.GorillaLog())

	//Using Negroni's Gzip functionality
	middle.Use(middleware.NegroniGzip(gzip.DefaultCompression))

	// Now call middleware that can manipulate the HTTP body

	// Define the router. Note that we can add the router to our
	// middleware stack before we define the routes, if we want.
	router := mux.NewRouter()
	middle.UseHandler(router)

	// Configure our router
	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})

	// Define middleware that will apply to only some routes
	greenMiddle := interpose.New()

	// Tell the main router to send /green requests to our subrouter.
	// Again, we can do this before defining the full middleware stack.
	router.Methods("GET").PathPrefix("/green").Handler(greenMiddle)

	// Within the secondary middleware, just like above, we want to call anything that
	// will modify the HTTP headers before anything that will modify the body
	greenMiddle.UseHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		rw.Header().Set("X-Favorite-Color", "green")
	}))

	// Finally, define a sub-router based on our love of the color green
	// When you call any url such as http://localhost:3001/green/man , you will
	// also see an HTTP header sent called X-Favorite-Color with value "green"
	greenRouter := mux.NewRouter().Methods("GET").PathPrefix("/green").Subrouter() //Headers("Accept", "application/json")
	greenMiddle.UseHandler(greenRouter)

	greenRouter.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, green %s!", mux.Vars(req)["user"])
	})

	http.ListenAndServe(":3001", middle)
}
Ejemplo n.º 19
0
func main() {
	flag.Parse()

	markers = make(map[string]map[string]string)
	portString := strconv.Itoa(port)

	stop := make(chan bool)
	go func() {
		for {
			select {
			case <-time.After(1 * time.Second):
				update()
			case <-stop:
				return
			}
		}
	}()

	r := mux.NewRouter()
	r.HandleFunc("/gps", gps)
	http.Handle("/", &CorsServer{r})
	fmt.Printf("bus-server listening on port %s\n", portString)
	err := http.ListenAndServe(":"+portString, nil)
	if err != nil {
		panic(err)
	}
}
Ejemplo n.º 20
0
func Main() {
	config = LoadConfig()
	BaseUrl = config.BaseUrl
	ArticlePrefix = config.ArticlePrefix

	log.LogTo(config.LogTo, config.LogLevel)
	logger = log.NewPrefixLogger("MAIN")

	db = newDb()
	defer db.Close()

	artclesPath := fmt.Sprintf("/%s", ArticlePrefix)
	articlePath := fmt.Sprintf("/%s/{source_slug}/{article_slug}/{article_id:[0-9]+}", ArticlePrefix)

	r := mux.NewRouter()
	r.HandleFunc(articlePath, serve(articleHandler)).Methods("GET")
	r.HandleFunc(articlePath, serve(reFetchArticleHandler)).Methods("PUT")
	r.HandleFunc(artclesPath, serve(articlesHandler)).Methods("GET")
	r.NotFoundHandler = http.HandlerFunc(unknownHandler)

	port := "8080" //os.Getenv("PORT")

	logger.Info("Listening on port %s\n", port)
	http.ListenAndServe(":"+port, r)
}
Ejemplo n.º 21
0
func CreateRouter(server contracts.Server) (*mux.Router, error) {
	r := mux.NewRouter()
	m := map[string]map[string]HttpApiFunc{
		"GET": {
			"/replays/{id:[0-9]+}": server.GetReplay,
		},
		"POST": {
			"/join":   server.JoinMatch,
			"/create": server.CreateMatch,
			"/start":  server.StartMatch,
		},
	}

	for method, routes := range m {
		for route, handler := range routes {
			localRoute := route
			localHandler := handler
			localMethod := method
			f := makeHttpHandler(localMethod, localRoute, localHandler)

			r.Path(localRoute).Methods(localMethod).HandlerFunc(f)
		}
	}

	return r, nil
}
Ejemplo n.º 22
0
func MakeTestServer(repository matchRepository) *negroni.Negroni {
	server := negroni.New() // don't need all the middleware here or logging.
	mx := mux.NewRouter()
	initRoutes(mx, formatter, repository)
	server.UseHandler(mx)
	return server
}
Ejemplo n.º 23
0
func (t Twilio) Handler() *mux.Router {
	m := mux.NewRouter()
	m.Path("/sms").HandlerFunc(sms)
	m.Path("/call/inbound").HandlerFunc(inboundCall)
	m.Path("/call/outbound").HandlerFunc(outboundCall)
	return m
}
Ejemplo n.º 24
0
func main() {

	// configure the github oauth parameters
	config := &auth.GitHubConfig{
		&auth.Config{
			ClientID:     os.Getenv("GITHUB_CLIENT_ID"),
			ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
			CallbackURL:  os.Getenv("GITHUB_CALLBACK_URL"),
		},
	}
	auth.SetGitHubConfig(config)

	// setup a store, in our case one using secure cookies
	store := sessions.NewCookieStore([]byte("something-very-secret"))
	s := auth.NewServer(store)

	// configure a mux
	r := mux.NewRouter()
	r.PathPrefix(auth.PathPrefix).Handler(s.GetMux())

	// add a wrapper to check the session for each request
	o := auth.CheckSession(r, store)

	// listen to the network
	http.ListenAndServe(":5000", o)
}
Ejemplo n.º 25
0
// setupTestServer creates a listener for the rest requests.
func setupTestServer() {

	router := mux.NewRouter()

	// register handlers for cni
	t := router.Headers("Content-Type", "application/json").Methods("POST").Subrouter()
	t.HandleFunc(cniapi.EPAddURL, httpWrapper(stubAddPod))
	t.HandleFunc(cniapi.EPDelURL, httpWrapper(stubDeletePod))

	driverPath := cniapi.ContivCniSocket
	os.Remove(driverPath)
	os.MkdirAll(cniapi.PluginPath, 0700)

	go func() {
		l, err := net.ListenUnix("unix", &net.UnixAddr{Name: driverPath, Net: "unix"})
		if err != nil {
			panic(err)
		}

		logger.Infof("k8s test plugin listening on %s", driverPath)
		http.Serve(l, router)
		l.Close()
		logger.Infof("k8s test plugin closing %s", driverPath)
	}()

}
Ejemplo n.º 26
0
func setupDaemon(port int) {

	router := mux.NewRouter()
	router.HandleFunc("/", HomeHandler)
	http.Handle("/", router)
	http.Handle("/static/", http.FileServer(http.Dir(".")))

	restHandler := rest.ResourceHandler{}

	restHandler.SetRoutes(
		rest.Route{"GET", "/api/test", RestTest},
	)

	restHandler.EnableGzip = true
	restHandler.EnableLogAsJson = true
	restHandler.EnableResponseStackTrace = true
	restHandler.EnableStatusService = true

	http.Handle("/api/", &restHandler)

	err := http.ListenAndServe(fmt.Sprintf(":%d", port), handlers.CombinedLoggingHandler(os.Stdout, http.DefaultServeMux))

	if err != nil {
		log.Fatalln(err)
	}

}
Ejemplo n.º 27
0
func TestReportPostHandler(t *testing.T) {
	test := func(contentType string, encoder func(interface{}) ([]byte, error)) {
		router := mux.NewRouter()
		c := app.NewCollector(1 * time.Minute)
		app.RegisterReportPostHandler(c, router)
		ts := httptest.NewServer(router)
		defer ts.Close()

		b, err := encoder(fixture.Report)
		if err != nil {
			t.Fatalf("Content-Type %s: %s", contentType, err)
		}

		req, err := http.NewRequest("POST", ts.URL+"/api/report", bytes.NewReader(b))
		if err != nil {
			t.Fatalf("Error posting report: %v", err)
		}
		req.Header.Set("Content-Type", contentType)

		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			t.Fatalf("Error posting report %v", err)
		}

		_, err = ioutil.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			t.Fatalf("Error posting report: %v", err)
		}

		if resp.StatusCode != http.StatusOK {
			t.Fatalf("Error posting report: %d", resp.StatusCode)
		}

		ctx := context.Background()
		report, err := c.Report(ctx)
		if err != nil {
			t.Error(err)
		}
		if want, have := fixture.Report.Endpoint.Nodes, report.Endpoint.Nodes; len(have) == 0 || len(want) != len(have) {
			t.Fatalf("Content-Type %s: %v", contentType, test.Diff(have, want))
		}
	}

	test("", func(v interface{}) ([]byte, error) {
		buf := &bytes.Buffer{}
		err := gob.NewEncoder(buf).Encode(v)
		return buf.Bytes(), err
	})
	test("application/json", func(v interface{}) ([]byte, error) {
		buf := &bytes.Buffer{}
		err := codec.NewEncoder(buf, &codec.JsonHandle{}).Encode(v)
		return buf.Bytes(), err
	})
	test("application/msgpack", func(v interface{}) ([]byte, error) {
		buf := &bytes.Buffer{}
		err := codec.NewEncoder(buf, &codec.MsgpackHandle{}).Encode(v)
		return buf.Bytes(), err
	})
}
Ejemplo n.º 28
0
func setupRoutes(cfg config.WebConfig) {
	log.LogInfo("Theme templates mapped to '%v'", cfg.TemplateDir)
	log.LogInfo("Theme static content mapped to '%v'", cfg.PublicDir)

	r := mux.NewRouter()
	// Static content
	r.PathPrefix("/public/").Handler(http.StripPrefix("/public/",
		http.FileServer(http.Dir(cfg.PublicDir))))

	// Root
	r.Path("/").Handler(handler(RootIndex)).Name("RootIndex").Methods("GET")
	r.Path("/status").Handler(handler(RootStatus)).Name("RootStatus").Methods("GET")
	r.Path("/link/{name}/{id}").Handler(handler(MailboxLink)).Name("MailboxLink").Methods("GET")
	r.Path("/mailbox").Handler(handler(MailboxIndex)).Name("MailboxIndex").Methods("GET")
	r.Path("/mailbox/{name}").Handler(handler(MailboxList)).Name("MailboxList").Methods("GET")
	r.Path("/mailbox/{name}").Handler(handler(MailboxPurge)).Name("MailboxPurge").Methods("DELETE")
	r.Path("/mailbox/{name}/{id}").Handler(handler(MailboxShow)).Name("MailboxShow").Methods("GET")
	r.Path("/mailbox/{name}/{id}/html").Handler(handler(MailboxHtml)).Name("MailboxHtml").Methods("GET")
	r.Path("/mailbox/{name}/{id}/source").Handler(handler(MailboxSource)).Name("MailboxSource").Methods("GET")
	r.Path("/mailbox/{name}/{id}").Handler(handler(MailboxDelete)).Name("MailboxDelete").Methods("DELETE")
	r.Path("/mailbox/dattach/{name}/{id}/{num}/{file}").Handler(handler(MailboxDownloadAttach)).Name("MailboxDownloadAttach").Methods("GET")
	r.Path("/mailbox/vattach/{name}/{id}/{num}/{file}").Handler(handler(MailboxViewAttach)).Name("MailboxViewAttach").Methods("GET")

	// Register w/ HTTP
	Router = r
	http.Handle("/", Router)
}
Ejemplo n.º 29
0
func main() {
	dbHost := flag.String("dbhost", "localhost", "the database host")
	dbPort := flag.Int("dbport", 5432, "the database port")
	dbUser := flag.String("dbuser", "aclapp", "the database user")
	dbSsl := flag.Bool("dbssl", false, "database ssl config")
	dbName := flag.String("dbname", "acl", "the database name")
	dbPassword := flag.String("dbpass", "", "database password")
	flag.Parse()
	config := pgmapper.DefaultConfig()
	config.Host = *dbHost
	config.Port = *dbPort
	config.User = *dbUser
	config.Ssl = *dbSsl
	config.Database = *dbName
	config.Password = *dbPassword
	r := mux.NewRouter()
	mapper, err := pgmapper.New(config)
	if err != nil {
		log.Fatal(err)
	}
	objectIdExtractor := idextractor.MuxIdExtractor("objectId")
	userIdExtractor := idextractor.MuxIdExtractor("userId")
	r.Methods("POST").Path("/objects").Handler(jwtware.New(addObjectHandler(mapper)))
	r.Methods("DELETE").Path("/objects/{objectId}").Handler(jwtware.New(deleteObjectHandler(mapper, objectIdExtractor)))
	r.Methods("GET").Path("/objects/{objectId}/permissions/{userId}").Handler(jwtware.New(getPermissionsHandler(mapper, objectIdExtractor, userIdExtractor)))
	r.Methods("PUT").Path("/objects/{objectId}/permissions").Handler(jwtware.New(upsertPermissionsHandler(mapper, objectIdExtractor)))
	r.Methods("PUT").Path("/sids/{sid}/permissions").Handler(jwtware.New(upsertMultiplePermissionsHandler(mapper, idextractor.MuxIdExtractor("sid"))))
	log.Println("listening on 8080")
	http.ListenAndServe(":8080", r)
}
Ejemplo n.º 30
0
//Start starts the c2b api server
//starts the callback listener
func (c2b *C2B) Start() {

	r := mux.NewRouter()
	r.HandleFunc("/", c2b.useMiddleware(
		common.CheckHeader(),
	))
	r.HandleFunc("/{code}", c2b.useMiddleware(
		common.CheckHeader(),
	))

	go func() {
		server.ListenAndServe(c2b.address, r)
	}()

	go func() {
		for {
			select {
			case trx := <-c2b.callback:
				if trx == nil {
					return
				}
				fmt.Println("Delaying by:", c2b.config.CallBackDelay)
				time.Sleep(time.Second * time.Duration(c2b.config.CallBackDelay))
				c2b.callClientCallBack(trx)
			}
		}
	}()

	fmt.Println("C2B started: ", c2b.address)
}