示例#1
0
func main() {
	err := manners.ListenAndServe(Project.String("server", "addr"), Router)
	if err != nil {
		fmt.Println(err)
	}
	ShutDown()
}
示例#2
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)
}
示例#3
0
func (s *ServerApp) Run(exit chan interface{}) {
	go manners.ListenAndServe(fmt.Sprintf(":%s", s.Port), s.Mux)

	<-exit

	manners.Close()
}
示例#4
0
文件: main.go 项目: yrong/gotraining
// main is the entry point for the application.
func main() {
	log.Println("main : Started")

	// Check the environment for a configured port value.
	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}

	// Create this goroutine to run the web server.
	go func() {
		log.Println("listener : Started : Listening on: http://localhost:" + port)
		manners.ListenAndServe(":"+port, routes.API())
	}()

	// Listen for an interrupt signal from the OS.
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, os.Interrupt)
	<-sigChan

	log.Println("main : Shutting down...")
	manners.Close()

	log.Println("main : Completed")
}
示例#5
0
func StartServer(port string, shutdown <-chan struct{}) {
	log.Printf("http.start.port=%s\n", port)
	go listenForShutdown(shutdown)

	if err := manners.ListenAndServe(":"+port, app()); err != nil {
		log.Fatalf("server.server error=%v", err)
	}
}
示例#6
0
// Start start the http rest api plugin
func (cli *HTTPAPIServer) Start(config map[string]interface{}) error {

	wwwroot, _ := utils.GetString("static", config, "")
	addr, _ := utils.GetString("listen", config, ":8080")
	secret, ok := utils.GetString("secret", config, randomString(128))
	if !ok {
		logrus.Warnf("Plugins: httpapi: generated new secret: %s", secret)
	}

	jwt_middleware := &jwt.JWTMiddleware{
		Key:        []byte(secret),
		Realm:      "jwt auth",
		Timeout:    time.Hour,
		MaxRefresh: time.Hour * 24,
		Authenticator: func(userId string, password string) bool {
			return userId == "admin" && password == "admin"
		}}

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	api.Use(&rest.IfMiddleware{
		Condition: func(request *rest.Request) bool {
			return request.URL.Path != "/login"
		},
		IfTrue: jwt_middleware,
	})

	router, err := rest.MakeRouter(
		rest.Post("/login", jwt_middleware.LoginHandler),
		rest.Get("/refresh_token", jwt_middleware.RefreshHandler),

		rest.Get("/", getApiVersion),
		rest.Get("/sensors", getAllSensors),
		rest.Get("/sensors/:backend.:sensor", getSensor),
		rest.Get("/services", getAllServices),
		rest.Get("/services/:backend.:service", getService),
		rest.Post("/services/:backend.:service", callService),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)

	http.Handle("/v1/", http.StripPrefix("/v1", api.MakeHandler()))

	if wwwroot != "" {
		logrus.Infof("Plugin: httpapi: service static content from %s", wwwroot)
		http.Handle("/ui/", http.StripPrefix("/ui", http.FileServer(http.Dir(wwwroot))))
	}

	go func() {
		logrus.Infof("Plugin: httpapi: starting on %s", addr)
		manners.ListenAndServe(addr, http.DefaultServeMux)
	}()

	return nil
}
示例#7
0
func main() {
	handler := newHandler()

	ch := make(chan os.Signal)
	signal.Notify(ch, os.Interrupt, os.Kill)
	go listenForShutdown(ch)

	manners.ListenAndServe(":8080", handler)
}
示例#8
0
func main() {
	configFilename := flag.String("config", "config.json", "Path to configuration file")

	log.Init(os.Stderr, os.Stdout, os.Stdout, os.Stdout)

	app := application.NewApplication(configFilename)
	controller := newController(app)
	router := route(controller)

	launchProf()
	waitShutdown(app)

	log.Fatal.Pf("failed to start: ", manners.ListenAndServe(fmt.Sprintf(":%d", app.AppConfig().Port()), router))
}
示例#9
0
func Start() {
	LogInfo("Push proxy server is initializing...")

	if len(CfgPP.ApplePushCertPrivate) > 0 {
		appleCert, appleCertErr := certificate.FromPemFile(CfgPP.ApplePushCertPrivate, CfgPP.ApplePushCertPassword)
		if appleCertErr != nil {
			LogCritical(fmt.Sprintf("Failed to load the apple pem cert err=%v", appleCertErr))
		}

		if CfgPP.ApplePushUseDevelopment {
			appleClient = apns.NewClient(appleCert).Development()
		} else {
			appleClient = apns.NewClient(appleCert).Production()
		}
	} else {
		LogError("Apple push notifications not configured.  Mssing ApplePushCertPrivate.")
	}

	if len(CfgPP.AndroidApiKey) == 0 {
		LogError("Android push notifications not configured.  Mssing AndroidApiKey.")
	}

	router := mux.NewRouter()
	var handler http.Handler = router
	vary := throttled.VaryBy{}
	vary.RemoteAddr = false
	vary.Headers = strings.Fields(CfgPP.ThrottleVaryByHeader)
	th := throttled.RateLimit(throttled.PerSec(CfgPP.ThrottlePerSec), &vary, throttledStore.NewMemStore(CfgPP.ThrottleMemoryStoreSize))

	th.DeniedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		LogError(fmt.Sprintf("%v: code=429 ip=%v", r.URL.Path, GetIpAddress(r)))
		throttled.DefaultDeniedHandler.ServeHTTP(w, r)
	})

	handler = th.Throttle(router)

	router.HandleFunc("/", root).Methods("GET")

	r := router.PathPrefix("/api/v1").Subrouter()
	r.HandleFunc("/send_push", handleSendNotification).Methods("POST")

	go func() {
		err := manners.ListenAndServe(CfgPP.ListenAddress, handler)
		if err != nil {
			LogCritical(err.Error())
		}
	}()

	LogInfo("Server is listening on " + CfgPP.ListenAddress)
}
示例#10
0
func StartServer() {
	l4g.Info(utils.T("api.server.start_server.starting.info"))
	l4g.Info(utils.T("api.server.start_server.listening.info"), utils.Cfg.ServiceSettings.ListenAddress)

	var handler http.Handler = &CorsWrapper{Srv.Router}

	if *utils.Cfg.RateLimitSettings.Enable {
		l4g.Info(utils.T("api.server.start_server.rate.info"))

		store, err := memstore.New(utils.Cfg.RateLimitSettings.MemoryStoreSize)
		if err != nil {
			l4g.Critical(utils.T("api.server.start_server.rate_limiting_memory_store"))
			return
		}

		quota := throttled.RateQuota{
			MaxRate:  throttled.PerSec(utils.Cfg.RateLimitSettings.PerSec),
			MaxBurst: *utils.Cfg.RateLimitSettings.MaxBurst,
		}

		rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
		if err != nil {
			l4g.Critical(utils.T("api.server.start_server.rate_limiting_rate_limiter"))
			return
		}

		httpRateLimiter := throttled.HTTPRateLimiter{
			RateLimiter: rateLimiter,
			VaryBy:      &VaryBy{},
			DeniedHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				l4g.Error("%v: Denied due to throttling settings code=429 ip=%v", r.URL.Path, GetIpAddress(r))
				throttled.DefaultDeniedHandler.ServeHTTP(w, r)
			}),
		}

		handler = httpRateLimiter.RateLimit(handler)
	}

	go func() {
		err := manners.ListenAndServe(utils.Cfg.ServiceSettings.ListenAddress, handlers.RecoveryHandler(handlers.PrintRecoveryStack(true))(handler))
		if err != nil {
			l4g.Critical(utils.T("api.server.start_server.starting.critical"), err)
			time.Sleep(time.Second)
		}
	}()
}
示例#11
0
// serveJson will start a server on the hostPort and serve any path the Jsonified data.
// Each successive HTTP request will return the next data.
// If there is only one data, it will be returned on each request.
func serveJson(hostPort string, data ...interface{}) func() bool {
	var curData = 0

	var f http.HandlerFunc
	f = func(rw http.ResponseWriter, r *http.Request) {
		d := data[curData]
		curData = (curData + 1) % len(data)
		jsonData, err := json.MarshalIndent(d, "", "\t")
		if err != nil {
			panic(err)
		}
		fmt.Fprintf(rw, string(jsonData))
	}

	go manners.ListenAndServe(hostPort, f)

	return manners.Close
}
示例#12
0
文件: main.go 项目: yrong/gotraining
func main() {
	var err error

	// Connect to the local nats server.
	rawConn, err = nats.Connect(nats.DefaultURL)
	if err != nil {
		log.Println("ERROR: Unable to connect to NATS")
		return
	}

	// Create an encoded connection
	conn, err = nats.NewEncodedConn(rawConn, nats.JSON_ENCODER)
	if err != nil {
		log.Println("ERROR: Unable to create an encoded connection")
		return
	}

	// Support for shutting down cleanly.
	go func() {

		// Listen for an interrupt signal from the OS.
		sigChan := make(chan os.Signal, 1)
		signal.Notify(sigChan, os.Interrupt)
		<-sigChan

		log.Println("Starting shutdown...")
		log.Println("Waiting on requests to complete...")

		// We have been asked to shutdown the server.
		manners.Close()
	}()

	// Bind routes.
	http.HandleFunc("/users", GetUsers)

	// Start the web service.
	const host = "localhost:8080"
	log.Printf("Listening on: %s\n", host)
	manners.ListenAndServe(host, http.DefaultServeMux)

	// Close the connection to the NATS server.
	log.Println("Waiting on NATS to close...")
	conn.Close()
}
示例#13
0
func StartServer() {
	l4g.Info("Starting Server...")
	l4g.Info("Server is listening on " + utils.Cfg.ServiceSettings.ListenAddress)

	var handler http.Handler = Srv.Router

	if utils.Cfg.RateLimitSettings.EnableRateLimiter {
		l4g.Info("RateLimiter is enabled")

		vary := throttled.VaryBy{}

		if utils.Cfg.RateLimitSettings.VaryByRemoteAddr {
			vary.RemoteAddr = true
		}

		if len(utils.Cfg.RateLimitSettings.VaryByHeader) > 0 {
			vary.Headers = strings.Fields(utils.Cfg.RateLimitSettings.VaryByHeader)

			if utils.Cfg.RateLimitSettings.VaryByRemoteAddr {
				l4g.Warn("RateLimitSettings not configured properly using VaryByHeader and disabling VaryByRemoteAddr")
				vary.RemoteAddr = false
			}
		}

		th := throttled.RateLimit(throttled.PerSec(utils.Cfg.RateLimitSettings.PerSec), &vary, throttledStore.NewMemStore(utils.Cfg.RateLimitSettings.MemoryStoreSize))

		th.DeniedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			l4g.Error("%v: code=429 ip=%v", r.URL.Path, GetIpAddress(r))
			throttled.DefaultDeniedHandler.ServeHTTP(w, r)
		})

		handler = th.Throttle(Srv.Router)
	}

	go func() {
		err := manners.ListenAndServe(utils.Cfg.ServiceSettings.ListenAddress, handler)
		if err != nil {
			l4g.Critical("Error starting server, err:%v", err)
			time.Sleep(time.Second)
			panic("Error starting server " + err.Error())
		}
	}()
}
示例#14
0
func StartServer() {
	l4g.Info(utils.T("api.server.start_server.starting.info"))
	l4g.Info(utils.T("api.server.start_server.listening.info"), utils.Cfg.ServiceSettings.ListenAddress)

	var handler http.Handler = &CorsWrapper{Srv.Router}

	if utils.Cfg.RateLimitSettings.EnableRateLimiter {
		l4g.Info(utils.T("api.server.start_server.rate.info"))

		vary := throttled.VaryBy{}

		if utils.Cfg.RateLimitSettings.VaryByRemoteAddr {
			vary.RemoteAddr = true
		}

		if len(utils.Cfg.RateLimitSettings.VaryByHeader) > 0 {
			vary.Headers = strings.Fields(utils.Cfg.RateLimitSettings.VaryByHeader)

			if utils.Cfg.RateLimitSettings.VaryByRemoteAddr {
				l4g.Warn(utils.T("api.server.start_server.rate.warn"))
				vary.RemoteAddr = false
			}
		}

		th := throttled.RateLimit(throttled.PerSec(utils.Cfg.RateLimitSettings.PerSec), &vary, throttledStore.NewMemStore(utils.Cfg.RateLimitSettings.MemoryStoreSize))

		th.DeniedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			l4g.Error("%v: code=429 ip=%v", r.URL.Path, GetIpAddress(r))
			throttled.DefaultDeniedHandler.ServeHTTP(w, r)
		})

		handler = th.Throttle(&CorsWrapper{Srv.Router})
	}

	go func() {
		err := manners.ListenAndServe(utils.Cfg.ServiceSettings.ListenAddress, handler)
		if err != nil {
			l4g.Critical(utils.T("api.server.start_server.starting.critical"), err)
			time.Sleep(time.Second)
			panic(utils.T("api.server.start_server.starting.panic") + err.Error())
		}
	}()
}
示例#15
0
文件: websrv.go 项目: sqp/godock
// Start starts the registered service matching the given prefix key.
//
func (s *Srv) Start(key string) error {
	app, ok := s.list[key]
	if !ok {
		return errors.New("start webservice: key not found")
	}

	started := false
	for _, v := range s.list {
		started = started || v.started
	}

	app.started = true

	if started {
		return nil
	}

	manners.NewServer()
	go manners.ListenAndServe(s.URL(), s)
	return nil
}
示例#16
0
func (m *MxpSink) Start(sigs <-chan bool, done chan<- bool) {
	log.Printf("* Starting MxpSink on port %d", m.Port)

	r := mux.NewRouter().StrictSlash(false)

	r.HandleFunc("/", m.rootHandler).Methods("GET")

	r.HandleFunc("/track", m.trackGetHandler).Methods("GET")
	r.HandleFunc("/track", m.trackPostHandler).Methods("POST")

	r.HandleFunc("/import", m.importGetHandler).Methods("GET")
	r.HandleFunc("/import", m.importPostHandler).Methods("POST")

	incomingBeaconKiller := make(chan bool)
	incomingBeaconStopped := make(chan bool)

	incomingAliasKiller := make(chan bool)
	incomingAliasStopped := make(chan bool)

	go m.incomingBeaconConsumer(incomingBeaconKiller, incomingBeaconStopped)
	go m.incomingAliasConsumer(incomingAliasKiller, incomingAliasStopped)

	go func() {
		sig := <-sigs
		log.Println("Stopping MxpSink", sig)
		incomingBeaconKiller <- true
		incomingAliasKiller <- true
		manners.Close()
	}()

	if err := manners.ListenAndServe(fmt.Sprintf(":%d", m.Port), r); err != nil {
		log.Fatal(err)
	}

	<-incomingAliasStopped
	<-incomingBeaconStopped

	done <- true
}
示例#17
0
func main() {
	flag.Parse()

	var max int = 10 + rand.New(rand.NewSource(time.Now().UnixNano())).Intn(21)

	go cant_take_it_anymore(max)

	http.HandleFunc("/tick", func(w http.ResponseWriter, r *http.Request) {
		tmpOps := atomic.LoadUint64(&ops)

		marshal(w, tmpOps, max)

		log.Print(fmt.Sprintf("tock (%d/%d)", tmpOps+1, max))

		atomic.AddUint64(&ops, 1)
	})

	http.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {
		marshal(w, atomic.LoadUint64(&ops), max)
	})

	log.Printf("Ready to serve %d times on address %s", max, bind)
	log.Fatal(manners.ListenAndServe(bind, nil))
}
示例#18
0
文件: mux.go 项目: suwenyin/manners
func main() {
	handler := router()
	manners.ListenAndServe(handler, ":7000")
}
示例#19
0
func main() {
	flag.Parse()

	// Pass variables to packages
	model.SessionLength = *SESSION_LENGTH
	model.DbUser = *DB_USER
	model.DbPass = *DB_PASS
	model.DbName = *DB_NAME
	model.DbHost = *DB_HOST

	log.Print("Initializing database backend")
	model.DbMap = model.InitDb()

	log.Print("Initializing session backend")
	common.ActiveSession = &common.SessionConnector{
		Address:    *REDIS_HOST,
		Password:   *REDIS_PASSWORD,
		DatabaseId: int64(*REDIS_DBID),
	}
	err := common.ActiveSession.Connect()
	if err != nil {
		panic(err)
	}

	log.Print("Initializing web services")
	m := gin.New()
	m.Use(gin.Logger())
	m.Use(gin.Recovery())

	// Enable gzip compression
	m.Use(gzip.Gzip(gzip.DefaultCompression))

	// Serve up the static UI...
	m.Static("/ui", "./ui")
	m.StaticFile("/favicon.ico", "./ui/favicon.ico")

	// ... with a redirection for the root page
	m.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "./ui/index.html")
	})

	// All authorized pieces live in /api
	a := m.Group("/api")

	// JWT pieces
	auth := m.Group("/auth")
	auth.POST("/login", getAuthMiddleware().LoginHandler)
	auth.GET("/refresh_token", getAuthMiddleware().RefreshHandler)
	auth.DELETE("/logout", authMiddlewareLogout)
	auth.GET("/logout", authMiddlewareLogout) // for compatibility -- really shouldn't use this

	// Iterate through initializing API maps
	for k, v := range common.ApiMap {
		f := make([]string, 0)
		if v.Authenticated {
			f = append(f, "AUTH")
		}

		log.Printf("Adding handler /api/%s [%s]", k, strings.Join(f, ","))
		g := a.Group("/" + k)
		if v.Authenticated {
			g.Use(getAuthMiddleware().MiddlewareFunc())
		}
		v.RouterFunction(g)
	}

	if *HTTPS_KEY != "" && *HTTPS_CERT != "" {
		log.Printf("Launching https on port :%d", *HTTPS_PORT)
		go func() {
			log.Fatal(manners.ListenAndServeTLS(fmt.Sprintf(":%d", *HTTP_PORT), *HTTPS_CERT, *HTTPS_KEY, m))
		}()
	}

	// HTTP
	log.Printf("Launching http on port :%d", *HTTP_PORT)
	log.Fatal(manners.ListenAndServe(fmt.Sprintf(":%d", *HTTP_PORT), m))
}
示例#20
0
// Run the server for X seconds and release it back.
func (ts *ServerRequest) Start(t time.Duration) {
	go StopSoon(t, ts.Ready)
	manners.ListenAndServe(":8080", ts.Server.Middleware)
}