Пример #1
0
func main() {
	r := mux.NewRouter()

	conn, err := db.Connect(os.Getenv("DB_URL"), os.Getenv("DB_NAME"))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	r.Handle("/register.json", controllers.Register(conn)).Methods("POST")
	r.Handle("/login.json", controllers.Login(conn)).Methods("POST")
	r.Handle("/me.json", controllers.Me(conn)).Methods("GET")
	r.Handle("/devices.json", controllers.RegisterDevice(conn)).Methods("PUT")

	r.Handle("/listings.json", controllers.Listings(conn)).Methods("GET")
	r.Handle("/listings.json", controllers.CreateListing(conn)).Methods("POST")
	r.Handle("/listings/{id}.json", controllers.Listing(conn)).Methods("GET")
	r.Handle("/listings/{id}/rent.json", controllers.Rent(conn)).Methods("POST")

	r.Handle("/rentals.json", controllers.Rentals(conn)).Methods("GET")
	r.Handle("/rentals/{id}.json", controllers.Rental(conn)).Methods("GET")
	r.Handle("/rentals/{id}/confirm.json", controllers.ConfirmRental(conn)).Methods("PUT")
	r.Handle("/rentals/{id}/deny.json", controllers.DenyRental(conn)).Methods("PUT")

	r.Handle("/search.json", controllers.Search(conn)).Methods("GET")

	if os.Getenv("ENV") == "production" {
		log.Fatal(http.ListenAndServeTLS(":"+os.Getenv("PORT"),
			os.Getenv("SSL_CERT_PATH"), os.Getenv("SSL_KEY_PATH"), handlers.LoggingHandler(os.Stdout, r)))
	} else {
		log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), handlers.LoggingHandler(os.Stdout, r)))
	}
}
Пример #2
0
func main() {
	db := sqlx.MustOpen("sqlite3", ":memory:")

	db.MustExec(`CREATE TABLE Products (
                        id INTEGER PRIMARY KEY, 
                        name TEXT
                );
                INSERT INTO Products VALUES (1, 'TV');
                INSERT INTO Products VALUES (2, 'Microwave');`)

	inventory := &DatabaseInventoryRepository{db}

	env := &Env{
		inventory: inventory,
		decoder:   schema.NewDecoder(),
	}

	r := mux.NewRouter()

	r.Handle("/products", handlers.LoggingHandler(os.Stdout, Handler{env, ProductsHandler}))
	r.Handle("/products/search", handlers.LoggingHandler(os.Stdout, Handler{env, SearchHandler}))
	r.Handle("/docs/", http.StripPrefix("/docs/", http.FileServer(http.Dir("docs"))))

	http.ListenAndServe(":8080", r)
}
Пример #3
0
func main() {
	if os.Getenv("MEMCACHED") == "" {
		log.Println("MEMCACHED environment variable must be specified")
		os.Exit(1)
	}
	mc := memcached{memcache.New(os.Getenv("MEMCACHED"))}

	mx := mux.NewRouter()
	// GET secret
	mx.HandleFunc("/secret/{uuid:([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})}",
		func(response http.ResponseWriter, request *http.Request) {
			getHandler(response, request, mc)
		}).Methods("GET")
	// Check secret status
	mx.HandleFunc("/secret/{uuid:([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})}",
		func(response http.ResponseWriter, request *http.Request) {
			messageStatus(response, request, mc)
		}).Methods("HEAD")
	// Save secret
	mx.HandleFunc("/secret", func(response http.ResponseWriter, request *http.Request) {
		saveHandler(response, request, mc)
	}).Methods("POST")
	// Serve static files
	mx.PathPrefix("/").Handler(http.FileServer(http.Dir("public")))

	log.Println("Starting yopass. Listening on port 1337")
	if os.Getenv("TLS_CERT") != "" && os.Getenv("TLS_KEY") != "" {
		// Configure TLS with sane ciphers
		config := &tls.Config{MinVersion: tls.VersionTLS12,
			PreferServerCipherSuites: true,
			CipherSuites: []uint16{
				tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
				tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
				tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
				tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
				tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
				tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
				tls.TLS_RSA_WITH_AES_128_CBC_SHA,
				tls.TLS_RSA_WITH_AES_256_CBC_SHA,
				tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
				tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
			}}
		server := &http.Server{Addr: ":1337",
			Handler: handlers.LoggingHandler(os.Stdout, mx), TLSConfig: config}
		log.Fatal(server.ListenAndServeTLS(os.Getenv("TLS_CERT"), os.Getenv("TLS_KEY")))
	} else {
		log.Fatal(http.ListenAndServe(":1337", handlers.LoggingHandler(os.Stdout, mx)))
	}
}
Пример #4
0
func main() {
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	http.Handle("/", handlers.LoggingHandler(os.Stderr, http.FileServer(http.Dir("."))))
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Println(err)
			return
		}
		defer conn.Close()
		for {
			t, msg, err := conn.ReadMessage()
			if err != nil {
				log.Println(err)
				return
			}
			log.Println("Received:", string(msg))
			err = conn.WriteMessage(t, msg)
			if err != nil {
				log.Println(err)
				return
			}
		}
	})
	host := "localhost:3030"
	log.Printf("http://%v", host)
	log.Fatal(http.ListenAndServe(host, nil))
}
Пример #5
0
func main() {

	if os.Getenv("BASE_URL") == "" {
		log.Fatal("BASE_URL environment variable must be set")
	}
	if os.Getenv("DB_PATH") == "" {
		log.Fatal("DB_PATH environment variable must be set")
	}
	db := sqlite{Path: path.Join(os.Getenv("DB_PATH"), "db.sqlite")}
	db.Init()

	baseURL := os.Getenv("BASE_URL")
	if !strings.HasSuffix(baseURL, "/") {
		baseURL += "/"
	}

	r := mux.NewRouter()
	r.HandleFunc("/save",
		func(response http.ResponseWriter, request *http.Request) {
			encodeHandler(response, request, db, baseURL)
		}).Methods("POST")
	r.HandleFunc("/{id}", func(response http.ResponseWriter, request *http.Request) {
		decodeHandler(response, request, db)
	})
	r.PathPrefix("/").Handler(http.FileServer(http.Dir("public")))
	log.Println("Starting server on port :1337")
	log.Fatal(http.ListenAndServe(":1337", handlers.LoggingHandler(os.Stdout, r)))
}
Пример #6
0
func main() {
	counter, err := NewPostgresCounter(os.Getenv("POSTGRES_URL"))

	if err != nil {
		log.Printf("Error initializing counter: %#v", err)
		os.Exit(1)
	}

	router := mux.NewRouter().StrictSlash(false)
	router.HandleFunc("/", renderHandler(counter))
	router.HandleFunc("/index.html", renderHandler(counter))
	router.HandleFunc("/counter", counterHandler(counter))
	router.PathPrefix("/").Handler(http.FileServer(http.Dir("./static")))
	loggedRouter := handlers.LoggingHandler(os.Stdout, router)

	port := os.Getenv("PORT")

	if port == "" {
		port = "8080"
	}

	log.Printf("Server listening on port: %s", port)

	http.ListenAndServe(":"+port, loggedRouter)
}
Пример #7
0
func main() {
	http.HandleFunc("/favicon.ico", iconHandler)
	indexHandler := http.HandlerFunc(index)
	aboutHandler := http.HandlerFunc(about)
	logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		panic(err)
	}
	http.Handle("/", handlers.LoggingHandler(logFile, handlers.CompressHandler(indexHandler)))
	http.Handle("/about", handlers.LoggingHandler(logFile, handlers.CompressHandler(aboutHandler)))
	server := &http.Server{
		Addr: ":8080",
	}
	log.Println("Listening...")
	server.ListenAndServe()
}
Пример #8
0
func main() {
	log.Println("Starting journlr...")

	var err error
	db, err = sql.Open("postgres", os.Getenv("JOURNLR_DB"))

	if err != nil {
		log.Fatal("No database for journl")
	}

	r := mux.NewRouter()

	r.HandleFunc("/", indexHandler).Methods("GET")
	r.HandleFunc("/receive", receiveHandler).Methods("POST")

	// make is used to construct a channel otherwise nothing can be put into it.
	mailgunStorage = make(chan receiveMsg)

	// go keyword here is used to make this a goroutine. This is a
	// lightweight thread that doesn't block execution. If we
	// expect heavy traffic we can start 5 of these and they'd all
	// go and process reading off of the mailgunStorage channel.
	go fetchEmails()

	http.ListenAndServe(":80", handlers.LoggingHandler(os.Stdout, r))
}
Пример #9
0
func main() {
	flag.Parse()

	setupLogging(*HTTPLogLocation)
	log.Printf("Now serving on http://localhost:%d\n", *port)

	runtime.GOMAXPROCS(runtime.NumCPU())

	session, err := r.Connect(*DBConnection, "urls")
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	router := mux.NewRouter()
	// UUID format
	router.HandleFunc("/{key:[a-z0-9-]+}", func(w http.ResponseWriter, request *http.Request) {
		views.EmbiggenHandler(w, request, session)
	}).Methods("GET")
	router.HandleFunc("/", func(w http.ResponseWriter, request *http.Request) {
		views.ShortenHandler(w, request, session)
	}).Methods("POST")
	router.HandleFunc("/", views.IndexHandler).Methods("GET")
	http.Handle("/", router)
	err = http.ListenAndServe(fmt.Sprintf(":%d", *port), handlers.LoggingHandler(HTTPLogger, http.DefaultServeMux))
	if err != nil {
		log.Fatal(err)
	}
}
Пример #10
0
func main() {
	db := sqlx.MustConnect("sqlite3", ":memory:")

	if err := createFooTable(db); err != nil {
		log.Fatal("couldn't create table: ", err)
	}

	for i := 0; i < 10; i++ {
		id, err := insertFoo(db, "hello world "+strconv.Itoa(i))
		if err != nil {
			log.Fatal("failed to insert value: ", err)
		}
		log.Print("inserted foo record ", id)
	}

	h := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fooListEndpoint(w, r, &FooStore{db: db})
	}))
	h = handlers.LoggingHandler(os.Stdout, h)
	h = handlers.ContentTypeHandler(h, "application/json")

	http.Handle("/foo/", h)

	flag.Parse()
	log.Print("starting http server on ", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Printf("http server failed: ", err)
	}
}
Пример #11
0
func loggingHandler(next http.Handler) http.Handler {
	logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0777)
	if err != nil {
		panic(err)
	}
	return handlers.LoggingHandler(logFile, next)
}
func main() {
	var (
		socksProxy    = flag.String("socks-proxy", "", "Use specified SOCKS proxy (e.g. localhost:2323)")
		fleetEndpoint = flag.String("fleetEndpoint", "", "Fleet API http endpoint: `http://host:port`")
		whitelist     = flag.String("timerBasedServices", "", "List of timer based services separated by a comma: deployer.service,image-cleaner.service,tunnel-register.service")
	)

	flag.Parse()

	fleetAPIClient, err := newFleetAPIClient(*fleetEndpoint, *socksProxy)
	if err != nil {
		panic(err)
	}
	wl := strings.Split(*whitelist, ",")
	log.Printf("whitelisted services: %v", wl)
	wlRegexp := make([]*regexp.Regexp, len(wl))
	for i, s := range wl {
		wlRegexp[i] = regexp.MustCompile(s)
	}
	handler := fleetUnitHealthHandler(fleetAPIClient, fleetUnitHealthChecker{wlRegexp})

	r := mux.NewRouter()
	r.HandleFunc("/", handler)
	r.HandleFunc("/__health", handler)

	err = http.ListenAndServe(":8080", handlers.LoggingHandler(os.Stdout, r))
	if err != nil {
		panic(err)
	}
}
Пример #13
0
Файл: main.go Проект: silky/rct
func main() {
	directory := flag.String("directory", "/usr/local/rct", "Path to the folder storing RCT experiment data")
	templateDirectory := flag.String("template-directory", "/usr/local/rct/server/templates", "Path to the folder storing RCT server templates (this file -> server/templates)")
	staticDirectory := flag.String("static-directory", "/usr/local/rct/server/static", "Path to the folder storing RCT server templates (this file -> server/static)")

	flag.Parse()
	if len(flag.Args()) > 0 {
		log.Fatalf("Usage: server [-directory DIRECTORY] ")
	}
	h := new(RegexpHandler)
	renderRoute, err := regexp.Compile("/experiments/.*/iterations/.+/.+/render")
	if err != nil {
		log.Fatal(err)
	}
	iterationRoute, err := regexp.Compile("/experiments/.*/iterations/.+/.+")
	if err != nil {
		log.Fatal(err)
	}
	staticRoute, err := regexp.Compile("/static")
	if err != nil {
		log.Fatal(err)
	}
	defaultRoute, err := regexp.Compile("/")
	if err != nil {
		log.Fatal(err)
	}
	h.HandleFunc(renderRoute, renderHandler(*directory, *templateDirectory))
	h.HandleFunc(iterationRoute, newRctHandler(*directory, *templateDirectory))
	h.Handler(staticRoute, http.StripPrefix("/static", http.FileServer(http.Dir(*staticDirectory))))
	h.Handler(defaultRoute, http.FileServer(http.Dir(*directory)))
	allHandlers := jsonStripper(serverHeaderHandler(h))
	log.Fatal(http.ListenAndServe(":8080", handlers.LoggingHandler(os.Stdout, allHandlers)))
}
Пример #14
0
func StartWebServer() error {
	conf, err := config.GetConfig()
	if err != nil {
		return err
	}

	var hystrixTimeout time.Duration
	conf.Hystrix.Timeout = strings.TrimSpace(conf.Hystrix.Timeout)
	if conf.Hystrix.Timeout != "" {
		hystrixTimeout, err = time.ParseDuration(conf.Hystrix.Timeout)
		if err != nil || hystrixTimeout < time.Millisecond {
			hystrixTimeout = time.Second
			log15.Error("Use default time", "module", "hystrix", "timeout", hystrixTimeout)
		}
	}

	hystrix.ConfigureCommand("waitFor", hystrix.CommandConfig{
		Timeout:                int(int64(hystrixTimeout) / int64(time.Millisecond)), // converted into Millisecond.
		MaxConcurrentRequests:  conf.Hystrix.MaxConcurrentRequests,
		ErrorPercentThreshold:  conf.Hystrix.ErrorPercentThreshold,
		RequestVolumeThreshold: conf.Hystrix.RequestVolumeThreshold,
		SleepWindow:            conf.Hystrix.SleepWindow,
	})

	e := echo.New()
	e.Post("/api/v1/tweet", createTweetV1)
	e.Get("/api/v1/tweets/:id", getAllTweetForV1)
	e.Get("/api/v1/wait/:timeout", waitFor)
	e.Get("/api/v1/wait_protected/:timeout", waitForProtected)
	e.Static("/", "www/static/")
	logsrv := log15.New("pid", os.Getpid(), "addr", conf.Web.Address)
	return listenAndServer(logsrv, conf.Web.Address, handlers.LoggingHandler(os.Stdout, handlers.CompressHandler(e.Router())))
}
Пример #15
0
func main() {
	flag.Usage = usage
	flag.Parse()
	args := flag.Args()

	if len(args) != 3 {
		usage()
		return
	}

	if gpgpubkey == nil {
		fmt.Fprintf(os.Stderr, "internal error: gpgpubkey is nil")
		return
	}

	if https == nil {
		fmt.Fprintf(os.Stderr, "internal error: https is nil")
		return
	}

	if port == nil {
		fmt.Fprintf(os.Stderr, "internal error: port is nil")
		return
	}

	directory = args[0]
	username = args[1]
	password = args[2]

	os.RemoveAll(path.Join(directory, "tmp"))
	err := os.MkdirAll(path.Join(directory, "tmp"), 0755)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v", err)
		return
	}

	uploads = make(map[int]*upload)

	authHandler := func(h http.HandlerFunc) http.Handler {
		return authBasic(username, password, h)
	}

	r := mux.NewRouter()
	r.HandleFunc("/", renderListOfACIs)
	r.HandleFunc("/pubkeys.gpg", getPubkeys)
	r.Handle("/{image}/startupload", authHandler(initiateUpload))
	r.Handle("/manifest/{num}", authHandler(uploadManifest))
	r.Handle("/signature/{num}", authHandler(receiveUpload(tmpSigPath, gotSig)))
	r.Handle("/aci/{num}", authHandler(receiveUpload(tmpACIPath, gotACI)))
	r.Handle("/complete/{num}", authHandler(completeUpload))
	r.HandleFunc("/find", find)

	r.NotFoundHandler = http.FileServer(http.Dir(directory))

	h := handlers.LoggingHandler(os.Stderr, r)

	addr := ":" + strconv.Itoa(*port)
	log.Println("Listening on", addr)
	log.Fatal(http.ListenAndServe(addr, h))
}
Пример #16
0
func FilteredLoggingHandler(filteredPaths map[string]struct{}, writer io.Writer, router http.Handler) http.Handler {
	return filteredLoggingHandler{
		filteredPaths:  filteredPaths,
		handler:        router,
		loggingHandler: handlers.LoggingHandler(writer, router),
	}
}
Пример #17
0
func main() {
	webroot := "/var/www"
	bind := "localhost:8000"

	flag.StringVar(&webroot, "webroot", "/var/www", "web application root")
	flag.StringVar(&bind, "bind", "localhost:8000", "<host>:<port> or just <host> or <port>")
	flag.Parse()

	log.Println("")
	log.Println("   `( ◔ ౪◔)´")
	log.Println("")
	log.Println(" Server running on :8000")

	r := mux.NewRouter()
	r.HandleFunc("/ping", PingHandler)
	r.HandleFunc("/settings", SettingsHandler)
	r.HandleFunc("/test/lastfm", testArtistSearch)

	r.PathPrefix("/").Handler(
		handlers.LoggingHandler(os.Stdout,
			http.FileServer(http.Dir(webroot))))
	//r.HandleFunc("/socket.io", SocketHandler)
	err := http.ListenAndServe(bind, r)
	if err != nil {
		panic(err)
	}
}
Пример #18
0
func main() {
	//start a db session
	session, err := mgo.Dial("localhost")
	if err != nil {
		fmt.Println(err)
		return				//UGLY HACK: there are "too many" errors here.
	}

	ctx := appContext{db: session, decoder: schema.NewDecoder()} //db, templates map, decoder
	loggedRouter := handlers.LoggingHandler(os.Stdout, http.DefaultServeMux)
	fs := handlers.LoggingHandler(os.Stdout, http.FileServer(http.Dir("assets")))
	http.Handle("/", fs)
	http.HandleFunc("/submit", ctx.receiveSubmission )
	http.HandleFunc("/unlock/", ctx.unlockHandler)
	log.Fatal(http.ListenAndServe(":3000", loggedRouter))
}
Пример #19
0
func main() {
	flag.Parse()
	if *helpFlag {
		fmt.Fprintf(os.Stderr, "Usage of %s\n", os.Args[0])
		flag.PrintDefaults()
		os.Exit(1)
	}
	config := loadConfig(*configFile)

	logger := setupLogging(config.Log.File)

	mysqlDbmap := iamok.PrepareDBMap(config.MySql.ConnectionString)
	defer mysqlDbmap.Db.Close()

	mysqlDbmap.TraceOn("[gorp]", &Foo{})

	router := iamok.NewRouter()

	//Logs the http requests status
	logHandler := handlers.LoggingHandler(logger, router)
	c := cors.New(cors.Options{
		AllowedMethods: []string{"GET", "POST", "DELETE", "OPTIONS", "PUT"},
		AllowedHeaders: []string{"X-Requested-With", "Accept", "Content-Type"},
		Debug:          true,
	}) //for accepting CORS requests
	http.ListenAndServe(":8080", iamok.RecoveryHandler{Handler: c.Handler(logHandler)})
}
Пример #20
0
func RunAPI() {
	r := mux.NewRouter()
	r.HandleFunc("/groups", func(w http.ResponseWriter, r *http.Request) {
		group_server.HandleCreate(w, r)
	}).Methods("POST")

	r.HandleFunc("/groups/{gid}", func(w http.ResponseWriter, r *http.Request) {
		group_server.HandleDisband(w, r)
	}).Methods("DELETE")

	r.HandleFunc("/groups/{gid}/members", func(w http.ResponseWriter, r *http.Request) {
		group_server.HandleAddGroupMember(w, r)
	}).Methods("POST")

	r.HandleFunc("/groups/{gid}/members/{mid}", func(w http.ResponseWriter, r *http.Request) {
		group_server.HandleQuitGroup(w, r)
	}).Methods("DELETE")

	r.HandleFunc("/device/bind", BindToken).Methods("POST")
	r.HandleFunc("/device/unbind", UnbindToken).Methods("POST")
	r.HandleFunc("/notification/groups/{gid}", SetGroupQuiet).Methods("POST")
	r.HandleFunc("/auth/grant", AuthGrant).Methods("POST")
	r.HandleFunc("/messages", PostIMMessage).Methods("POST")
	r.HandleFunc("/messages", LoadLatestMessage).Methods("GET")

	http.Handle("/", handlers.LoggingHandler(os.Stdout, r))

	var PORT = config.port
	var BIND_ADDR = ""
	addr := fmt.Sprintf("%s:%d", BIND_ADDR, PORT)
	SingleHTTPService(addr, nil)
}
Пример #21
0
func main() {
	if flgVersion {
		fmt.Println(VERSION)
		return
	}

	r := http.NewServeMux()

	loggingHandler := func(h http.Handler) http.Handler {
		return gh.LoggingHandler(os.Stdout, h)
	}

	commonHandlers := alice.New(handlers.RecoverHandler, gh.ProxyHeaders, loggingHandler)

	r.Handle("/", commonHandlers.ThenFunc(RootHandler))
	r.Handle("/robots.txt", commonHandlers.ThenFunc(RobotsTxtHandler))

	r.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(flgStaticPath))))

	addr := fmt.Sprintf("%s:%d", flgHost, flgPort)
	log.Printf("Listening on %s", addr)

	err := http.ListenAndServe(addr, r)
	if err != nil {
		log.Fatal("ListenAndServe error: ", err)
	}
}
Пример #22
0
func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", hello)
	fmt.Println("Listening to port :3000")
	lr := handlers.LoggingHandler(os.Stdout, r)
	log.Fatal(http.ListenAndServe(":3000", lr))
}
Пример #23
0
func main() {
	flag.Parse()

	k := new(Kasse)
	k.log = log.New(os.Stderr, "", log.LstdFlags)

	if db, err := sqlx.Connect(*driver, *connect); err != nil {
		log.Fatal("Could not open database:", err)
	} else {
		k.db = db
	}
	defer func() {
		if err := k.db.Close(); err != nil {
			log.Println("Error closing database:", err)
		}
	}()

	k.sessions = sessions.NewCookieStore([]byte("TODO: Set up safer password"))
	http.Handle("/", handlers.LoggingHandler(os.Stderr, k.Handler()))

	var lcd *lcd2usb.Device
	if *hardware {
		var err error
		if lcd, err = lcd2usb.Open("/dev/ttyACM0", 2, 16); err != nil {
			log.Fatal(err)
		}
	}

	events := make(chan NFCEvent)
	// We have to wrap the call in a func(), because the go statement evaluates
	// it's arguments in the current goroutine, and the argument to log.Fatal
	// blocks in these cases.
	if *hardware {
		go func() {
			log.Fatal(ConnectAndPollNFCReader("", events))
		}()
	}

	RegisterHTTPReader(k)
	go func() {
		log.Fatal(http.ListenAndServe(*listen, context.ClearHandler(http.DefaultServeMux)))
	}()

	for {
		ev := <-events
		if ev.Err != nil {
			log.Println(ev.Err)
			continue
		}

		res, err := k.HandleCard(ev.UID)
		if res != nil {
			res.Print(lcd)
		} else {
			// TODO: Distinguish between user-facing errors and internal errors
			flashLCD(lcd, err.Error(), 255, 0, 0)
		}
	}
}
Пример #24
0
func LoggingHandler(h http.Handler) http.Handler {

	logFile, err := os.OpenFile("/usr/amagi/logs/server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		panic(err)
	}
	return handlers.LoggingHandler(logFile, h)
}
Пример #25
0
func RestLoggingHandler(h http.Handler) http.Handler {
	// Middleware to log the incoming request as per the Apache Common logging framework
	logFile, err := os.OpenFile(grutil.SERVER_LOG, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		panic(err)
	}
	return handlers.LoggingHandler(logFile, h)
}
Пример #26
0
// Run server.
func (c *config) Run() error {
	session = c.session

	log.Infof("Bind to: %s", c.bind)
	log.Infof("Using server URI: %s", c.serverURI)
	logr := handlers.LoggingHandler(os.Stderr, c.router)
	return http.ListenAndServe(c.bind, logr)
}
Пример #27
0
// New constructs a pointer to a new App and returns any error encountered.
func New(config *Config) (*App, error) {
	if config.Web.PublicDir == "" {
		config.Web.PublicDir = "/var/workload-simulator/public/static"
	}

	// create a new app config from config yaml and a new App.
	// OpsConfig can be nil on start since it is specified by the UI.
	appCfg := AppConfig{
		Host:      config.Web.Hostname,
		Port:      config.Web.HttpPort,
		PublicDir: config.Web.PublicDir,
		ViewsDir:  config.Web.ViewsDir,
		ReportDir: config.Web.ReportDir,

		MaxDial:    config.Settings.MaxDial,
		MaxWorkers: config.Settings.MaxWorkers,
	}

	app := App{
		config:    &appCfg,
		templates: make(map[string]*template.Template),
	}

	// Register handlers with ServeMux.
	r := http.NewServeMux()

	// Static assets.
	pubDir := config.Web.PublicDir
	serveStatic := func(name string) {
		fs := http.FileServer(http.Dir(filepath.Join(pubDir, name)))
		prefix := "/static/" + name + "/"
		r.Handle(prefix, http.StripPrefix(prefix, fs))
	}

	serveStatic(`img`)
	serveStatic(`css`)
	serveStatic(`js`)
	serveStatic(`lang`)

	r.HandleFunc("/", app.handleRoot)
	r.HandleFunc("/workload", app.handleWorkload)
	r.HandleFunc("/ping", app.handlePing)
	r.HandleFunc("/unload", app.handleUnload)
	r.HandleFunc("/pause", app.handlePause)
	r.HandleFunc("/stats", app.handleStats)
	r.HandleFunc("/status", app.handleStatus)
	r.HandleFunc("/live", app.handleLive)
	r.HandleFunc("/live/stats", app.handleLiveStats)
	r.HandleFunc("/sql", app.handleSql)
	r.HandleFunc("/save", app.handleSave)
	r.HandleFunc("/kill", app.handleKill)

	// Add router to app.
	loggedRouter := handlers.LoggingHandler(os.Stdout, r)
	app.router = loggedRouter

	return &app, nil
}
Пример #28
0
func main() {
	flag.Parse()

	if *file != "" {
		in, err := os.Open(*file)
		if err != nil {
			log.Fatal(err)
		}
		h := hasher.New(in)
		sng := h.Hash()
		in.Close()

		wav := wave.New(wave.Stereo, 22000)
		ks := karplus.Song{
			Song:         *sng,
			SamplingRate: 22000,
		}
		ks.Sound(&wav)

		out, err := os.Create(strings.TrimSuffix(*file, filepath.Ext(*file)) + ".wav")
		if err != nil {
			log.Fatal(err)
		}
		io.Copy(out, wav.Reader())
		return
	}

	if *seed != 0 {
		in := NewRandReader(2*1024*1024, *seed)
		h := hasher.New(in)
		sng := h.Hash()

		wav := wave.New(wave.Stereo, 22000)
		ks := karplus.Song{
			Song:         *sng,
			SamplingRate: 22000,
		}
		ks.Sound(&wav)

		out, err := os.Create(fmt.Sprintf("%v.wav", *seed))
		if err != nil {
			log.Fatal(err)
		}
		io.Copy(out, wav.Reader())
		return
	}

	port := os.Getenv("PORT")
	if port == "" {
		port = "8000"
	}

	r := mux.NewRouter()
	r.StrictSlash(true)
	r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/"))).Methods("GET")
	r.HandleFunc("/upload", api.FileUploadHandler).Methods("POST")
	http.ListenAndServe(":"+port, handlers.LoggingHandler(os.Stdout, r))
}
Пример #29
0
func main() {
	logFile, err := os.OpenFile("logs/app.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("Error accessing log file:", err)
		os.Exit(1)
	}

	r := mux.NewRouter()
	r.Handle("/", handlers.ProxyHeaders(handlers.LoggingHandler(logFile, repsheetHandler(http.HandlerFunc(LoginHandler)))))
	r.Handle("/admin", handlers.ProxyHeaders(handlers.LoggingHandler(logFile, repsheetHandler(http.HandlerFunc(AdminHandler)))))
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	http.Handle("/", r)

	err = http.ListenAndServe("localhost:8080", r)
	if err != nil {
		log.Fatal("Error starting server: ", err)
	}
}
Пример #30
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	r := mux.NewRouter()
	r.StrictSlash(true)
	r.Path("/login").Handler(Handler(GetLogin)).Methods("GET")
	// r.Path("/login").Handler(Handler(PostLogin)).Methods("POST")
	// r.Path("/logout").Handler(middleware.Restrict(Handler(PostLogout))).Methods("POST")
	log.Fatal(http.ListenAndServe(":8080", handlers.LoggingHandler(os.Stdout, r)))
}