Example #1
0
func RunServer(c *cli.Context) error {

	// logging middleware
	loggerMw, err := getLoggerMiddleware(c)
	if err != nil {
		return cli.NewExitError(err.Error(), 2)
	}
	// middleware chain
	baseChain := chain.NewChain(loggerMw.MiddlewareFn, cmw.CorsAdapter(cors.Default()))

	// database handler
	dbh, err := getPgWrapper(c)
	if err != nil {
		return cli.NewExitError(err.Error(), 2)
	}
	// http routes
	r := router.NewRouter()
	routes.AddPublication(&publication.Publication{dbh, c.String("version")}, baseChain, r)
	routes.AddAuthor(&publication.Author{dbh, c.String("version")}, baseChain, r)

	// start the server
	log.Printf("Starting modware api web server on port %d\n", c.Int("port"))
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", c.Int("port")), r.Router))
	return nil
}
func ExampleAddChain() {
	c := xhandler.Chain{}

	close := xhandler.CloseHandler
	cors := cors.Default().Handler
	timeout := xhandler.TimeoutHandler(2 * time.Second)
	auth := func(next xhandler.HandlerC) xhandler.HandlerC {
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			if v := ctx.Value("Authorization"); v == nil {
				http.Error(w, "Not authorized", http.StatusUnauthorized)
				return
			}
			next.ServeHTTPC(ctx, w, r)
		})
	}

	c.Add(close, cors, timeout)

	mux := http.NewServeMux()

	// Use c.Handler to terminate the chain with your final handler
	mux.Handle("/", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page!")
	})))

	// Create a new chain from an existing one, and add route-specific middleware to it
	protected := c.With(auth)

	mux.Handle("/admin", protected.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "protected endpoint!")
	})))
}
Example #3
0
// TODO : need to change to init ,this server it should run by core main.
func main() {
	fmt.Println("api server is started ... ", "\n", "port :8182 :443")
	router := NewRouter()
	handler := cors.Default().Handler(router)
	log.Fatal(http.ListenAndServeTLS(":443", "/root/.lego/certificates/paas.jigko.net.crt", "/root/.lego/certificates/paas.jigko.net.key", handler))
	///root/.lego/certificates/paas.jigko.net.crt
}
Example #4
0
func corsHandler() gin.HandlerFunc {
	handler := cors.Default()
	return func(c *gin.Context) {
		handler.HandlerFunc(c.Writer, c.Request)
		c.Next()
	}
}
Example #5
0
func main() {
	//TODO user httproute package
	r := httprouter.New()

	r.GET("/ws/:roomHash/connect/:userHash", model.ConnectToRoom)

	r.GET("/", serveHome)

	r.POST("/users/create", model.UserCreate)

	r.POST("/rooms/create", model.CreateRoom)

	r.GET("/rooms/get", model.GetRooms)
	r.GET("/rooms/users/:roomHash", model.GetRoomUsers)

	r.ServeFiles("/static/*filepath", http.Dir("./static/"))

	flag.Parse()

	handler := cors.Default().Handler(r)

	log.Println("Server running on port: 8000")
	err := http.ListenAndServe(":8000", handler)

	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Example #6
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	fetchFeed()

	e := echo.New()
	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(mw.StripTrailingSlash())
	e.Use(mw.Gzip())
	e.Use(cors.Default().Handler)

	bundle, _ := ioutil.ReadFile("./build/bundle.js")

	// stats
	s := stats.New()
	e.Use(s.Handler)
	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})
	// static files
	e.Static("/public/css", "public/css")
	e.Static("/universal.js", "./build/bundle.js")
	e.Favicon("public/favicon.ico")

	e.Get("/", selfjs.New(runtime.NumCPU(), string(bundle), rss))
	e.Get("/about", selfjs.New(runtime.NumCPU(), string(bundle), loremJSON()))

	e.Get("/api/data", apiFrontPage)
	e.Get("/api/anotherpage", apiAnotherPage)
	go tick()
	fmt.Println("serving at port 3000")
	e.Run(":3000")
}
Example #7
0
func BuildHandler(utilsFunc utils.UtilsFunc, doGzip bool) http.Handler {
	uf = utilsFunc
	mux := http.NewServeMux()

	fs := http.FileServer(httpFs{http.Dir("public")})
	mux.Handle("/css/", fs)
	mux.Handle("/html/", fs)
	mux.Handle("/img/", fs)

	mux.HandleFunc("/", httpRedirect)
	mux.HandleFunc("/js/all.js", httpAllJs)
	mux.HandleFunc("/js/data.json", httpDataJson)
	mux.HandleFunc("/js/jquery.plugin.js", httpJqueryPluginJs)
	mux.HandleFunc("/v2/js/data.json", httpDataJson2)
	mux.HandleFunc("/v2/js/history.json", httpHistoryJson)

	mux.HandleFunc("/config", httpConfig)

	handler := cors.Default().Handler(mux)
	if !doGzip {
		return handler
	}

	return gziphandler.GzipHandler(handler)
}
Example #8
0
func main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "%s <comments-path> <addr>\n", os.Args[0])
		os.Exit(2)
	}
	path = os.Args[1]
	if strings.HasSuffix(path, "/") {
		path = path[:len(path)-1]
	}
	addr = os.Args[2]
	fmt.Println("looking for comments in", path)
	fmt.Println("will listen for http traffic on", addr)

	http.Handle("/", cors.Default().Handler(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				if r.Method == "POST" {
					handlePost(w, r)
				} else {
					handleGet(w, r)
				}
			},
		),
	),
	)
	http.ListenAndServe(addr, nil)
}
Example #9
0
func main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "%s <csv-file> <addr>\n", os.Args[0])
		os.Exit(2)
	}

	csvPath = os.Args[1]
	addr = os.Args[2]

	setupCsv(Subscriber{})

	fmt.Println("CSV file located at", csvPath)
	fmt.Println("listening on", addr)

	http.Handle("/subscribe", cors.Default().Handler(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				if r.Method == "POST" {
					handlePost(w, r)
				} else {
					http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
				}
			},
		),
	))
	http.ListenAndServe(addr, nil)
}
Example #10
0
func StartServer(portNumber int) (err error) {

	mux := http.NewServeMux()

	// Root: Show status of service
	mux.HandleFunc("/", StatusHandler)

	// Convert CX stream into Cytoscape JS
	mux.HandleFunc("/cx2cyjs", Cx2CyjsHandler)

	// Utility to convert network stored in NDEx into Cytoscape.js
	mux.HandleFunc("/ndex2cyjs/", Ndex2CyjsHandler)

	handler := cors.Default().Handler(mux)

	log.Println("Serving cxtool API on port ", portNumber)

	portNumStr := strconv.Itoa(portNumber)

	err = http.ListenAndServe(":"+portNumStr, handler)

	if err != nil {
		log.Fatal("Could not start API server: ", err)
	}

	return nil
}
Example #11
0
/**
 * Main entry point for the web service
 */
func main() {
	lf, _ := os.OpenFile("service.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0777)
	defer lf.Close()
	logger = log.New(lf, "service: ", log.LstdFlags)
	// use below to log to console....
	//logger = log.New(os.Stdout, "logger: ", log.LstdFlags)

	// Load cfg
	logger.Printf("===> pdf-ws staring up <===")
	logger.Printf("Load configuration...")
	viper.SetConfigName("config")
	viper.SetConfigType("yml")
	viper.AddConfigPath(".")
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Printf("Unable to read config: %s", err.Error())
		os.Exit(1)
	}

	// Init DB connection
	logger.Printf("Init DB connection...")
	connectStr := fmt.Sprintf("%s:%s@tcp(%s)/%s?allowOldPasswords=%s", viper.GetString("db_user"), viper.GetString("db_pass"),
		viper.GetString("db_host"), viper.GetString("db_name"), viper.GetString("db_old_passwords"))
	db, err = sql.Open("mysql", connectStr)
	if err != nil {
		fmt.Printf("Database connection failed: %s", err.Error())
		os.Exit(1)
	}
	defer db.Close()

	// Set routes and start server
	mux := httprouter.New()
	mux.GET("/", rootHandler)
	mux.GET("/:pid", pdfGenerate)
	mux.GET("/:pid/status", statusHandler)
	mux.GET("/:pid/download", downloadHandler)
	logger.Printf("Start service on port %s", viper.GetString("port"))

	if viper.GetBool("https") == true {
		crt := viper.GetString("ssl_crt")
		key := viper.GetString("ssl_key")
		log.Fatal(http.ListenAndServeTLS(":"+viper.GetString("port"), crt, key, cors.Default().Handler(mux)))
	} else {
		log.Fatal(http.ListenAndServe(":"+viper.GetString("port"), cors.Default().Handler(mux)))
	}
}
Example #12
0
func init() {
	router := httprouter.New()

	router.OPTIONS("/", api.Options)
	router.GET("/", api.UserInterface)
	router.POST("/bench", api.Boomer)

	http.Handle("/", cors.Default().Handler(router))
}
Example #13
0
func main() {
	fromEmail = os.Getenv("FROMEMAIL")
	emailSendingPasswd = os.Getenv("EMAILSENDINGPASSWD")
	if fromEmail == "" || emailSendingPasswd == "" {
		log.Fatal("FROMEMAIL or EMAILSENDINGPASSWD was not set")
	}
	runtime.GOMAXPROCS(runtime.NumCPU())
	app := NewApplication()
	app.Init()
	e := echo.New()

	e.Use(middleware.HttpLogger())
	e.HTTP2()
	e.SetHTTPErrorHandler(app.errorHandler)
	e.Use(mw.Recover())
	e.Use(mw.Gzip())
	e.StripTrailingSlash()
	e.Use(cors.Default().Handler)
	/* TODO: logs too much
	newrelickey, found := os.LookupEnv("NEWRELICKEY")
	if found == true {
		gorelic.InitNewRelicAgent(newrelickey, "go-register-login", true)
		e.Use(gorelic.Handler())
	}
	*/
	s := stats.New()
	e.Use(s.Handler)

	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})

	e.Favicon("public/favicon.ico")
	e.Static("/public/css", "public/css")
	e.Static("/universal.js", "./build/bundle.js")

	bundle, _ := ioutil.ReadFile("./build/bundle.js")
	user, _ := json.Marshal(domain.User{})

	e.Get("/", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))
	e.Get("/register", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))
	e.Get("/login", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))

	admin := e.Group("/members")
	admin.Use(middleware.CheckAdmin(app.Redis, string(bundle)))
	admin.Get("", selfjs.New(runtime.NumCPU(), string(bundle), app.listUsers()))

	e.Get("/api/users", app.listUsersAPI)
	e.Get("/api/user/:id", app.userAPI)
	e.Get("/verify/:id/:hash", app.verifyEmail)
	e.Post("/register", app.createUser)
	e.Get("/logout", app.logout)
	e.Post("/login", app.login)
	fmt.Println("Starting server at port 3300")
	e.Run(":3300")
}
Example #14
0
func main() {
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("{\"hello\": \"world\"}"))
	})

	// Use default options
	handler := cors.Default().Handler(h)
	http.ListenAndServe(":8080", handler)
}
Example #15
0
func main() {
	r := httprouter.New()
	r.GET("/r/:id", DispatchHandler)
	r.POST("/api/short", CreateShortedURLHandler)
	r.GET("/api/stats/:id", ViewStatisticsHandler)
	r.GET("/api/stats", ListURLHandler)

	handler := cors.Default().Handler(r)
	logging("Starting server %d...", *port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), handler))
}
Example #16
0
// StartHttpServerBlocking is a blocking method which takes an arbritrary number
// of HttpServeables, adds all their routes the http mux and starts a server on
// the configured port and address.
func StartHttpServerBlocking(serveables ...HttpServeable) {
	router := AssembleRouter(serveables...)
	httpPort := conf.Global.UInt("http.port", 8080)
	httpAddress := conf.Global.UString("http.address", "")
	httpListenAddr := fmt.Sprintf("%s:%d", httpAddress, httpPort)
	log.Printf("Trying to http listen on %s", httpListenAddr)
	handler := cors.Default().Handler(router)
	http.Handle("/", handler)
	http.Handle("/metrics", stat.Handler())
	log.Fatal(http.ListenAndServe(httpListenAddr, nil))
}
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", handler)
	mux.HandleFunc("/submit/", submitHandler)

	// cors.Default() setup the middleware with default options being
	// all origins accepted with simple methods (GET, POST). See
	// documentation below for more options.
	handler := cors.Default().Handler(mux)
	http.ListenAndServe("localhost:8081", handler)
}
Example #18
0
func main() {
	log.Println("VERSION: ", VERSION)
	e := echo.New()
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Use(cors.Default().Handler)
	e.Index("public/index.html")
	e.Static("/", "public")

	if len(os.Args) < 2 {
		fmt.Println("\nPlease input callback url.\n  Usage: app.exe [callback_url]")
		os.Exit(0)
	}
	callback_url = os.Args[1]
	//e.Favicon("public/favicon.ico")

	server, err := socketio.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}
	e.Get("/publish/photo", CallbackHandler)
	e.Post("/publish/photo", ReceiveHandler)
	e.Get("/socket.io/", server)

	server.On("connection", func(so socketio.Socket) {
		log.Println("====================== on connection ======================")
		result := make([]interface{}, 12)
		cur, err := r.Table("instacat").OrderBy(r.OrderByOpts{
			Index: r.Desc("time"),
		}).Limit(12).Run(session)
		if err != nil {
			log.Println(err.Error())
		}
		cur.All(&result)
		fmt.Println("Get result over. ")
		err = so.Emit("recent", result)
		if err != nil {
			log.Println(err.Error())
		}
		so.On("disconnect", func() {
			log.Println("on disconnect")
		})

		RealtimeChangefeed(so)
	})

	//go SubscribeTag()
	go sub()
	port := ":3000"
	log.Printf("Starting HTTP service on %s ...", port)
	e.Run(port)

}
Example #19
0
func main() {
	index := resource.NewIndex()

	// configure your resources

	api, err := rest.NewHandler(index)
	if err != nil {
		log.Fatalf("Invalid API configuration: %s", err)
	}

	handler := cors.Default().Handler(api)
	log.Fatal(http.ListenAndServe(":8080", handler))
}
Example #20
0
func main() {

	mx := mux.NewRouter()
	mx.HandleFunc("/{js_filename}.js", ServeJS)
	mx.HandleFunc("/getfiles/callback={callback}", GetFiles)
	mx.HandleFunc("/index", Index)
	mx.HandleFunc("/upload", Upload)

	n := negroni.Classic()
	n.UseHandler(cors.Default().Handler(mx))

	n.Run(":" + os.Getenv("PORT"))
}
Example #21
0
func (r *Router) init() {
	router := mux.NewRouter()

	router.HandleFunc("/", handler)
	r.ComputationController.AddRoutes(router)
	r.ComputeController.AddRoutes(router)

	corsHandler := cors.Default()
	xffmw, _ := xff.Default()
	chain := alice.New(corsHandler.Handler, xffmw.Handler)

	r.router = chain.Then(router)
}
Example #22
0
func main() {
	e := echo.New()
	e.StripTrailingSlash()
	e.Use(middleware.Logger())
	e.Use(middleware.Gzip())
	e.Use(middleware.Recover())
	e.Use(cors.Default().Handler)

	e.Get("/user", getHandlerFunc(models.GetUsers))
	e.Get("/store", getHandlerFunc(models.GetStores))
	e.Get("/deal", getHandlerFunc(models.GetDeals))

	e.Run(":3000")
}
Example #23
0
File: main.go Project: helphone/api
func main() {
	log.Infof("Starting Helphone API service on port %s", port)

	router := service.NewRouter()
	h := service.MuxWrapper{
		IsReady: false,
		Router:  router,
	}

	go manager.Init()

	handler := handlers.CompressHandler(handlers.ProxyHeaders(cors.Default().Handler(h.Router)))
	log.Fatal(http.ListenAndServe(":"+port, handler))
}
Example #24
0
func main() {
	c := xhandler.Chain{}

	// Use default options
	c.UseC(cors.Default().HandlerC)

	mux := http.NewServeMux()
	mux.Handle("/", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("{\"hello\": \"world\"}"))
	})))

	http.ListenAndServe(":8080", mux)
}
Example #25
0
func main() {
	defer glog.Flush()
	flag.Parse()

	if *versionFlag {
		fmt.Printf("cAdvisor version %s (%s)\n", version.Info["version"], version.Info["revision"])
		os.Exit(0)
	}

	setMaxProcs()

	memoryStorage, err := NewMemoryStorage(*argDbDriver)
	if err != nil {
		glog.Fatalf("Failed to connect to database: %s", err)
	}

	sysFs, err := sysfs.NewRealSysFs()
	if err != nil {
		glog.Fatalf("Failed to create a system interface: %s", err)
	}

	containerManager, err := manager.New(memoryStorage, sysFs, *maxHousekeepingInterval, *allowDynamicHousekeeping)
	if err != nil {
		glog.Fatalf("Failed to create a Container Manager: %s", err)
	}

	mux := http.DefaultServeMux
	handler := cors.Default().Handler(mux)
	// Register all HTTP handlers.
	err = cadvisorHttp.RegisterHandlers(mux, containerManager, *httpAuthFile, *httpAuthRealm, *httpDigestFile, *httpDigestRealm)
	if err != nil {
		glog.Fatalf("Failed to register HTTP handlers: %v", err)
	}

	cadvisorHttp.RegisterPrometheusHandler(mux, containerManager, *prometheusEndpoint, nil)

	// Start the manager.
	if err := containerManager.Start(); err != nil {
		glog.Fatalf("Failed to start container manager: %v", err)
	}

	// Install signal handler.
	installSignalHandler(containerManager)

	glog.Infof("Starting cAdvisor version: %s-%s on port %d", version.Info["version"], version.Info["revision"], *argPort)

	addr := fmt.Sprintf("%s:%d", *argIp, *argPort)
	glog.Fatal(http.ListenAndServe(addr, handler))

}
Example #26
0
func main() {
	router := mux.NewRouter()
	router.HandleFunc("/routes/{route}", api.Stops)
	router.HandleFunc("/routes", api.AllStops)
	router.HandleFunc("/vehicles/{route}", api.Vehicles)
	router.HandleFunc("/vehicles", api.AllVehicles)

	n := negroni.New()
	n.Use(gzip.Gzip(gzip.DefaultCompression))
	n.UseHandler(cors.Default().Handler(router))

	go jobs.RunFetch()
	go jobs.RunExpire()

	n.Run(":8048")
}
Example #27
0
func newServerStack(engine *engine.Engine) *negroni.Negroni {
	context := handlers.NewContext(engine)

	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/", context.IndexHandler).Methods("GET")
	router.HandleFunc("/execute", context.ExecuteHandler).Methods("POST")
	router.HandleFunc("/executews", context.ExecuteWSHandler).Methods("GET")
	router.HandleFunc("/info", context.InfoHandler).Methods("GET")

	server := negroni.New(xrequestid.New(16),
		context,
		negronilogrus.NewCustomMiddleware(logrus.InfoLevel, &logrus.JSONFormatter{}, "straitjacket"),
		cors.Default(),
		negroni.NewStatic(http.Dir("public")))
	server.UseHandler(router)
	return server
}
Example #28
0
func init() {
	users = map[string]user{
		"1": user{
			ID:   "1",
			Name: "Wreck-It Ralph",
		},
	}

	// hook into the echo instance to create an endpoint group
	// and add specific middleware to it plus handlers
	g := e.Group("/users")
	g.Use(cors.Default().Handler)

	g.Post("", createUser)
	g.Get("", getUsers)
	g.Get("/:id", getUser)
}
Example #29
0
File: zest.go Project: wid-la/wus
func initApp(z *Zest) error {
	type dependencies struct {
		Router *httptreemux.TreeMux

		Store *infrastructure.GormStore

		SessionCacheInter    *usecases.SessionCacheInter
		PermissionCacheInter *usecases.PermissionCacheInter
		AccountGuestInter    *resources.AccountGuestInter

		RouteDir *usecases.RouteDirectory
		Render   *infrastructure.Render
	}

	d := &dependencies{}
	err := z.Injector.Get(d)
	if err != nil {
		return err
	}

	if z.DatabaseURL != "" {
		err = d.Store.Connect("postgres", z.DatabaseURL)
	} else {
		err = d.Store.Connect("sqlite3", "database.db")
	}
	if err != nil {
		return err
	}

	d.SessionCacheInter.Refresh()
	d.PermissionCacheInter.Refresh()

	d.RouteDir.Register(d.Router)

	z.App.Use(middlewares.NewLogger())
	z.App.Use(middlewares.NewRecovery(d.Render))
	z.App.Use(cors.Default())
	z.App.Use(middlewares.NewSessions(d.AccountGuestInter))

	d.Router.RedirectBehavior = httptreemux.UseHandler

	z.App.UseHandler(d.Router)

	return nil
}
Example #30
0
func Middleware(fn func(http.ResponseWriter, *http.Request), o ServerOptions) http.Handler {
	next := http.Handler(http.HandlerFunc(fn))

	if o.Concurrency > 0 {
		next = throttle(next, o)
	}
	if o.Gzip {
		next = httpgzip.NewHandler(next)
	}
	if o.CORS {
		next = cors.Default().Handler(next)
	}
	if o.ApiKey != "" {
		next = authorizeClient(next, o.ApiKey)
	}

	return validate(defaultHeaders(next))
}