Beispiel #1
1
// Handler uses a multiplexing router to route http requests
func (ws *webServer) Handler() http.Handler {
	mux := mux.NewRouter()

	mux.PathPrefix("/t/cc/").HandlerFunc(ws.Cloudconfig).Methods("GET")
	mux.PathPrefix("/t/ig/").HandlerFunc(ws.Ignition).Methods("GET")
	mux.PathPrefix("/t/bp/").HandlerFunc(ws.Bootparams).Methods("GET")

	mux.HandleFunc("/api/version", ws.Version)

	mux.HandleFunc("/api/machines", ws.MachinesList)
	mux.HandleFunc("/api/machines/{mac}", ws.MachineDelete).Methods("DELETE")

	// mux.PathPrefix("/api/machine/").HandlerFunc(ws.NodeSetIPMI).Methods("PUT")

	// Machine variables; used in templates
	mux.PathPrefix("/api/machines/{mac}/variables").HandlerFunc(ws.MachineVariables).Methods("GET")
	mux.PathPrefix("/api/machines/{mac}/variables/{name}").HandlerFunc(ws.SetMachineVariable).Methods("PUT")
	mux.PathPrefix("/api/machines/{mac}/variables/{name}").HandlerFunc(ws.DelMachineVariable).Methods("DELETE")

	// Cluster variables; used in templates
	mux.PathPrefix("/api/variables/{name}").HandlerFunc(ws.GetClusterVariables).Methods("GET")
	mux.PathPrefix("/api/variables/{name}").HandlerFunc(ws.SetClusterVariables).Methods("PUT")
	mux.PathPrefix("/api/variables/{name}").HandlerFunc(ws.DelClusterVariables).Methods("DELETE")
	mux.PathPrefix("/api/variables").HandlerFunc(ws.ClusterVariablesList).Methods("GET")

	// TODO: returning other files functionalities
	mux.PathPrefix("/files/images/").Handler(http.StripPrefix("/files/images",
		http.FileServer(http.Dir(filepath.Join(ws.ds.WorkspacePath(), "images")))))
	mux.PathPrefix("/files/").Handler(http.StripPrefix("/files/",
		http.FileServer(http.Dir(filepath.Join(ws.ds.WorkspacePath(), "files")))))

	mux.Path("/ui").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "/ui/", 302)
	}))

	mux.PathPrefix("/ui/").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		index, _ := FSByte(false, "/static/index.html")
		w.Write(index)
	}))

	mux.PathPrefix("/static/").Handler(http.FileServer(FS(false)))

	mux.PathPrefix("/uploadworkspace/{hash}").HandlerFunc(ws.WorkspaceUploadHandler).Methods("POST")

	return mux
}
Beispiel #2
0
func main() {

	// Load the environment variables we need
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	// Read the port
	port := os.Getenv("PORT")

	tlsConfig, err := getTLSConfig(os.Getenv("SWARM_CREDS_DIR"))
	if err != nil {
		log.Fatal("Could not create TLS certificate.")
	}

	docker, _ := dockerclient.NewDockerClient(os.Getenv("DOCKER_HOST"), tlsConfig)

	mux := mux.NewRouter()
	// mux.HandleFunc("/events", get_events(dbmap)).Methods("GET")
	// mux.HandleFunc("/events/{year}", get_events_by_year(dbmap)).Methods("GET")
	mux.HandleFunc("/spawn", spawn(docker)).Methods("GET")
	mux.HandleFunc("/list-containers", list_containers(docker)).Methods("GET")
	n := negroni.Classic()
	n.UseHandler(mux)
	log.Printf("Listening on port %s\n", port)
	n.Run(":" + port)

}
Beispiel #3
0
// Handler uses a multiplexing router to route http requests
func (ws *webServer) Handler() http.Handler {
	mux := mux.NewRouter()

	mux.PathPrefix("/t/cc/").HandlerFunc(ws.Cloudconfig).Methods("GET")
	mux.PathPrefix("/t/ig/").HandlerFunc(ws.Ignition).Methods("GET")
	mux.PathPrefix("/t/bp/").HandlerFunc(ws.Bootparams).Methods("GET")

	mux.HandleFunc("/api/version", ws.Version)

	mux.HandleFunc("/api/nodes", ws.NodesList)
	mux.PathPrefix("/api/node/").HandlerFunc(ws.NodeFlags).Methods("GET")

	mux.PathPrefix("/api/flag/").HandlerFunc(ws.SetFlag).Methods("PUT")
	mux.PathPrefix("/api/flag/").HandlerFunc(ws.DelFlag).Methods("DELETE")

	mux.HandleFunc("/upload/", ws.Upload)
	mux.HandleFunc("/files", ws.Files).Methods("GET")
	mux.HandleFunc("/files", ws.DeleteFile).Methods("DELETE")
	mux.PathPrefix("/files/").Handler(http.StripPrefix("/files/",
		http.FileServer(http.Dir(filepath.Join(ws.ds.WorkspacePath(), "files")))))

	mux.PathPrefix("/ui/").Handler(http.FileServer(FS(false)))

	return mux
}
Beispiel #4
0
func RouteRequest() http.Handler {
	mux := mux.NewRouter()
	mux.HandleFunc("/test", HandleTest)
	mux.HandleFunc("/json", HandleJSON)
	mux.HandleFunc("/retry", HandleRetry)
	mux.HandleFunc("/limit", HandleLimit)
	return mux
}
Beispiel #5
0
func Start(c *Configuration) {
	log.Printf("Starting Deamon on Port: %s", c.Port)

	mux := mux.NewRouter()
	mux.HandleFunc("/bounce/{type}/{name}/{version}", http.HandlerFunc(bounce))
	mux.HandleFunc("/hook", http.HandlerFunc(hook))
	http.Handle("/", mux)

	log.Println("Listening...")
	http.ListenAndServe(":"+c.Port, nil)
}
Beispiel #6
0
// Create a new server.
func NewServer(addr string, hooks ServerHooks, logger *log.Logger) *Server {
	srv := &Server{}
	srv.addr = addr
	srv.hooks = hooks
	srv.logger = logger
	mux := mux.NewRouter()
	mux.StrictSlash(true)
	mux.HandleFunc("/stop/", srv.handleStop).Methods("POST")
	mux.HandleFunc("/reload/", srv.handleReload).Methods("POST")
	srv.server = NewHTTPServer(addr, mux)
	return srv
}
//
// Benchmarks for rcrowley/go-tigertonic's tigertonic.TrieServeMux:
//
func tigertonicRouterFor(namespaces []string, resources []string) http.Handler {
	mux := tigertonic.NewTrieServeMux()
	for _, ns := range namespaces {
		for _, res := range resources {
			mux.HandleFunc("GET", "/"+ns+"/"+res, helloHandler)
			mux.HandleFunc("POST", "/"+ns+"/"+res, helloHandler)
			mux.HandleFunc("GET", "/"+ns+"/"+res+"/{id}", helloHandler)
			mux.HandleFunc("POST", "/"+ns+"/"+res+"/{id}", helloHandler)
			mux.HandleFunc("DELETE", "/"+ns+"/"+res+"/{id}", helloHandler)
		}
	}
	return mux
}
Beispiel #8
0
func main() {
	mux := mux.NewRouter().StrictSlash(true)

	mux.HandleFunc("/orders", GetOrders).Methods("GET")
	mux.HandleFunc("/orders/{orderId}/", GetOrder).Methods("GET")
	mux.HandleFunc("/orders/", PostOrder).Methods("POST")
	mux.HandleFunc("/orders/{orderId}/", DeleteOrder).Methods("DELETE")
	mux.HandleFunc("/orders/{orderId}/", PutOrder).Methods("PUT")

	log.Println("Listening...")
	log.Fatal(http.ListenAndServe(":3000", mux))

}
Beispiel #9
0
func main() {

	mux := mux.NewRouter()
	mux.HandleFunc("/", homeHandler)
	mux.HandleFunc("/data/{food}", dataHandler)
	mux.HandleFunc("/static/{folder}/{file}", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, r.URL.Path[1:])
	})

	port := ":3000"
	log.Println("Listening on " + port)
	http.ListenAndServe(port, mux)
}
Beispiel #10
0
func (a *RestServer) Mux() *mux.Router {
	mux := mux.NewRouter()
	mux.HandleFunc("/api/nodes", a.nodesList)
	mux.HandleFunc("/api/etcd-endpoints", a.etcdEndpoints)

	mux.HandleFunc("/upload/", a.upload)
	mux.HandleFunc("/files", a.files).Methods("GET")
	mux.HandleFunc("/files", a.deleteFile).Methods("DELETE")
	mux.PathPrefix("/files/").Handler(http.StripPrefix("/files/", http.FileServer(http.Dir(filepath.Join(a.runtimeConfig.WorkspacePath, "files")))))
	mux.PathPrefix("/ui/").Handler(http.FileServer(FS(false)))

	return mux
}
func main() {
	app := cli.App("System-healthcheck", "A service that report on current VM status at __health")

	hostPath = app.String(cli.StringOpt{
		Name:   "hostPath",
		Value:  "",
		Desc:   "The dir path of the mounted host fs (in the container)",
		EnvVar: "SYS_HC_HOST_PATH",
	})

	checks = append(checks, diskFreeChecker{20}.Checks()...)
	checks = append(checks, memoryChecker{15}.Checks()...)
	checks = append(checks, loadAverageChecker{}.Checks()...)
	checks = append(checks, ntpChecker{}.Checks()...)
	checks = append(checks, tcpChecker{}.Checks()...)

	mux := mux.NewRouter()
	mux.HandleFunc("/__health", fthealth.Handler("myserver", "a server", checks...))

	log.Printf("Starting http server on 8080\n")
	err := http.ListenAndServe(":8080", mux)
	if err != nil {
		panic(err)
	}
}
Beispiel #12
0
func runServer() *httptest.Server {
	handler := ShortenerHandler{Database: database}
	mux := mux.NewRouter().StrictSlash(true)
	mux.HandleFunc("/", handler.Add).Methods("POST")
	server := httptest.NewServer(mux)
	return server
}
// vulcan
func startVulcan() {
	mux := vulcan.NewMux()
	expr := fmt.Sprintf(`Method("%s") && Path("%s")`, "GET", "/hello")
	mux.HandleFunc(expr, helloHandler)

	http.ListenAndServe(":"+strconv.Itoa(port), mux)
}
func ExampleServeMux_customized() {
	// Define our error format and how to expose it to the client.
	type customError struct {
		Error    string `json:"error"`
		HTTPCode int    `json:"http_code"`
	}
	errorHandler := func(w ehttp.ResponseWriter, req *http.Request, err error) {
		_ = json.NewEncoder(w).Encode(customError{
			Error:    err.Error(),
			HTTPCode: w.Code(),
		})
	}

	// Define a cutom logger for unexpected events (double header send).
	logger := log.New(os.Stderr, "", log.LstdFlags)

	// Create the mux.
	mux := ehttp.NewServeMux(errorHandler, "application/text; charset=utf-8", false, logger)

	// Register the handler.
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) error {
		// Return an error.
		return ehttp.NewErrorf(http.StatusTeapot, "fail")
	})

	// Start serve the mux.
	log.Fatal(http.ListenAndServe(":8080", mux))
}
func ExampleServeMux_panic() {
	mux := ehttp.NewServeMux(nil, "application/text; charset=utf-8", true, nil)
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) error {
		panic(ehttp.InternalServerError)
	})
	log.Fatal(http.ListenAndServe(":8080", mux))
}
Beispiel #16
0
func startTestDriver() error {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	if server == nil {
		return fmt.Errorf("Failed to start a HTTP Server")
	}

	mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, `{"Implements": ["%s"]}`, driverapi.NetworkPluginEndpointType)
	})

	mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, `{"Scope":"global"}`)
	})

	mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	if err := os.MkdirAll("/etc/docker/plugins", 0755); err != nil {
		return err
	}

	if err := ioutil.WriteFile("/etc/docker/plugins/test.spec", []byte(server.URL), 0644); err != nil {
		return err
	}

	return nil
}
func loadTigerTonic(routes []route) http.Handler {
	re := regexp.MustCompile(":([^/]*)")
	mux := tigertonic.NewTrieServeMux()
	for _, route := range routes {
		mux.HandleFunc(route.method, re.ReplaceAllString(route.path, "{$1}"), httpHandlerFunc)
	}
	return mux
}
Beispiel #18
0
func main() {

	handlers := BaseHandlers()

	mux := mux.NewRouter()

	mux.HandleFunc("/", handlers.landing)
	mux.HandleFunc("/signup", handlers.signup)

	accounts := mux.PathPrefix("/account").Subrouter()
	accounts.HandleFunc("/", handlers.accountIndex)

	n := negroni.Classic()

	n.UseHandler(mux)
	n.Run(*httpAddr)
}
Beispiel #19
0
func main() {
	mux := mux.NewRouter()
	mux.HandleFunc("/", rootHandler)

	muxWithMiddlewares := http.TimeoutHandler(mux, time.Second*39, "Timeout!")

	http.ListenAndServe(":18080", muxWithMiddlewares)
}
Beispiel #20
0
func main() {
	configtoml := flag.String("f", "nixy.toml", "Path to config. (default nixy.toml)")
	version := flag.Bool("v", false, "prints current nixy version")
	flag.Parse()
	if *version {
		fmt.Println(VERSION)
		os.Exit(0)
	}
	file, err := ioutil.ReadFile(*configtoml)
	if err != nil {
		log.Fatal(err)
	}
	err = toml.Unmarshal(file, &config)
	if err != nil {
		log.Fatal("Problem parsing config: ", err)
	}
	if config.Statsd != "" {
		statsd, _ = g2s.Dial("udp", config.Statsd)
	}
	nixystats := stats.New()
	//mux := http.NewServeMux()
	mux := mux.NewRouter()
	mux.HandleFunc("/", nixy_version)
	mux.HandleFunc("/v1/reload", nixy_reload)
	mux.HandleFunc("/v1/apps", nixy_apps)
	mux.HandleFunc("/v1/health", nixy_health)
	mux.HandleFunc("/v1/stats", func(w http.ResponseWriter, req *http.Request) {
		stats := nixystats.Data()
		b, _ := json.MarshalIndent(stats, "", "  ")
		w.Write(b)
		return
	})
	handler := nixystats.Handler(mux)
	s := &http.Server{
		Addr:    ":" + config.Port,
		Handler: handler,
	}
	eventStream()
	eventWorker()
	log.Println("Starting nixy on :" + config.Port)
	err = s.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
Beispiel #21
0
// to run
//
func run() {
	mux := mux.NewRouter()

	mux.HandleFunc("/metrics",
		serveContext(route.PostMetrics)).Methods("POST")

	mux.HandleFunc("/planets",
		serveContext(route.GetPlanets)).Methods("GET")

	mux.HandleFunc("/containers",
		serveContext(route.GetContainers)).Methods("GET")

	mux.HandleFunc("/metrics",
		serveContext(route.GetMetrics)).Methods("GET")

	http.Handle("/", serveMiddleware(mux))
	http.ListenAndServe(":"+port, nil)
}
func BenchmarkRcrowleyTigerTonic_Simple(b *testing.B) {
	mux := tigertonic.NewTrieServeMux()
	mux.HandleFunc("GET", "/action", helloHandler)
	rw, r := testRequest("GET", "/action")
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		mux.ServeHTTP(rw, r)
	}
}
Beispiel #23
0
func init() {

	mux := mux.NewRouter()

	mux.HandleFunc("/", root)
	n := negroni.Classic()

	n.UseHandler(mux)
	http.Handle("/", n)
}
func loadVulcanSingle(method, path string, handler http.HandlerFunc) http.Handler {
	re := regexp.MustCompile(":([^/]*)")
	mux := vulcan.NewMux()
	path = re.ReplaceAllString(path, "<$1>")
	expr := fmt.Sprintf(`Method("%s") && Path("%s")`, method, path)
	if err := mux.HandleFunc(expr, httpHandlerFunc); err != nil {
		panic(err)
	}
	return mux
}
func ExampleServeMux_customLogger() {
	// When returning an error after sending the errors, we can't set the http Status.
	// As data as already been sent, we don't want to corrupt it so we log the error server side.
	logger := log.New(os.Stderr, "", log.LstdFlags)
	mux := ehttp.NewServeMux(nil, "application/text; charset=utf-8", true, logger)
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) error {
		panic(ehttp.InternalServerError)
	})
	log.Fatal(http.ListenAndServe(":8080", mux))
}
Beispiel #26
0
func main() {
	configtoml := flag.String("f", "nixy.toml", "Path to config. (default nixy.toml)")
	version := flag.Bool("v", false, "prints current nixy version")
	flag.Parse()
	if *version {
		fmt.Println(VERSION)
		os.Exit(0)
	}
	file, err := ioutil.ReadFile(*configtoml)
	if err != nil {
		logger.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Fatal("problem opening toml config")
	}
	err = toml.Unmarshal(file, &config)
	if err != nil {
		logger.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Fatal("problem parsing config")
	}

	statsd, _ = setupStatsd()

	mux := mux.NewRouter()
	mux.HandleFunc("/", nixy_version)
	mux.HandleFunc("/v1/reload", nixy_reload)
	mux.HandleFunc("/v1/config", nixy_config)
	mux.HandleFunc("/v1/health", nixy_health)
	s := &http.Server{
		Addr:    ":" + config.Port,
		Handler: mux,
	}
	health = newHealth()
	endpointHealth()
	eventStream()
	eventWorker()
	logger.Info("starting nixy on :" + config.Port)
	err = s.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
func Example_customErrorHandler() {
	// Define how to send errors to the user.
	errorHandler := func(w ehttp.ResponseWriter, req *http.Request, err error) {
		fmt.Fprintf(w, "<<<<<<%s>>>>>>", err)
	}
	mux := ehttp.NewServeMux(errorHandler, "application/text; charset=utf-8", false, nil)
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) error {
		return ehttp.NewErrorf(http.StatusTeapot, "fail")
	})
	log.Fatal(http.ListenAndServe(":8080", mux))
}
Beispiel #28
0
func main() {
	store, err = ratelimit.Init(&net.TCPAddr{Port: 6379})
	if err != nil {
		panic(err)
	}
	defer store.Close()

	mux := mux.NewRouter()
	mux.HandleFunc("/", redis_ping)

	http.ListenAndServe(":8080", mux)
}
func loadVulcan(routes []route) http.Handler {
	re := regexp.MustCompile(":([^/]*)")
	mux := vulcan.NewMux()
	for _, route := range routes {
		path := re.ReplaceAllString(route.path, "<$1>")
		expr := fmt.Sprintf(`Method("%s") && Path("%s")`, route.method, path)
		if err := mux.HandleFunc(expr, httpHandlerFunc); err != nil {
			panic(err)
		}
	}
	return mux
}
func main() {
	addr := flag.String("listen", "0.0.0.0:9004", "Endpoint address")
	redisEndpoint := flag.String("redis", "127.0.0.1:6379", "Redis endpoint")
	paymentEndpoint := flag.String("payment", "localhost:9002", "Endpoint for payment service")
	catalogEndpoint := flag.String("catalog", "localhost:9003", "Endpoint for catalog service")
	services.ParseBalanceEndpointsFlags()
	flag.Parse()
	services.ParseLoadBalanceConfig()
	services.EnableResponseLogging()
	golib.ConfigureOpenFilesLimit()

	redisClient, err := services.ConnectRedis(*redisEndpoint)
	if err != nil {
		log.Fatalln(err)
	}

	if err := services.RegisterLockScripts(redisClient); err != nil {
		log.Fatalln("Failed to register redis scripts", err)
	}

	shop := &Shop{
		redis:           redisClient,
		redisLockValue:  services.EndpointLockValue(*addr),
		catalogEndpoint: *catalogEndpoint,
		paymentEndpoint: *paymentEndpoint,
	}
	launchOrderProcessing(shop)

	mux := mux.NewRouter()
	mux.HandleFunc("/shop", shop.show_items).Methods("GET")
	mux.HandleFunc("/order", shop.order_item).Methods("POST").MatcherFunc(services.MatchFormKeys("user", "item", "qty"))
	mux.HandleFunc("/order/{order}", shop.get_order).Methods("GET")
	mux.HandleFunc("/orders/{user}", shop.show_orders).Methods("GET")

	services.L.Warnf("Running on " + *addr)
	if err := http.ListenAndServe(*addr, mux); err != nil {
		log.Fatal(err)
	}
}