Esempio n. 1
0
func main() {
	// Setup the global variables and settings
	err := models.Setup()
	if err != nil {
		fmt.Println(err)
	}
	wg := &sync.WaitGroup{}
	wg.Add(1)
	// Start the web servers
	go func() {
		defer wg.Done()
		if config.Conf.AdminConf.UseTLS { // use TLS for Admin web server if available
			Logger.Printf("Starting admin server at https://%s\n", config.Conf.AdminConf.ListenURL)
			Logger.Fatal(http.ListenAndServeTLS(config.Conf.AdminConf.ListenURL, config.Conf.AdminConf.CertPath, config.Conf.AdminConf.KeyPath,
				handlers.CombinedLoggingHandler(os.Stdout, controllers.CreateAdminRouter())))
		} else {
			Logger.Printf("Starting admin server at http://%s\n", config.Conf.AdminConf.ListenURL)
			Logger.Fatal(http.ListenAndServe(config.Conf.AdminConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreateAdminRouter())))
		}
	}()
	wg.Add(1)
	go func() {
		defer wg.Done()
		if config.Conf.PhishConf.UseTLS { // use TLS for Phish web server if available
			Logger.Printf("Starting phishing server at https://%s\n", config.Conf.PhishConf.ListenURL)
			Logger.Fatal(http.ListenAndServeTLS(config.Conf.PhishConf.ListenURL, config.Conf.PhishConf.CertPath, config.Conf.PhishConf.KeyPath,
				handlers.CombinedLoggingHandler(os.Stdout, controllers.CreatePhishingRouter())))
		} else {
			Logger.Printf("Starting phishing server at http://%s\n", config.Conf.PhishConf.ListenURL)
			Logger.Fatal(http.ListenAndServe(config.Conf.PhishConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreatePhishingRouter())))
		}
	}()
	wg.Wait()
}
Esempio n. 2
0
func main() {
	// Setup the global variables and settings
	err := models.Setup()
	if err != nil {
		fmt.Println(err)
	}
	// Start the web servers
	Logger.Printf("Admin server started at http://%s\n", config.Conf.AdminURL)
	go http.ListenAndServe(config.Conf.AdminURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreateAdminRouter()))
	Logger.Printf("Phishing server started at http://%s\n", config.Conf.PhishURL)
	http.ListenAndServe(config.Conf.PhishURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreatePhishingRouter()))
}
Esempio n. 3
0
File: main.go Progetto: chiku/dashy
func main() {
	file, err := os.OpenFile("dashy.log", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0644)
	if err != nil {
		log.Fatalf("Failed to open log file: %s", err)
	}
	defer file.Close()
	logWriter := io.MultiWriter(file, os.Stdout)
	log.SetOutput(logWriter)

	client := gocd.NewClient()

	mux := http.DefaultServeMux
	mux.HandleFunc("/dashy", app.DashyHandler(client))
	mux.Handle("/", http.FileServer(http.Dir("./public")))

	loggingHandler := handlers.CombinedLoggingHandler(logWriter, mux)
	server := &http.Server{
		Addr:    ":3000",
		Handler: loggingHandler,
	}

	fmt.Println("Starting the application on http://localhost:3000")
	err = server.ListenAndServe()
	if err != nil {
		fmt.Printf("failed to start application: %s\n", err)
	}
}
Esempio n. 4
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)
	}

}
Esempio n. 5
0
func main() {

	//Create the server router and add the middleware
	var mainRouter http.Handler
	mainRouter = routing.NewRouter(cfg)
	mainRouter = handlers.CombinedLoggingHandler(os.Stdout, mainRouter)
	// mainRouter = handlers.CompressHandler(mainRouter)

	http.Handle("/", mainRouter)

	//Cache
	//get_subrouter.HandleFunc("/api/v1/reset_cache", Respond("text/xml", "utf-8", ResetCache))

	//TLS support only
	tlsConfig := &tls.Config{
		MinVersion:               tls.VersionTLS10,
		PreferServerCipherSuites: true,
	}

	server := &http.Server{Addr: cfg.Server.Bindip + ":" + strconv.Itoa(cfg.Server.Port), Handler: nil, TLSConfig: tlsConfig}
	//Web service binds to server. Requests served over HTTPS.

	err := server.ListenAndServeTLS(cfg.Server.Cert, cfg.Server.Privkey)

	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Esempio n. 6
0
func main() {
	Portfolios = make(map[float32]Portfolio)

	// HTTP request multiplexer
	// mux.Router matches incoming requests against a list of registered routes
	// and calls a handler for the route that matches the URL
	r := mux.NewRouter()

	s := rpc.NewServer()
	s.RegisterCodec(json.NewCodec(), "application/json")

	stockDealer := new(StockDealer)
	s.RegisterService(stockDealer, "")

	// middle ware: organizing  hared functionalities
	chain := alice.New(
		func(h http.Handler) http.Handler {
			return handlers.CombinedLoggingHandler(os.Stdout, h)
		},
		handlers.CompressHandler,
		func(h http.Handler) http.Handler {
			return recovery.Handler(os.Stderr, h, true)
		})

	r.Handle("/rpc", chain.Then(s))
	fmt.Println("Server listening on 8080")
	log.Fatal(http.ListenAndServe(":8080", r))
}
Esempio n. 7
0
func startWebserver() {
	processEnv()

	router = mux.NewRouter()
	router.HandleFunc("/ws", wrap(wsHandler))

	dockerRouter := router.PathPrefix(fmt.Sprintf("/api/%v/docker", apiVersion)).Subrouter()
	dockerRouter.HandleFunc("/containers", wrap(dockerClient.ContainersHandler))
	dockerRouter.HandleFunc("/containers/graph", wrap(dockerClient.ContainerGraphHandler))
	dockerRouter.HandleFunc("/container/{id}", wrap(dockerClient.ContainerHandler))
	dockerRouter.HandleFunc("/images", wrap(dockerClient.ImagesHandler))
	dockerRouter.HandleFunc("/image/history/{id}", wrap(dockerClient.HistoryHandler))
	dockerRouter.HandleFunc("/info", wrap(dockerClient.InfoHandler))

	consulRouter := router.PathPrefix(fmt.Sprintf("/api/%v/consul", apiVersion)).Subrouter()
	consulRouter.HandleFunc("/datacenters", wrap(consulRegistry.DatacentersHandler))
	consulRouter.HandleFunc("/nodes", wrap(consulRegistry.NodesHandler))
	consulRouter.HandleFunc("/nodes/{dc}", wrap(consulRegistry.NodesHandler))
	consulRouter.HandleFunc("/node/{name}", wrap(consulRegistry.NodeHandler))
	consulRouter.HandleFunc("/health/{name}", wrap(consulRegistry.HealthHandler))
	consulRouter.HandleFunc("/health/{name}/{dc}", wrap(consulRegistry.HealthHandler))

	http.Handle("/", router)
	loggedRouter := handlers.CombinedLoggingHandler(os.Stdout, router)
	panic(http.ListenAndServe(addr, handlers.CompressHandler(loggedRouter)))
}
Esempio n. 8
0
func main() {

	//initialize the stock account
	var st = (new(StockAccounts))

	//initialize a tradeId with random number
	tradeId = rand.Intn(10000) + 1

	// //register the stock account data and start server with HTTP protocol
	// rpc.Register(&st)
	// rpc.HandleHTTP()

	// //start listening
	// err := http.ListenAndServe(":1234", nil) //nil, no need for handler
	router := mux.NewRouter()
	server := rpc.NewServer()
	server.RegisterCodec(json.NewCodec(), "application/json")
	server.RegisterService(st, "")

	chain := alice.New(
		func(h http.Handler) http.Handler {
			return handlers.CombinedLoggingHandler(os.Stdout, h)
		},
		handlers.CompressHandler,
		func(h http.Handler) http.Handler {
			return recovery.Handler(os.Stderr, h, true)
		})

	router.Handle("/rpc", chain.Then(server))
	log.Fatal(http.ListenAndServe(":1234", server))

	// checkError(err)

}
Esempio n. 9
0
func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	if l.file == nil {
		next(rw, r)
	} else {
		handlers.CombinedLoggingHandler(l.file, next).ServeHTTP(rw, r)
	}
}
Esempio n. 10
0
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)
}
Esempio n. 11
0
// NewRegistry creates a new registry from a context and configuration struct.
func NewRegistry(ctx context.Context, config *configuration.Configuration) (*Registry, error) {
	var err error
	ctx, err = configureLogging(ctx, config)
	if err != nil {
		return nil, fmt.Errorf("error configuring logger: %v", err)
	}

	// inject a logger into the uuid library. warns us if there is a problem
	// with uuid generation under low entropy.
	uuid.Loggerf = context.GetLogger(ctx).Warnf

	app := handlers.NewApp(ctx, config)
	// TODO(aaronl): The global scope of the health checks means NewRegistry
	// can only be called once per process.
	app.RegisterHealthChecks()
	handler := configureReporting(app)
	handler = alive("/", handler)
	handler = health.Handler(handler)
	handler = panicHandler(handler)
	handler = gorhandlers.CombinedLoggingHandler(os.Stdout, handler)

	server := &http.Server{
		Handler: handler,
	}

	return &Registry{
		app:    app,
		config: config,
		server: server,
	}, nil
}
Esempio n. 12
0
func main() {
	if !flag.Parsed() {
		flag.Parse()
	}

	router := mux.NewRouter()
	router.StrictSlash(true)
	for _, route := range routes {
		handler := http.Handler(http.HandlerFunc(route.HandlerFunc))
		switch route.Type {
		case "JSON":
			handler = handlers.ContentTypeHandler(handler, "application/json")
		case "":
			break
		default:
			log.Fatalf("invalid route type: %v", route.Type)
		}

		r := router.NewRoute()
		r.Name(route.Name).
			Path(route.Path).
			Methods(route.Methods).
			Handler(handler)
	}

	address := fmt.Sprintf(":%d", *port)
	handler := handlers.CombinedLoggingHandler(os.Stderr, router)
	log.Printf("Version: %s", version.DeploymentManagerVersion)
	log.Printf("Listening on port %d...", *port)
	log.Fatal(http.ListenAndServe(address, handler))
}
Esempio n. 13
0
func main() {
	flag.Parse()
	glog.Infof("Starting Goship...")

	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	auth.Initialize(auth.User{Name: *defaultUser, Avatar: *defaultAvatar}, []byte(*cookieSessionHash))

	h, err := buildHandler(ctx)
	if err != nil {
		glog.Fatal(err)
	}
	w := io.WriteCloser(os.Stdout)
	if *requestLog != "-" {
		w, err = os.OpenFile(*requestLog, os.O_APPEND|os.O_CREATE, 0644)
		if err != nil {
			glog.Fatalf("Cannot open request log %s: %v", *requestLog, err)
		}
		defer w.Close()
	}
	h = ghandlers.CombinedLoggingHandler(w, h)

	fmt.Printf("Running on %s\n", *bindAddress)
	s := &http.Server{
		Addr:    *bindAddress,
		Handler: h,
	}
	if err := s.ListenAndServe(); err != nil {
		glog.Fatal(err)
	}
}
Esempio n. 14
0
func main() {
	lo = C.lok_init(C.CString("/usr/lib/libreoffice/program"))

	if lo == nil {
		return
	}

	http.HandleFunc("/pdf", func(w http.ResponseWriter, r *http.Request) {
		bytes, err := convert(r, "pdf")

		if err != nil {
			return
		}

		w.Header().Set("Content-Type", "application/pdf")
		w.Write(bytes)
	})

	http.HandleFunc("/txt", func(w http.ResponseWriter, r *http.Request) {
		bytes, err := convert(r, "txt")

		if err != nil {
			return
		}

		w.Header().Set("Content-Type", "text/plain;charset=utf8")
		w.Write(bytes)
	})

	http.ListenAndServe(
		":3000",
		handlers.CombinedLoggingHandler(os.Stdout, http.DefaultServeMux),
	)
}
Esempio n. 15
0
func main() {
	r := mux.NewRouter()

	flag.Parse()
	if flag.NArg() != 1 {
		log.Fatal("filename not specified")
	}
	dirname := flag.Args()[0]

	if _, err := os.Stat(dirname); os.IsNotExist(err) {
		log.Println(err)
		os.Exit(0)
	}

	fs := http.FileServer(http.Dir(dirname))

	log.Println("Serving", dirname)

	proxy1 := makeProxyHandler("http://localhost:6543")

	r.HandleFunc("/api/{_dummy:.*}/", handler(proxy1))

	// To use my router the behavior is different to `http.Handle`
	// matching will only occur on a fixed path or using an expression to
	// handle depth
	// Below I use `PathPrefix` with a `Handler` to fix this.
	r.PathPrefix("/").Handler(handlers.CombinedLoggingHandler(os.Stdout, fs))
	http.Handle("/", r)

	log.Println("Listening...on port :8000")
	err := http.ListenAndServe(":8000", nil)
	if err != nil {
		panic(err)
	}
}
func main() {

	//stock account Initialization
	var st = (new(StockAccounts))

	//Trade Id random generator
	tradeId = rand.Intn(99999) + 1

	//start listening
	router := mux.NewRouter()
	server := rpc.NewServer()
	server.RegisterCodec(json.NewCodec(), "application/json")
	server.RegisterService(st, "")

	chain := alice.New(
		func(h http.Handler) http.Handler {
			return handlers.CombinedLoggingHandler(os.Stdout, h)
		},
		handlers.CompressHandler,
		func(h http.Handler) http.Handler {
			return recovery.Handler(os.Stderr, h, true)
		})

	router.Handle("/rpc", chain.Then(server))
	log.Fatal(http.ListenAndServe(":8070", server))

}
Esempio n. 17
0
File: server.go Progetto: vsco/dcdr
// ServeHTTP registers the `HTTPCachingHandler` and sets up the route
// handlers and logging.
func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	srv.Use(middleware.HTTPCachingHandler)
	srv.RegisterRoutes()

	logger := gh.CombinedLoggingHandler(os.Stdout, srv.Router)
	logger.ServeHTTP(w, r)
}
Esempio n. 18
0
func newTestEnvWithConfig(t *testing.T, config *configuration.Configuration) *testEnv {
	ctx := context.Background()

	app := NewApp(ctx, *config)
	server := httptest.NewServer(handlers.CombinedLoggingHandler(os.Stderr, app))
	builder, err := v2.NewURLBuilderFromString(server.URL + config.HTTP.Prefix)

	if err != nil {
		t.Fatalf("error creating url builder: %v", err)
	}

	pk, err := libtrust.GenerateECP256PrivateKey()
	if err != nil {
		t.Fatalf("unexpected error generating private key: %v", err)
	}

	return &testEnv{
		pk:      pk,
		ctx:     ctx,
		config:  *config,
		app:     app,
		server:  server,
		builder: builder,
	}
}
Esempio n. 19
0
func main() {
	flag.Parse()

	var err error
	if config, err = cfg.ReadConf(); err != nil {
		log.Printf("ReadConf: %v", err)
		os.Exit(1)
	}

	index = template.Must(template.New("index").Parse(indexTemplate))
	servers = &serversInfo{Info: map[string]ServerInfo{}}

	go staleCheck()

	http.Handle("/", handlers.CombinedLoggingHandler(os.Stdout, http.HandlerFunc(indexHandler)))
	log.Println("Serving mothership index at /")

	dir := wwwDir()
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
	log.Printf("Serving static files from %v at /static", dir)

	if err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil); err != nil {
		log.Println("Error starting www server:", err)
		// os.IsPermission(err) doesn't work.
		if *port == 80 {
			log.Printf("Try: sudo setcap 'cap_net_bind_service=+ep' %v", os.Args[0])
		}
	}
}
func main() {

	//Creating stock records
	var st = (new(StockRecords))

	//TradeID Initialization
	tradeId = 0

	router := mux.NewRouter()
	server := rpc.NewServer()
	server.RegisterCodec(json.NewCodec(), "application/json")
	server.RegisterService(st, "")

	chain := alice.New(
		func(h http.Handler) http.Handler {
			return handlers.CombinedLoggingHandler(os.Stdout, h)
		},
		handlers.CompressHandler,
		func(h http.Handler) http.Handler {
			return recovery.Handler(os.Stderr, h, true)
		})

	router.Handle("/rpc", chain.Then(server))
	log.Fatal(http.ListenAndServe(":1333", server))

}
Esempio n. 21
0
// launchServer sets up the http fileserver. Exciting!
func launchServer() {
	r := mux.NewRouter().
		StrictSlash(true)

	// Grab all our config junk and prepare to launch
	ip := viper.GetString("ListenAddr")
	port := viper.GetInt("ListenPort")
	fmt.Println(viper.GetInt("ListenPort"))

	// I... I guess, if you want TLS, you can totally have it
	cert, key := viper.GetString("CertFile"), viper.GetString("KeyFile")
	useTLS := len(cert) > 0 && len(key) > 0
	scheme := "https"
	if !useTLS {
		if port == 0 {
			port = 80
		}
		scheme = "http"
	} else if port == 0 {
		port = 443
	}

	p := fmt.Sprintf("%s:%d", ip, port)

	root, files := viper.GetString("ServerRoot"), viper.GetString("StaticFiles")

	reload, err := lr.New(lr.DefaultName, lr.DefaultPort)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	go reload.ListenAndServe()

	r.PathPrefix(root).
		Handler(
			handlers.CombinedLoggingHandler(
				os.Stdout, injectReload(root, files, scheme),
			),
		)

	go func() {
		fmt.Printf("Launching ogload on %s\n", p)
		if !useTLS {
			if err := http.ListenAndServe(p, r); err != nil {
				fmt.Printf("Server failed! scheme=%s, addr=%s, err=%v\n", scheme, p, err)
				os.Exit(1)
			}
			return
		}

		if err := http.ListenAndServeTLS(p, cert, key, r); err != nil {
			fmt.Printf("TLS Server failed! scheme=%s, addr=%s, err=%v\n", scheme, p, err)
			os.Exit(1)
		}
	}()

	wait := watchDir(files, reload)
	<-wait
}
Esempio n. 22
0
func main() {
	if len(os.Args) < 2 {
		printUsage()
		return
	}

	log.SetOutput(os.Stdout)

	file, err := os.Open(os.Args[1])
	if err != nil {
		log.Println("Error opening config file:", err)
		return
	}
	decoder := json.NewDecoder(file)
	config := Config{}
	err = decoder.Decode(&config)
	if err != nil {
		log.Println("Error reading config file:", err)
		return
	}

	gob.Register(auth.SessionUser{}) // this is needed to pass the SessionUser struct around in the gorilla session.

	dbb, err := db.InitializeDatabase(config.DbTypeName, config.DbUser, config.DbPassword, config.DbName, config.DbServer, config.DbPort)
	if err != nil {
		log.Println("Error initializing database:", err)
		return
	}

	var Logger = log.New(os.Stdout, " ", log.Ldate|log.Ltime|log.Lshortfile)
	Logger.Printf("Starting " + config.ListenerType + " server on port " + config.ListenerPort + "...")

	if config.ListenerType == "https" {
		// for https. Make sure you have the server.pem and server.key file. To gen self signed:
		// openssl genrsa -out server.key 2048
		// openssl req -new -x509 -key server.key -out server.pem -days 3650
		err = http.ListenAndServeTLS(":"+config.ListenerPort, config.ListenerCertFile, config.ListenerKeyFile,
			handlers.CombinedLoggingHandler(os.Stdout, routes.CreateRouter(dbb)))
	} else {
		err = http.ListenAndServe(":"+config.ListenerPort, handlers.CombinedLoggingHandler(os.Stdout, routes.CreateRouter(dbb)))
	}

	if err != nil {
		log.Println(err)
	}
}
Esempio n. 23
0
func assetHandler() {
	for _, d := range []string{"css", "img", "js"} {
		prefix := "/" + d + "/"
		fileServer := http.FileServer(http.Dir("assets/" + d))
		handler := http.StripPrefix(prefix, fileServer)
		http.Handle(prefix, handlers.CombinedLoggingHandler(logOut, handler))
	}
}
Esempio n. 24
0
func main() {
	//if err := downloadFile("nvdcve-2.0-2002.xml"); err != nil {
	//	fmt.Println(err)
	//}
	http.Handle("/", handlers.CombinedLoggingHandler(os.Stdout, NewRouter()))
	fmt.Println("Listening on :3334")
	http.ListenAndServe("127.0.0.1:3334", nil)
}
Esempio n. 25
0
func (r *Runner) start() error {
	r.githubToken = os.Getenv("GITHUB_TOKEN")
	if r.githubToken == "" {
		return errors.New("GITHUB_TOKEN not set")
	}

	awsAuth, err := aws.EnvAuth()
	if err != nil {
		return err
	}
	r.s3Bucket = s3.New(awsAuth, aws.USEast).Bucket(logBucket)

	if r.dockerFS == "" {
		var err error
		bc := r.bc
		bc.Network, err = r.allocateNet()
		if err != nil {
			return err
		}
		if r.dockerFS, err = cluster.BuildFlynn(bc, "", util.Repos, os.Stdout); err != nil {
			return fmt.Errorf("could not build flynn: %s", err)
		}
		r.releaseNet(bc.Network)
		defer os.RemoveAll(r.dockerFS)
	}

	db, err := bolt.Open(args.DBPath, 0600, &bolt.Options{Timeout: 5 * time.Second})
	if err != nil {
		return fmt.Errorf("could not open db: %s", err)
	}
	r.db = db
	defer r.db.Close()

	if err := r.db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte("pending-builds"))
		return err
	}); err != nil {
		return fmt.Errorf("could not create pending-builds bucket: %s", err)
	}

	for i := 0; i < maxBuilds; i++ {
		r.buildCh <- struct{}{}
	}

	if err := r.buildPending(); err != nil {
		log.Printf("could not build pending builds: %s", err)
	}

	go r.watchEvents()

	http.Handle("/", handlers.CombinedLoggingHandler(os.Stdout, http.HandlerFunc(r.httpEventHandler)))
	log.Println("Listening on :80...")
	if err := http.ListenAndServe(":80", nil); err != nil {
		return fmt.Errorf("ListenAndServer: %s", err)
	}
	return nil
}
Esempio n. 26
0
func main() {
	if err := db.Connect(os.Getenv("DBHOST"), os.Getenv("DBNAME")); err != nil {
		log.Fatal(err)
	}

	http.Handle("/", handlers.CombinedLoggingHandler(os.Stderr, router))

	log.Printf("Listening on :%s", os.Getenv("PORT"))
	panic(http.ListenAndServe(":"+os.Getenv("PORT"), nil))
}
Esempio n. 27
0
// RegisterAccessLogger will wrap a logrotate-aware Apache-style access log handler
// around the given handler if an access log location is provided by the config.
func RegisterAccessLogger(cfg *config.Server, handler http.Handler) http.Handler {
	if len(cfg.HTTPAccessLog) == 0 {
		return handler
	}

	lf, err := logrotate.NewFile(cfg.HTTPAccessLog)
	if err != nil {
		Log.Fatalf("unable to access http access log file: %s", err)
	}
	return handlers.CombinedLoggingHandler(lf, handler)
}
Esempio n. 28
0
// apiHandler wraps the given handler with standard
// middleware for serving API requests.
func apiHandler(h http.Handler) http.Handler {
	// Support CORS (Allow all origins)
	c := cors.New(cors.Options{
		// Allows requests from browsers (API is read-only).
		AllowedHeaders: []string{"Accept", "X-Requested-With"},
		Debug:          *debugMode,
	})

	// Add handler middleware for logging.
	return handlers.CombinedLoggingHandler(logging.LogWriter{logging.Info}, c.Handler(h))
}
Esempio n. 29
0
func main() {
	log.SetFlags(0)

	// Read configuration.
	flag.Usage = usage
	flag.Parse()

	// Validate arguments.
	if *dataDir == "" {
		log.Fatal("data directory required: --data-dir")
	} else if *certFile != "" && *keyFile == "" {
		log.Fatal("key file required: --key-file")
	} else if *keyFile != "" && *certFile == "" {
		log.Fatal("certificate file required: --cert-file")
	}
	var useTLS = (*certFile != "" && *keyFile != "")

	// Initialize data directory.
	if err := os.MkdirAll(*dataDir, 0700); err != nil {
		log.Fatal(err)
	}

	// Seed the PRNG for API key generation.
	rand.Seed(time.Now().Unix())

	// Initialize db.
	var db db.DB
	if err := db.Open(filepath.Join(*dataDir, "db"), 0666); err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Initialize handler.
	h, err := server.NewHandler(&db)
	if err != nil {
		log.Fatal(err)
	}
	logHandler := handlers.CombinedLoggingHandler(os.Stdout, h)

	// Start servers.
	log.Printf("Listening on http://localhost%s", *addr)
	if useTLS {
		log.Printf("Listening on http://localhost%s", *tlsAddr)
	}
	log.SetFlags(log.LstdFlags)

	go func() { log.Fatal(http.ListenAndServe(*addr, logHandler)) }()
	if useTLS {
		go func() { log.Fatal(http.ListenAndServeTLS(*tlsAddr, *certFile, *keyFile, logHandler)) }()
	}

	select {}
}
Esempio n. 30
0
func main() {
	if logger, err := syslog.New(syslog.LOG_NOTICE|syslog.LOG_LOCAL1, "alanisoft-routing"); err != nil {
		logger.Err(err.Error())
	} else {
		r := NewRouter(logger)
		r.Handle("/", handlers.AppHandler(handlers.GetMain)).Methods("GET")
		http.Handle("/", logging.CombinedLoggingHandler(logger, r))
		if err := http.ListenAndServe(":8080", nil); err != nil {
			logger.Crit(err.Error())
		}
	}
}