示例#1
0
func main() {

	//Setup router
	router := mux.NewRouter()
	handlers.ConfigUserHandler(router.PathPrefix("/user").Subrouter())
	handlers.ConfigFormHandler(router.PathPrefix("/form").Subrouter())
	handlers.ConfigMiscHandlers(router.PathPrefix("/misc").Subrouter())
	handlers.ConfigReviewHandler(router.PathPrefix("/review").Subrouter())
	handlers.ConfigRecommHandler(router.PathPrefix("/recomm").Subrouter())
	handlers.ConfigAdminHandler(router.PathPrefix("/gm").Subrouter())

	http.Handle("/", router)

	//Setup CORS Options
	origins := make([]string, 1)
	origins[0] = "*"
	allowOrigins := goHandlers.AllowedOrigins(origins)

	addrStr := fmt.Sprintf("%s:%d",
		public.Config.GetString("server.address"),
		public.Config.GetInt("server.port"))
	public.LogV.Printf("Listen address: %s\n", addrStr)
	public.LogE.Fatal(http.ListenAndServe(
		addrStr,
		context.ClearHandler(goHandlers.CORS(allowOrigins)(http.DefaultServeMux)),
	))
}
示例#2
0
文件: api.go 项目: Gurrt/go-IoTDM
func (runtime *RuntimeInfo) StartAPI() {
	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/profiles/{id}", runtime.getProfile).Methods("GET")
	router.HandleFunc("/profiles/{id}/{field}/convert", runtime.convert).Methods("GET")
	fmt.Println("Starting API Server @ port 8081")
	log.Fatal(http.ListenAndServe(":8081", handlers.CORS()(router)))
}
示例#3
0
func RegisterMiddleware(apiRouter *mux.Router) http.Handler {
	var apiHandler http.Handler = apiRouter

	apiHandler = handlers.CompressHandler(apiHandler)
	apiHandler = handlers.CORS()(apiHandler)
	apiHandler = ResponseHeaders(apiHandler)

	return apiHandler
}
示例#4
0
func main() {
	parseFlags()

	ss := NewHTTPStaticServer(gcfg.Root)
	ss.Theme = gcfg.Theme
	ss.Title = gcfg.Title

	if gcfg.Upload {
		ss.EnableUpload()
	}
	if gcfg.PlistProxy != nil {
		gcfg.PlistProxy.Scheme = "https"
		ss.PlistProxy = gcfg.PlistProxy.String()
	}

	var hdlr http.Handler = ss

	hdlr = accesslog.NewLoggingHandler(hdlr, l)

	// HTTP Basic Authentication
	userpass := strings.SplitN(gcfg.HttpAuth, ":", 2)
	if len(userpass) == 2 {
		user, pass := userpass[0], userpass[1]
		hdlr = httpauth.SimpleBasicAuth(user, pass)(hdlr)
	}
	// CORS
	if gcfg.Cors {
		hdlr = handlers.CORS()(hdlr)
	}
	if gcfg.XHeaders {
		hdlr = handlers.ProxyHeaders(hdlr)
	}

	http.Handle("/", hdlr)
	http.HandleFunc("/-/sysinfo", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		data, _ := json.Marshal(map[string]interface{}{
			"version": VERSION,
		})
		w.Write(data)
	})

	log.Printf("Listening on addr: %s\n", strconv.Quote(gcfg.Addr))

	var err error
	if gcfg.Key != "" && gcfg.Cert != "" {
		err = http.ListenAndServeTLS(gcfg.Addr, gcfg.Cert, gcfg.Key, nil)
	} else {
		err = http.ListenAndServe(gcfg.Addr, nil)
	}
	log.Fatal(err)
}
示例#5
0
文件: serve.go 项目: erasche/gologme
func ServeFromGolog(g *gologme.Golog, url string) {
	golog = g

	router := mux.NewRouter()
	RegisterRoutes(router)

	// Listen and serve
	fmt.Printf("Listening on %s ...\n", url)
	log.Fatal(http.ListenAndServe(url,
		handlers.CORS(
			handlers.AllowedOrigins([]string{"http://localhost:3000"}),
			handlers.AllowedMethods([]string{"POST", "GET", "HEAD", "OPTIONS"}),
			handlers.AllowedHeaders([]string{"Authorization", "Content-Type"}),
			handlers.AllowCredentials(),
		)(router)))
}
示例#6
0
文件: main.go 项目: akkgr/gestia
func main() {
	log.SetOutput(os.Stderr)

	port := flag.String("port", "8080", "server listening tcp port")
	dbServer := flag.String("server", "localhost", "database server")
	dbName := flag.String("db", "estia", "database name")
	siteType := flag.String("type", "dir", "site path type zip or dir")
	sitePath := flag.String("path", "wwwroot", "path containing site")
	flag.Parse()

	server = *dbServer
	database = *dbName

	db, err := mgo.Dial(server)
	if err != nil {
		log.Panic(err)
	}
	defer db.Close()

	router := NewRouter()
	if *siteType == "zip" {
		rd, err := zip.OpenReader(*sitePath)
		if err != nil {
			log.Fatal(err)
		}
		fs := zipfs.New(rd, *sitePath)
		router.PathPrefix("/").Handler(http.FileServer(httpfs.New(fs)))
	} else {
		router.PathPrefix("/").Handler(http.FileServer(http.Dir(*sitePath)))
	}

	withLog := handlers.LoggingHandler(os.Stdout, router)

	withdb := WithDB(db, withLog)

	withcors := handlers.CORS()(withdb)

	withGz := handlers.CompressHandler(withcors)

	log.Printf(
		"%s\t%s",
		"Server listening on ",
		*port,
	)

	log.Fatal(http.ListenAndServeTLS(":"+*port, "cert.pem", "key.pem", context.ClearHandler(withGz)))
}
示例#7
0
func main() {

	flag.Parse()

	config, err := infrastructure.GetConfiguration(*confFilePath)
	if err != nil {
		fmt.Println(err.Error())
		panic("Cannot parse configuration")
	}

	doInteractor := usecases.DOInteractor{}

	handler := interfaces.WebServiceHandler{
		Interactor:  doInteractor,
		ID:          config.ClientID,
		Secret:      config.ClientSecret,
		Scopes:      config.Scopes,
		RedirectURI: config.RedirectURI,
		APIHost:     config.APIHost,
	}

	headers := handlers.AllowedHeaders([]string{"Accept", "Content-Type", "Authorization"})
	origins := handlers.AllowedOrigins([]string{"http://localhost", "http://provision.tinkerware.io", "https://provision.tinkerware.io"})

	r := mux.NewRouter()

	subrouter := r.PathPrefix("/api/v1/cloud").Subrouter()

	subrouter.HandleFunc("/digital_ocean/", handler.Login)
	subrouter.HandleFunc("/digital_ocean/oauth", handler.DOCallback).Methods("POST")
	subrouter.HandleFunc("/digital_ocean/keys", handler.ShowKeys).Methods("GET")
	subrouter.HandleFunc("/digital_ocean/keys", handler.CreateKey).Methods("POST")
	subrouter.HandleFunc("/digital_ocean/instances", handler.CreateDroplet).Methods("POST")
	subrouter.HandleFunc("/digital_ocean/instances", handler.ListDroplets).Methods("GET")
	subrouter.HandleFunc("/digital_ocean/instance/{instanceID}", handler.GetInstance).Methods("GET")

	n := negroni.Classic()
	n.UseHandler(handlers.CORS(headers, origins)(r))

	port := bytes.Buffer{}

	port.WriteString(":")
	port.WriteString(config.Port)

	n.Run(port.String())

}
示例#8
0
文件: main.go 项目: patterns/re
func main() {
	var (
		httpAddr = flag.String("http.addr", ":8080", "HTTP listen address")
		maildir  = flag.String("maildir", ".Maildir", "Maildir directory path")
	)
	flag.Parse()

	var logger log.Logger
	{
		logger = log.NewLogfmtLogger(os.Stderr)
		logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC)
		logger = log.NewContext(logger).With("caller", log.DefaultCaller)
	}

	var ctx context.Context
	{
		ctx = context.Background()
	}

	var s restsvc.Service
	{
		s = restsvc.NewInmemService(*maildir)
		s = restsvc.LoggingMiddleware(logger)(s)
	}

	var h http.Handler
	{
		h = restsvc.MakeHTTPHandler(ctx, s, log.NewContext(logger).With("component", "HTTP"))
	}

	errs := make(chan error)
	go func() {
		c := make(chan os.Signal)
		signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
		errs <- fmt.Errorf("%s", <-c)
	}()

	go func() {
		logger.Log("transport", "HTTP", "addr", *httpAddr)
		errs <- http.ListenAndServe(*httpAddr, handlers.CORS()(h))
	}()

	logger.Log("exit", <-errs)
}
示例#9
0
文件: api.go 项目: yetis-br/tp-server
func main() {
	Tasks = mq.NewMQ()
	Tasks.NewQueue("APICallbackQueue", "callback")
	CallbackMessages = Tasks.GetMessages("APICallbackQueue")

	trip := new(TripHandler)

	router := mux.NewRouter()
	router.HandleFunc("/trips", requestHandler(trip)).Methods("GET", "POST")
	router.HandleFunc("/trip/{id}", requestHandler(trip)).Methods("GET", "PUT", "DELETE")

	http.Handle("/", handlers.CORS()(router))

	log.Println("[TP-Server] Listening on 3000")

	loggedRouter := handlers.CombinedLoggingHandler(os.Stdout, router)

	http.ListenAndServe(":3000", loggedRouter)
}
示例#10
0
//https://elithrar.github.io/article/vue-react-ember-server-golang/
func main() {
	var entry string
	var static string
	var port string

	flag.StringVar(&entry, "entry", "./index.html", "the entrypoint to serve.")
	flag.StringVar(&static, "static", ".", "the directory to serve static files from.")
	flag.StringVar(&port, "port", "8000", "the `port` to listen on.")
	flag.Parse()

	r := mux.NewRouter()
	r.Headers("Content-Type", "application/json")
	r.PathPrefix("/api/v1/helloworld").HandlerFunc(APIHandler)
	r.PathPrefix("/api/v1/contact").HandlerFunc(MailHandler)
	r.PathPrefix("/dist").Handler(noDirListing(http.FileServer(http.Dir(static))))
	r.PathPrefix("/").HandlerFunc(IndexHandler(entry))

	log.Println("Server started")
	http.ListenAndServe(":8000", handlers.CORS()(r))
}
示例#11
0
文件: main.go 项目: buth/pillar
func main() {

	router := route.NewRouter()

	log.Printf(http.ListenAndServe(":8080", handlers.CORS()(router)).Error())
}
示例#12
0
文件: main.go 项目: Civil/carbonapi
func main() {

	z := flag.String("z", "", "zipper")
	port := flag.Int("p", 8080, "port")
	l := flag.Int("l", 20, "concurrency limit")
	cacheType := flag.String("cache", "mem", "cache type to use")
	mc := flag.String("mc", "", "comma separated memcached server list")
	memsize := flag.Int("memsize", 0, "in-memory cache size in MB (0 is unlimited)")
	cpus := flag.Int("cpus", 0, "number of CPUs to use")
	tz := flag.String("tz", "", "timezone,offset to use for dates with no timezone")
	graphiteHost := flag.String("graphite", "", "graphite destination host")
	logdir := flag.String("logdir", "/var/log/carbonapi/", "logging directory")
	logtostdout := flag.Bool("stdout", false, "log also to stdout")
	interval := flag.Duration("i", 60*time.Second, "interval to report internal statistics to graphite")
	idleconns := flag.Int("idleconns", 10, "max idle connections")
	pidFile := flag.String("pid", "", "pidfile (default: empty, don't create pidfile)")

	flag.Parse()

	if *logdir == "" {
		mlog.SetRawStream(os.Stdout)
	} else {
		mlog.SetOutput(*logdir, "carbonapi", *logtostdout)
	}

	expvar.NewString("BuildVersion").Set(BuildVersion)
	logger.Logln("starting carbonapi", BuildVersion)

	if p := os.Getenv("PORT"); p != "" {
		*port, _ = strconv.Atoi(p)
	}

	Limiter = newLimiter(*l)

	if *z == "" {
		logger.Fatalln("no zipper provided")
	}

	if _, err := url.Parse(*z); err != nil {
		logger.Fatalln("unable to parze zipper:", err)
	}

	logger.Logln("using zipper", *z)
	Zipper = zipper{
		z: *z,
		client: &http.Client{
			Transport: &http.Transport{
				MaxIdleConnsPerHost: *idleconns,
			},
		},
	}

	switch *cacheType {
	case "memcache":
		if *mc == "" {
			logger.Fatalln("memcache cache requested but no memcache servers provided")
		}

		servers := strings.Split(*mc, ",")
		logger.Logln("using memcache servers:", servers)
		queryCache = &memcachedCache{client: memcache.New(servers...)}
		findCache = &memcachedCache{client: memcache.New(servers...)}

	case "mem":
		qcache := &expireCache{ec: ecache.New(uint64(*memsize * 1024 * 1024))}
		queryCache = qcache
		go queryCache.(*expireCache).ec.ApproximateCleaner(10 * time.Second)

		findCache = &expireCache{ec: ecache.New(0)}
		go findCache.(*expireCache).ec.ApproximateCleaner(10 * time.Second)

		Metrics.CacheSize = expvar.Func(func() interface{} {
			return qcache.ec.Size()
		})
		expvar.Publish("cache_size", Metrics.CacheSize)

		Metrics.CacheItems = expvar.Func(func() interface{} {
			return qcache.ec.Items()
		})
		expvar.Publish("cache_items", Metrics.CacheItems)

	case "null":
		queryCache = &nullCache{}
		findCache = &nullCache{}
	}

	if *tz != "" {
		fields := strings.Split(*tz, ",")
		if len(fields) != 2 {
			logger.Fatalf("expected two fields for tz,seconds, got %d", len(fields))
		}

		var err error
		offs, err := strconv.Atoi(fields[1])
		if err != nil {
			logger.Fatalf("unable to parse seconds: %s: %s", fields[1], err)
		}

		defaultTimeZone = time.FixedZone(fields[0], offs)
		logger.Logf("using fixed timezone %s, offset %d ", defaultTimeZone.String(), offs)
	}

	if *cpus != 0 {
		logger.Logln("using GOMAXPROCS", *cpus)
		runtime.GOMAXPROCS(*cpus)
	}

	if envhost := os.Getenv("GRAPHITEHOST") + ":" + os.Getenv("GRAPHITEPORT"); envhost != ":" || *graphiteHost != "" {

		var host string

		switch {
		case envhost != ":" && *graphiteHost != "":
			host = *graphiteHost
		case envhost != ":":
			host = envhost
		case *graphiteHost != "":
			host = *graphiteHost
		}

		logger.Logln("Using graphite host", host)

		logger.Logln("setting stats interval to", *interval)

		// register our metrics with graphite
		graphite := g2g.NewGraphite(host, *interval, 10*time.Second)

		hostname, _ := os.Hostname()
		hostname = strings.Replace(hostname, ".", "_", -1)

		graphite.Register(fmt.Sprintf("carbon.api.%s.requests", hostname), Metrics.Requests)
		graphite.Register(fmt.Sprintf("carbon.api.%s.request_cache_hits", hostname), Metrics.RequestCacheHits)

		graphite.Register(fmt.Sprintf("carbon.api.%s.find_requests", hostname), Metrics.FindRequests)
		graphite.Register(fmt.Sprintf("carbon.api.%s.find_cache_hits", hostname), Metrics.FindCacheHits)

		graphite.Register(fmt.Sprintf("carbon.api.%s.render_requests", hostname), Metrics.RenderRequests)

		graphite.Register(fmt.Sprintf("carbon.api.%s.memcache_timeouts", hostname), Metrics.MemcacheTimeouts)

		if Metrics.CacheSize != nil {
			graphite.Register(fmt.Sprintf("carbon.api.%s.cache_size", hostname), Metrics.CacheSize)
			graphite.Register(fmt.Sprintf("carbon.api.%s.cache_items", hostname), Metrics.CacheItems)
		}

		go mstats.Start(*interval)

		graphite.Register(fmt.Sprintf("carbon.api.%s.alloc", hostname), &mstats.Alloc)
		graphite.Register(fmt.Sprintf("carbon.api.%s.total_alloc", hostname), &mstats.TotalAlloc)
		graphite.Register(fmt.Sprintf("carbon.api.%s.num_gc", hostname), &mstats.NumGC)
		graphite.Register(fmt.Sprintf("carbon.api.%s.pause_ns", hostname), &mstats.PauseNS)

	}

	render := func(w http.ResponseWriter, r *http.Request) {
		var stats renderStats
		t0 := time.Now()
		renderHandler(w, r, &stats)
		since := time.Since(t0)
		logger.Logln(r.RequestURI, since.Nanoseconds()/int64(time.Millisecond), stats.zipperRequests)
	}

	if *pidFile != "" {
		pidfile.SetPidfilePath(*pidFile)
		err := pidfile.Write()
		if err != nil {
			logger.Fatalln("error during pidfile.Write():", err)
		}
	}

	r := http.DefaultServeMux
	r.HandleFunc("/render/", render)
	r.HandleFunc("/render", render)

	r.HandleFunc("/metrics/find/", findHandler)
	r.HandleFunc("/metrics/find", findHandler)

	r.HandleFunc("/info/", passthroughHandler)
	r.HandleFunc("/info", passthroughHandler)

	r.HandleFunc("/lb_check", lbcheckHandler)
	r.HandleFunc("/", usageHandler)

	logger.Logln("listening on port", *port)
	handler := handlers.CompressHandler(r)
	handler = handlers.CORS()(handler)
	handler = handlers.CombinedLoggingHandler(mlog.GetOutput(), handler)

	err := gracehttp.Serve(&http.Server{
		Addr:    ":" + strconv.Itoa(*port),
		Handler: handler,
	})

	if err != nil {
		logger.Fatalln(err)
	}
}
示例#13
0
func main() {
	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/georadius/{longitude}/{latitude}/{miles}", handleGeoRadius)
	router.HandleFunc("/barDetail/{id}", handleBarDetail)
	log.Fatal(http.ListenAndServe(":8080", handlers.CORS()(router)))
}