func main() { var wg sync.WaitGroup wg.Add(3) go func() { n := negroni.New() fmt.Println("Launching server on :3000") graceful.Run(":3000", 0, n) fmt.Println("Terminated server on :3000") wg.Done() }() go func() { n := negroni.New() fmt.Println("Launching server on :3001") graceful.Run(":3001", 0, n) fmt.Println("Terminated server on :3001") wg.Done() }() go func() { n := negroni.New() fmt.Println("Launching server on :3002") graceful.Run(":3002", 0, n) fmt.Println("Terminated server on :3002") wg.Done() }() fmt.Println("Press ctrl+c. All servers should terminate.") wg.Wait() }
func main() { middle := interpose.New() // Tell the browser which server this came from. // This modifies headers, so we want this to be called before // any middleware which might modify the body (in HTTP, the headers cannot be // modified after the body is modified) middle.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("X-Server-Name", "Interpose Test Server") next.ServeHTTP(rw, req) }) }) // Apply the router. By adding it last, all of our other middleware will be // executed before the router, allowing us to modify headers before any // output has been generated. router := mux.NewRouter() middle.UseHandler(router) router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) // Launch and permit graceful shutdown, allowing up to 10 seconds for existing // connections to end graceful.Run(":3001", 10*time.Second, middle) }
func main() { flag.Parse() listen := fmt.Sprintf(":%s", *port) router := mux.NewRouter() // static files root, _ := os.Getwd() router.PathPrefix("/static").Handler(http.StripPrefix("/static", http.FileServer(http.Dir(path.Join(root, "public"))))) // web routes router.PathPrefix("/").Handler(tarabish.BuildRoutes()) // setup server var handler http.Handler // if Debug is true, enable logging if os.Getenv("DEBUG") == "true" { log.SetLevel(log.DebugLevel) handler = handlers.CombinedLoggingHandler(os.Stdout, router) } else { handler = router } log.WithFields(log.Fields{ "listen": listen, }).Info("Server running") graceful.Run(listen, 10*time.Second, handler) }
func main() { mw := interpose.New() // Turn on output buffering. It's added first because it encapsulates all other output. // This enables headers to be written after data is sent, because they're all stored // in a buffer, so the user's browser will see everything in the order it expects. mw.Use(middleware.Buffer()) // Tell the browser our output will be JSON. Note that because this is added // before the router, we will write JSON headers AFTER the router starts // writing output to the browser! Usually this would mean that the header would // not get set correctly. However, because we are buffering (see below), // nothing will get sent to the browser until all output is finished rendering. // This means that the header will get set correctly. mw.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") next.ServeHTTP(w, req) }) }) // Apply the router. router := mux.NewRouter() router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) mw.UseHandler(router) // Launch and permit graceful shutdown, allowing up to 10 seconds for existing // connections to end graceful.Run(":3001", 10*time.Second, mw) }
func main() { mw := interpose.New() // Use unrolled's secure framework // If you inspect the headers, you will see X-Frame-Options set to DENY // Must be called before the router because it modifies HTTP headers secureMiddleware := secure.New(secure.Options{ FrameDeny: true, }) mw.Use(secureMiddleware.Handler) // Apply the router. By adding it first, all of our other middleware will be // executed before the router, allowing us to modify headers before any // output has been generated. router := mux.NewRouter() mw.UseHandler(router) router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) // Launch and permit graceful shutdown, allowing up to 10 seconds for existing // connections to end graceful.Run(":3001", 10*time.Second, mw) }
func main() { mw := interpose.New() // Set a random integer everytime someone loads the page mw.Use(context.ClearHandler) mw.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { c := rand.Int() fmt.Println("Setting ctx count to:", c) context.Set(req, CountKey, c) next.ServeHTTP(w, req) }) }) // Apply the router. router := mux.NewRouter() router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { c, ok := context.GetOk(req, CountKey) if !ok { fmt.Println("Get not ok") } fmt.Fprintf(w, "Welcome to the home page, %s!\nCount:%d", mux.Vars(req)["user"], c) }) mw.UseHandler(router) // Launch and permit graceful shutdown, allowing up to 10 seconds for existing // connections to end graceful.Run(":3001", 10*time.Second, mw) }
func main() { var ( addr = flag.String("addr", ":8080", "endpoint address") mongo = flag.String("mongo", "localhost", "mongodb address") ) log.Println("Dialing mongo", *mongo) db, err := mgo.Dial(*mongo) if err != nil { log.Fatalln("failed to connect to mongo:", err) } defer db.Close() mux := http.NewServeMux() mux.HandleFunc("/polls/", withCORS(withVars(withData(db, withAPIKey(handlePolls))))) log.Println("Starting web server on", *addr) graceful.Run(*addr, 1*time.Second, mux) log.Println("Stopping...") }
func main() { var ( addr = flag.String("addr", ":8080", "エンドポイントのアドレス") mongo = flag.String("mongo", "localhost", "MongoDBのアドレス") ) flag.Parse() log.Println("MongoDB に接続します", *mongo) db, err := mgo.Dial(*mongo) if err != nil { log.Fatalln("MongoDB への接続に失敗しました:", err) } defer db.Close() mux := http.NewServeMux() mux.HandleFunc("/polls/", withCORS(withVars(withData(db, withAPIKey(handlePolls))))) log.Println("Webサーバを開始します:", *addr) graceful.Run(*addr, 1*time.Second, mux) log.Println("停止します...") }
func main() { l := log.New(os.Stdout, "[cuddled] ", 0) e := log.New(os.Stderr, "[cuddled] ", 0) // define flags debug := flag.Bool("debug", false, "print debug messages") help := flag.Bool("help", false, "print help") portname := flag.String("port", "/dev/ttyUSB0", "the serial port name") listenaddr := flag.String("listen", ":http", "the address on which to listen") // parse flags flag.Parse() // print help if *help { flag.Usage() os.Exit(0) } // do not accept arguments if flag.NArg() > 0 { flag.Usage() os.Exit(1) } // connect serial port port, err := cuddle.OpenPort(*portname) if err != nil { e.Fatalln(err) } defer port.Close() l.Println("Connected to", *portname) // update setpoints in background go cuddle.SendQueuedMessagesTo(port) // set debug cuddle.Debug = *debug // create server instance mux := cuddle.New() // run with graceful shutdown graceful.Run(*listenaddr, time.Second, mux) }
func QuasarServeHTTP(q *btrdb.Quasar, addr string) { go func() { log.Info("Active HTTP requests: ", outstandingHttpReqs) }() mux := pat.New() mux.Get("/data/uuid/:uuid", http.HandlerFunc(curry(q, request_get_VRANGE))) mux.Get("/csv/uuid/:uuid", http.HandlerFunc(curry(q, request_get_CSV))) mux.Post("/directcsv", http.HandlerFunc(curry(q, request_post_MULTICSV))) mux.Post("/wrappedcsv", http.HandlerFunc(curry(q, request_post_WRAPPED_MULTICSV))) //mux.Get("/q/versions", http.HandlerFunc(curry(q, request_get_VERSIONS))) mux.Get("/q/nearest/:uuid", http.HandlerFunc(curry(q, request_get_NEAREST))) mux.Post("/q/bracket", http.HandlerFunc(curry(q, request_post_BRACKET))) mux.Post("/data/add/:subkey", http.HandlerFunc(curry(q, request_post_INSERT))) mux.Post("/data/legacyadd/:subkey", http.HandlerFunc(curry(q, request_post_LEGACYINSERT))) mux.Get("/status", http.HandlerFunc(curry(q, request_get_STATUS))) //mux.Post("/q/:uuid/v", curry(q, p log.Info("serving http on %v", addr) graceful.Run(addr, 10*time.Second, mux) }
func main() { var ( addr = flag.String("addr", ":8005", "接听地址") mongo = flag.String("mongo", "localhost", "MongoDB地址") ) flag.Parse() log.Println("MaongoDB链接中") db, err := mgo.Dial(*mongo) if err != nil { log.Fatalf("MaongoDB链接失败:", err) } defer db.Close() mux := http.NewServeMux() mux.HandleFunc("/polls/", withCORS(withVars(withData(db, withAPIKey(handlePolls))))) log.Println("web服务器启动中:", *addr) graceful.Run(*addr, 1*time.Second, mux) log.Println("停止中") }
func main() { log.SetFlags(log.Llongfile) //Get the config from the config.yaml file config, err := utils.GetConfigFromFile("./config.toml") s, err := web.NewServer(config) if err != nil { log.Fatal(err) } l := fmt.Sprintf("%s:%d", config.Server.Address, config.Server.Port) log.Printf("Listening on: %s", l) graceful.Run(l, time.Duration(config.Server.Timeout), s) }
func main() { isDevelopment := os.Getenv("ENVIRONMENT") == "development" dbURL := os.Getenv("MONGOLAB_URI") if isDevelopment { dbURL = os.Getenv("DB_PORT_27017_TCP_ADDR") } dbAccessor := utils.NewDatabaseAccessor(dbURL, os.Getenv("DATABASE_NAME"), 0) cuAccessor := utils.NewCurrentUserAccessor(1) s := web.NewServer(*dbAccessor, *cuAccessor, os.Getenv("GOOGLE_OAUTH2_CLIENT_ID"), os.Getenv("GOOGLE_OAUTH2_CLIENT_SECRET"), os.Getenv("SESSION_SECRET"), isDevelopment, os.Getenv("GOOGLE_ANALYTICS_KEY")) port := os.Getenv("PORT") if port == "" { port = "3000" } graceful.Run(":"+port, 0, s) }
func main() { initializeDB := flag.Bool("initdb", false, "initalizing database") flag.Parse() InitApp(logFile, initializeDB) m := martini.Classic() m.Use(render.Renderer()) m.Use(martini.Recovery()) //status m.Get("/status", StatusHandler) //Login end point m.Post("/auth/login", binding.Bind(LoginCredential{}), LoginHandler) //Create new user m.Post("/user/create", binding.Bind(CreateUserRequest{}), CreateUserHandler) //Validate unique username m.Post("/validate/username", binding.Bind(ValidateUsernameRequest{}), ValidateUsernameHandler) //Validate session token m.Post("/validate/token", binding.Bind(ValidateSessionTokenRequest{}), ValidateSessionTokenHandler) //Change password m.Post("/user/changePassword", binding.Bind(ChangePasswordRequest{}), ChangePasswordHandler) //Check permission m.Post("/user/checkPermission", binding.Bind(CheckPermissionRequest{}), CheckPermissionsForUserHandler) appGracefulShutdownTimeinSeconds, err := strconv.Atoi(viper.GetString("appGracefulShutdownTimeinSeconds")) if err != nil { ERROR.Panicln("Cannot start the server, shutdown time missing from config file") } graceful.Run(":"+viper.GetString("appPort"), time.Duration(appGracefulShutdownTimeinSeconds)*time.Second, m) defer cleanUpAfterShutdown() }
func main() { router := mux.NewRouter() router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) mw := interpose.New() // Use logrus x := negroni.Handler(negronilogrus.NewMiddleware()) mw.Use(adaptors.FromNegroni(x)) // Apply the router. By adding it last, all of our other middleware will be // executed before the router, allowing us to modify headers before any // output has been generated. mw.UseHandler(router) // Launch and permit graceful shutdown, allowing up to 10 seconds for existing // connections to end graceful.Run(":3001", 10*time.Second, mw) }
func main() { // flagパッケージでデフォルト値を設定 var ( addr = flag.String("addr", ":8080", "endpoint address") mongo = flag.String("mongo", "localhost", "mongodb address") ) log.Println("Dialing mongo", *mongo) db, err := mgo.Dial(*mongo) if err != nil { log.Fatalln("failed to connect to mongo:", err) } // DB接続後はdeferで閉じるようにしておく defer db.Close() // Go標準のパッケージを使用して、/polls/のハンドラーを指定する mux := http.NewServeMux() // CORSの設定→OpenVars,CloseVars→db変数にセッションの参照を設定→APIのキーチェック mux.HandleFunc("/polls/", withCORS(withVars(withData(db, withAPIKey(handlePolls))))) log.Println("Starting web server on", *addr) // サーバーを開始する graceful.Run(*addr, 1*time.Second, mux) log.Println("Stopping...") }
func main() { var ( // defines string flags with specified name, default value, and usage string. addr = flag.String("addr", ":8080", "endpoint address") mongo = flag.String("mongo", "127.0.0.1", "mongodb address") ) flag.Parse() log.Println("Dialing mongo", *mongo) db, err := mgo.Dial(*mongo) if err != nil { log.Fatalln("failed to connect to mongo:", err) } defer db.Close() mux := http.NewServeMux() // register a signle handler for all requests begin with the path /polls/ mux.HandleFunc("/polls/", withCORS(withVars(withData(db, withAPIKey(handlePolls))))) log.Println("Starting web server on", *addr) // specify time.Duration when running any http.Handler(ServeMux handler), which // allow in-flight requests some time to complete before the function exits. // wait 1 sec before killing active requests and stopping the server. graceful.Run(*addr, 1*time.Second, mux) log.Println("Stopping...") }
func main() { mw := interpose.New() // Invoke NoSurf (it modifies headers so must be called before your router) mw.Use(middleware.Nosurf()) // Create and apply the router router := mux.NewRouter() mw.UseHandler(router) router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { context := make(map[string]string) context["token"] = nosurf.Token(req) if req.Method == "POST" { context["name"] = req.FormValue("name") } templ.Execute(w, context) }) // Launch and permit graceful shutdown, allowing up to 10 seconds for existing // connections to end graceful.Run(":3001", 10*time.Second, mw) }
func main() { mw := interpose.New() // Tell the browser our output will be JSON mw.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") next.ServeHTTP(w, req) }) }) // Apply the router. Because HTTP requires that headers be modified before // the body, the JSON header function must be added to the middleware stack // before the router. router := mux.NewRouter() router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) mw.UseHandler(router) // Launch and permit graceful shutdown, allowing up to 10 seconds for existing // connections to end graceful.Run(":3001", 10*time.Second, mw) }
func main() { graceful.Run(":80", 3*time.Second, serve.Handler()) }