示例#1
0
func router() *mux.Router {
	r := mux.NewRouter()
	r.Handle("/tasks", http.Handler(ContextAdapter{ctx: taskctx, handler: ContextHandlerFunc(tasklist)})).Methods("GET")
	r.Handle("/tasks", http.Handler(ContextAdapter{ctx: taskctx, handler: ContextHandlerFunc(taskadd)})).Methods("POST")
	r.Handle("/tasks/complete", http.Handler(ContextAdapter{ctx: taskctx, handler: ContextHandlerFunc(taskcomplete)})).Methods("POST")
	r.Handle("/tasks/search", http.Handler(ContextAdapter{ctx: taskctx, handler: ContextHandlerFunc(tasksearch)})).Methods("GET")
	return r
}
示例#2
0
func UploadHandler(fileBackend backend.FileBackend) http.Handler {
	result := func(w http.ResponseWriter, r *http.Request) {
		log.Println("Uploading file...")
		uploadedFile, header, err := r.FormFile("data")
		if err != nil {
			log.Printf("problem with file %v", err)
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		defer uploadedFile.Close()
		parts := s.Split(header.Filename, ".")
		extension := parts[len(parts)-1]
		contentType := mime.TypeByExtension("." + extension)
		log.Printf("determined %s as content type", contentType)
		log.Printf("got file %s", header.Filename)
		id, err := fileBackend.Save(contentType, nil, uploadedFile)
		if err != nil {
			log.Printf("problem saving file %v", err)
			w.WriteHeader(http.StatusInternalServerError)
		}
		w.Header().Set("Location", id)
		w.WriteHeader(http.StatusCreated)
	}
	return http.Handler(http.HandlerFunc(result))
}
示例#3
0
文件: api.go 项目: carriercomm/rivet
func (a *Api) Run() error {
	globalMux := http.NewServeMux()

	router := mux.NewRouter()
	router.HandleFunc("/", a.index).Methods("GET")
	router.HandleFunc("/create", a.create).Methods("POST")
	router.HandleFunc("/ip", a.getIP).Methods("GET")
	router.HandleFunc("/state", a.getState).Methods("GET")
	router.HandleFunc("/start", a.start).Methods("GET")
	router.HandleFunc("/kill", a.kill).Methods("GET")
	router.HandleFunc("/remove", a.remove).Methods("GET")
	router.HandleFunc("/restart", a.restart).Methods("GET")
	router.HandleFunc("/stop", a.stop).Methods("GET")
	// enable auth if token is present
	if a.config.AuthToken != "" {
		am := auth.NewAuthMiddleware(a.config.AuthToken)
		globalMux.Handle("/", negroni.New(
			negroni.HandlerFunc(am.Handler),
			negroni.Wrap(http.Handler(router)),
		))
	} else {

		globalMux.Handle("/", router)
	}

	log.Infof("rivet version %s", version.FULL_VERSION)
	log.Infof("listening: addr=%s", a.config.ListenAddr)
	n := negroni.New()
	n.UseHandler(globalMux)
	return http.ListenAndServe(a.config.ListenAddr, n)
}
示例#4
0
文件: app.go 项目: kwketh/gotty
func (app *App) Run() error {
	path := "/"
	if app.options.RandomUrl {
		randomPath := generateRandomString(8)
		path = "/" + randomPath + "/"
	}

	fs := http.StripPrefix(path, http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "bindata"}))
	http.Handle(path, fs)
	http.HandleFunc(path+"ws", app.handler)

	endpoint := app.options.Address + ":" + app.options.Port
	log.Printf("Server is running at %s, command: %s", endpoint+path, strings.Join(app.options.Command, " "))
	handler := http.Handler(http.DefaultServeMux)
	handler = loggerHandler(handler)
	if app.options.Credential != "" {
		handler = basicAuthHandler(handler, app.options.Credential)
	}
	err := http.ListenAndServe(endpoint, handler)
	if err != nil {
		return err
	}

	return nil
}
示例#5
0
func startHTTP(wg *sync.WaitGroup) {
	log.Println("Starting HTTP Server...")

	mux := http.NewServeMux()
	mux.HandleFunc("/status", statusHandler)
	mux.HandleFunc("/ls", lsHandler)
	mux.HandleFunc("/shutdown", func(w http.ResponseWriter, _ *http.Request) {
		fmt.Fprintf(w, "OK")
		forceShutdown <- true
	})
	mux.Handle("/files/", http.StripPrefix("/files/", http.FileServer(torrentFS)))

	handler := http.Handler(mux)
	if config.idleTimeout > 0 {
		connTrackChannel := make(chan int, 10)
		handler = NewConnectionCounterHandler(connTrackChannel, mux)
		go inactiveAutoShutdown(connTrackChannel)
	}

	log.Printf("Listening HTTP on %s...\n", config.bindAddress)
	s := &http.Server{
		Addr:    config.bindAddress,
		Handler: handler,
	}

	var e error
	if httpListener, e = net.Listen("tcp", config.bindAddress); e != nil {
		log.Fatal(e)
	}
	go s.Serve(httpListener)
	defer wg.Done()
}
示例#6
0
文件: etcd.go 项目: menglingwei/etcd
func (e *Etcd) serve() (err error) {
	var ctlscfg *tls.Config
	if !e.cfg.ClientTLSInfo.Empty() {
		plog.Infof("ClientTLS: %s", e.cfg.ClientTLSInfo)
		if ctlscfg, err = e.cfg.ClientTLSInfo.ServerConfig(); err != nil {
			return err
		}
	}

	if e.cfg.CorsInfo.String() != "" {
		plog.Infof("cors = %s", e.cfg.CorsInfo)
	}

	// Start the peer server in a goroutine
	ph := v2http.NewPeerHandler(e.Server)
	for _, l := range e.Peers {
		go func(l net.Listener) {
			e.errc <- servePeerHTTP(l, ph)
		}(l)
	}

	// Start a client server goroutine for each listen address
	ch := http.Handler(&cors.CORSHandler{
		Handler: v2http.NewClientHandler(e.Server, e.Server.Cfg.ReqTimeout()),
		Info:    e.cfg.CorsInfo,
	})
	for _, sctx := range e.sctxs {
		// read timeout does not work with http close notify
		// TODO: https://github.com/golang/go/issues/9524
		go func(s *serveCtx) {
			e.errc <- s.serve(e.Server, ctlscfg, ch, e.errc)
		}(sctx)
	}
	return nil
}
示例#7
0
文件: ent.go 项目: queer1/ent
func main() {
	var (
		fsRoot      = flag.String("fs.root", "/tmp", "FileSystem root directory")
		httpAddress = flag.String("http.addr", ":5555", "HTTP listen address")
		providerDir = flag.String("provider.dir", "/tmp", "Provider directory with bucket policies")
	)
	flag.Parse()

	prometheus.Register("ent_requests_total", "Total number of requests made", prometheus.NilLabels, requestTotal)
	prometheus.Register("ent_requests_duration_nanoseconds_total", "Total amount of time ent has spent to answer requests in nanoseconds", prometheus.NilLabels, requestDuration)
	prometheus.Register("ent_requests_duration_nanoseconds", "Amounts of time ent has spent answering requests in nanoseconds", prometheus.NilLabels, requestDurations)
	prometheus.Register("ent_request_bytes_total", "Total volume of request payloads emitted in bytes", prometheus.NilLabels, requestBytes)
	prometheus.Register("ent_response_bytes_total", "Total volume of response payloads emitted in bytes", prometheus.NilLabels, responseBytes)

	p, err := NewDiskProvider(*providerDir)
	if err != nil {
		log.Fatal(err)
	}

	fs := NewDiskFS(*fsRoot)
	r := pat.New()
	r.Get(fileRoute, handleGet(p, fs))
	r.Post(fileRoute, handleCreate(p, fs))
	r.Handle("/metrics", prometheus.DefaultRegistry.Handler())
	r.Get("/", handleBucketList(p))

	log.Fatal(http.ListenAndServe(*httpAddress, http.Handler(r)))
}
示例#8
0
文件: config.go 项目: bryk/kubernetes
// New returns a new instance of GenericAPIServer from the given config.
// Certain config fields will be set to a default value if unset,
// including:
//   ServiceClusterIPRange
//   ServiceNodePortRange
//   MasterCount
//   ReadWritePort
//   PublicAddress
// Public fields:
//   Handler -- The returned GenericAPIServer has a field TopHandler which is an
//   http.Handler which handles all the endpoints provided by the GenericAPIServer,
//   including the API, the UI, and miscellaneous debugging endpoints.  All
//   these are subject to authorization and authentication.
//   InsecureHandler -- an http.Handler which handles all the same
//   endpoints as Handler, but no authorization and authentication is done.
// Public methods:
//   HandleWithAuth -- Allows caller to add an http.Handler for an endpoint
//   that uses the same authentication and authorization (if any is configured)
//   as the GenericAPIServer's built-in endpoints.
//   If the caller wants to add additional endpoints not using the GenericAPIServer's
//   auth, then the caller should create a handler for those endpoints, which delegates the
//   any unhandled paths to "Handler".
func (c completedConfig) New() (*GenericAPIServer, error) {
	if c.Serializer == nil {
		return nil, fmt.Errorf("Genericapiserver.New() called with config.Serializer == nil")
	}

	s := &GenericAPIServer{
		ServiceClusterIPRange: c.ServiceClusterIPRange,
		ServiceNodePortRange:  c.ServiceNodePortRange,
		LoopbackClientConfig:  c.LoopbackClientConfig,
		legacyAPIPrefix:       c.APIPrefix,
		apiPrefix:             c.APIGroupPrefix,
		admissionControl:      c.AdmissionControl,
		requestContextMapper:  c.RequestContextMapper,
		Serializer:            c.Serializer,

		minRequestTimeout:    time.Duration(c.MinRequestTimeout) * time.Second,
		enableSwaggerSupport: c.EnableSwaggerSupport,

		MasterCount:          c.MasterCount,
		SecureServingInfo:    c.SecureServingInfo,
		InsecureServingInfo:  c.InsecureServingInfo,
		ExternalAddress:      c.ExternalHost,
		ClusterIP:            c.PublicAddress,
		PublicReadWritePort:  c.ReadWritePort,
		ServiceReadWriteIP:   c.ServiceReadWriteIP,
		ServiceReadWritePort: c.ServiceReadWritePort,
		ExtraServicePorts:    c.ExtraServicePorts,
		ExtraEndpointPorts:   c.ExtraEndpointPorts,

		KubernetesServiceNodePort: c.KubernetesServiceNodePort,
		apiGroupsForDiscovery:     map[string]unversioned.APIGroup{},

		enableOpenAPISupport:   c.EnableOpenAPISupport,
		openAPIInfo:            c.OpenAPIInfo,
		openAPIDefaultResponse: c.OpenAPIDefaultResponse,
		openAPIDefinitions:     c.OpenAPIDefinitions,
	}

	if c.RestfulContainer != nil {
		s.HandlerContainer = c.RestfulContainer
	} else {
		s.HandlerContainer = NewHandlerContainer(http.NewServeMux(), c.Serializer)
	}
	// Use CurlyRouter to be able to use regular expressions in paths. Regular expressions are required in paths for example for proxy (where the path is proxy/{kind}/{name}/{*})
	s.HandlerContainer.Router(restful.CurlyRouter{})
	s.Mux = apiserver.NewPathRecorderMux(s.HandlerContainer.ServeMux)
	apiserver.InstallServiceErrorHandler(s.Serializer, s.HandlerContainer)

	if c.ProxyDialer != nil || c.ProxyTLSClientConfig != nil {
		s.ProxyTransport = utilnet.SetTransportDefaults(&http.Transport{
			Dial:            c.ProxyDialer,
			TLSClientConfig: c.ProxyTLSClientConfig,
		})
	}

	s.installAPI(c.Config)
	s.Handler, s.InsecureHandler = s.buildHandlerChains(c.Config, http.Handler(s.Mux.BaseMux().(*http.ServeMux)))

	return s, nil
}
示例#9
0
func upsertMultiplePermissionsHandler(mapper *pgmapper.Mapper, sidIdExtractor idextractor.Extractor) http.Handler {
	result := func(w http.ResponseWriter, r *http.Request) {
		sid, err := sidIdExtractor(r)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		ids, ok := r.URL.Query()["oid"]
		if !ok {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		permissions := make(map[string]interface{})
		err = json.NewDecoder(r.Body).Decode(&permissions)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		err = mapper.Execute("SELECT insert_bulk_sid_permissions(%v)", sid, permissions["create_permission"], permissions["read_permission"], permissions["update_permission"], permissions["delete_permission"], ids)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusOK)
		return
	}
	return http.Handler(http.HandlerFunc(result))
}
示例#10
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))
}
示例#11
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)
	}
}
示例#12
0
// Use adds a Middleware function to the stack.
func (b *Builder) Use(f Middleware) {
	b.handler = http.Handler(nil)
	b.middleware = append(b.middleware, f)
	for i := len(b.middleware) - 1; i >= 0; i-- {
		b.handler = b.middleware[i](b.handler)
	}
}
示例#13
0
func upsertPermissionsHandler(mapper *pgmapper.Mapper, objectIdExtractor idextractor.Extractor) http.Handler {
	result := func(w http.ResponseWriter, r *http.Request) {
		objectId, err := objectIdExtractor(r)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		ids, ok := r.URL.Query()["sid"]
		entity := make(map[string]interface{})
		err = json.NewDecoder(r.Body).Decode(&entity)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		if ok {
			err = mapper.Execute("SELECT insert_bulk_permissions(%v)", objectId, entity["create_permission"], entity["read_permission"], entity["update_permission"], entity["delete_permission"], ids)
		} else {
			_, err = mapper.ExecuteRaw("insert into acl_entries(object_id,sid,create_permission,read_permission,update_permission,delete_permission) values($1,$2,$3,$4,$5,$6) ON CONFLICT (object_id,sid) DO UPDATE SET create_permission = $3, read_permission = $4, update_permission = $5, delete_permission = $6 where acl_entries.sid = $2 AND acl_entries.object_id = $1", objectId, entity["sid"], entity["create_permission"], entity["read_permission"], entity["update_permission"], entity["delete_permission"])
		}
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
	}
	return http.Handler(http.HandlerFunc(result))
}
示例#14
0
文件: http.go 项目: codeaudit/shift
// StartHTTP starts listening for RPC requests sent via HTTP.
func StartHttp(cfg HttpConfig, codec codec.Codec, api shared.EthereumApi) error {
	httpServerMu.Lock()
	defer httpServerMu.Unlock()

	addr := fmt.Sprintf("%s:%d", cfg.ListenAddress, cfg.ListenPort)
	if httpServer != nil {
		if addr != httpServer.Addr {
			return fmt.Errorf("RPC service already running on %s ", httpServer.Addr)
		}
		return nil // RPC service already running on given host/port
	}
	// Set up the request handler, wrapping it with CORS headers if configured.
	handler := http.Handler(&handler{codec, api})
	if len(cfg.CorsDomain) > 0 {
		opts := cors.Options{
			AllowedMethods: []string{"POST"},
			AllowedOrigins: strings.Split(cfg.CorsDomain, " "),
		}
		handler = cors.New(opts).Handler(handler)
	}
	// Start the server.
	s, err := listenHTTP(addr, handler)
	if err != nil {
		glog.V(logger.Error).Infof("Can't listen on %s:%d: %v", cfg.ListenAddress, cfg.ListenPort, err)
		return err
	}
	httpServer = s
	return nil
}
示例#15
0
文件: vfs_test.go 项目: sombr/ccat
func TestRWVFS(t *testing.T) {
	tmpdir, err := ioutil.TempDir("", "rwvfs-test-")
	if err != nil {
		t.Fatal("TempDir", err)
	}
	defer os.RemoveAll(tmpdir)

	h := http.Handler(rwvfs.HTTPHandler(rwvfs.Map(map[string]string{}), nil))
	httpServer := httptest.NewServer(h)
	defer httpServer.Close()
	httpURL, err := url.Parse(httpServer.URL)
	if err != nil {
		t.Fatal(err)
	}

	tests := []struct {
		fs   rwvfs.FileSystem
		path string
	}{
		{rwvfs.OS(tmpdir), "/foo"},
		{rwvfs.Map(map[string]string{}), "/foo"},
		{rwvfs.Sub(rwvfs.Map(map[string]string{}), "/x"), "/foo"},
		{rwvfs.HTTP(httpURL, nil), "/foo"},
	}
	for _, test := range tests {
		testWrite(t, test.fs, test.path)
		testMkdir(t, test.fs)
		testMkdirAll(t, test.fs)
		testGlob(t, test.fs)
	}
}
func prepareServer(serviceName string) *httptest.Server {
	// wir schreiben einen fake server. Dieser server stellt den eigentlichen service dar,
	// an den du deine Requests weiterleiten möchtest (beispielsweise der authentication-service).
	// Falls er angesprochen wird soll er den Statuscode 418 (im a teapot) zurückgesendet.
	serviceHandler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusTeapot)
	}))
	server := httptest.NewServer(serviceHandler)

	// der servicecache wird so konfiguriert, dass er immer die url des eben erstellten server zurückliefert.
	// Wir umgehen somit die periodischen Anfragen an den discovery-service.
	fakeRetriever := func(consulAddress string) (map[string]*api.AgentService, error) {
		services := make(map[string]*api.AgentService)
		serviceUrl, _ := url.Parse(server.URL)
		parts := strings.Split(serviceUrl.Host, ":")
		host := parts[0]
		port, _ := strconv.Atoi(parts[1])
		services[serviceName] = createService(serviceName+"1", serviceName, port, host, "public", "interactive-lecture")
		return services, nil
	}
	// wir configurieren den cache und bauen anschließend unseren mock-retreiver ein.
	cache, _ := servicecache.Configure("discovery:8500", 1*time.Millisecond, serviceName)
	cache.SetServiceRetriever(fakeRetriever)
	return server
}
示例#17
0
文件: vfs_test.go 项目: sombr/ccat
func TestHTTP_BaseURL(t *testing.T) {
	m := map[string]string{"b/c": "c"}
	mapFS := rwvfs.Map(m)

	prefix := "/foo/bar/baz"

	h := http.Handler(http.StripPrefix(prefix, rwvfs.HTTPHandler(mapFS, nil)))
	httpServer := httptest.NewServer(h)
	defer httpServer.Close()
	httpURL, err := url.Parse(httpServer.URL + prefix)
	if err != nil {
		t.Fatal(err)
	}

	fs := rwvfs.HTTP(httpURL, nil)

	if err := rwvfs.MkdirAll(fs, "b"); err != nil {
		t.Errorf("MkdirAll %q: %s", "b", err)
	}

	fis, err := fs.ReadDir("b")
	if err != nil {
		t.Fatal(err)
	}
	if len(fis) != 1 {
		t.Errorf("got len(fis) == %d, want 1", len(fis))
	}
	if wantName := "c"; fis[0].Name() != wantName {
		t.Errorf("got name == %q, want %q", fis[0].Name(), wantName)
	}
}
示例#18
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lmicroseconds)
	var (
		httpAddress  = flag.String("http.addr", ":8080", "HTTP listen address")
		historicData = flag.String("historic.data", "", "path to data directory")
		printVersion = flag.Bool("version", false, "print version and exit")
	)
	flag.Parse()

	if *printVersion {
		fmt.Printf("%s", Version)
		os.Exit(0)
	}

	cache, err := populateExchangeRateCache(*historicData)
	if err != nil {
		log.Fatalf("Unable to populate cache: %v", err)
	}

	go func() {
		for {
			time.Sleep(6 * time.Hour)

			updateExchangeRatesCache(cache)
		}
	}()

	log.Printf("listening on %v", *httpAddress)
	log.Fatal(http.ListenAndServe(*httpAddress, logHandler(http.Handler(rateHTTP.Handler(cache)))))
}
示例#19
0
文件: hitch.go 项目: dnamenon/hitch
// Handler returns an http.Handler for the embedded router and middleware.
func (h *Hitch) Handler() http.Handler {
	handler := http.Handler(h.Router)
	for i := len(h.middleware) - 1; i >= 0; i-- {
		handler = h.middleware[i](handler)
	}
	return handler
}
示例#20
0
func listen(port string, environment string, dbUrl string) {
	log.Printf("Setting env to %v", environment)

	db, err = sql.Open("mysql", dbUrl)

	if err != nil {
		log.Fatalf("Error opening DB connection: %v", err)
	}

	http.HandleFunc("/validate/", validationHandler)
	http.Handle("/metrics", http.Handler(inmemMetrics))

	//Only host the static template when the ENV is 'Live' or 'Test'
	if environment == "Live" || environment == "Test" {
		http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			http.ServeFile(w, r, "static/"+r.URL.Path[1:])
		})
	}

	err = http.ListenAndServe(":"+port, nil)

	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
示例#21
0
// NewProxyServer creates and installs a new ProxyServer.
// It automatically registers the created ProxyServer to http.DefaultServeMux.
// 'filter', if non-nil, protects requests to the api only.
func NewProxyServer(port int, filebase string, apiProxyPrefix string, staticPrefix string, filter *FilterServer, cfg *client.Config) (*ProxyServer, error) {
	host := cfg.Host
	if !strings.HasSuffix(host, "/") {
		host = host + "/"
	}
	target, err := url.Parse(host)
	if err != nil {
		return nil, err
	}
	proxy := newProxy(target)
	if proxy.Transport, err = client.TransportFor(cfg); err != nil {
		return nil, err
	}
	proxyServer := http.Handler(proxy)
	if filter != nil {
		proxyServer = filter.HandlerFor(proxyServer)
	}

	if !strings.HasPrefix(apiProxyPrefix, "/api") {
		proxyServer = stripLeaveSlash(apiProxyPrefix, proxyServer)
	}

	mux := http.NewServeMux()
	mux.Handle(apiProxyPrefix, proxyServer)
	if filebase != "" {
		// Require user to explicitly request this behavior rather than
		// serving their working directory by default.
		mux.Handle(staticPrefix, newFileHandler(staticPrefix, filebase))
	}
	return &ProxyServer{handler: mux, port: port}, nil
}
示例#22
0
func main() {
	o := ParseOpts()
	if o.ShowVersion {
		fmt.Println("sms-api-server", Version)
		os.Exit(0)
	}
	tx := &smpp.Transceiver{
		Addr:   o.SMPPAddr,
		User:   os.Getenv("SMPP_USER"),
		Passwd: os.Getenv("SMPP_PASSWD"),
	}
	exit := make(chan os.Signal, 1)
	signal.Notify(exit, os.Interrupt, os.Kill)
	go func() {
		<-exit
		tx.Close()
		os.Exit(0)
	}()
	if o.ClientTLS {
		host, _, _ := net.SplitHostPort(tx.Addr)
		tx.TLS = &tls.Config{
			ServerName: host,
		}
		if o.ClientTLSInsecure {
			tx.TLS.InsecureSkipVerify = true
		}
	}
	api := &apiserver.Handler{Prefix: o.APIPrefix, Tx: tx}
	conn := api.Register(http.DefaultServeMux)
	go func() {
		for c := range conn {
			m := fmt.Sprintf("SMPP connection status to %s: %s",
				o.SMPPAddr, c.Status())
			if err := c.Error(); err != nil {
				m = fmt.Sprintf("%s (%v)", m, err)
			}
			log.Println(m)
		}
	}()
	if o.PublicDir != "" {
		fs := http.FileServer(http.Dir(o.PublicDir))
		http.Handle("/", http.StripPrefix(o.APIPrefix, fs))
	}
	mux := http.Handler(http.DefaultServeMux)
	if o.Log {
		var l *log.Logger
		if o.LogTS {
			l = log.New(os.Stderr, "", log.LstdFlags)
		} else {
			l = log.New(os.Stderr, "", 0)
		}
		mux = httplog.ApacheCombinedFormat(l)(mux.ServeHTTP)
	}
	err := ListenAndServe(o, mux)
	if err != nil {
		log.Fatal(err)
	}
}
示例#23
0
func runReplicaAPI(context *cli.Context) {
	router := http.Handler(replica.NewRouter())
	router = handlers.LoggingHandler(os.Stdout, router)
	router = handlers.ProxyHeaders(router)
	listen := "0.0.0.0:80"
	logrus.Infof("Listening on %s", listen)
	err := http.ListenAndServe(listen, router)
	logrus.Fatalf("API returned with error: %v", err)
}
示例#24
0
// TestHealthHandler ensures that our handler implementation correct protects
// the web application when things aren't so healthy.
func TestHealthHandler(t *testing.T) {
	// clear out existing checks.
	DefaultRegistry = NewRegistry()

	// protect an http server
	handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusNoContent)
	}))

	// wrap it in our health handler
	handler = Handler(handler)

	// use this swap check status
	updater := NewStatusUpdater()
	Register("test_check", updater)

	// now, create a test server
	server := httptest.NewServer(handler)

	checkUp := func(t *testing.T, message string) {
		resp, err := http.Get(server.URL)
		if err != nil {
			t.Fatalf("error getting success status: %v", err)
		}
		defer resp.Body.Close()

		if resp.StatusCode != http.StatusNoContent {
			t.Fatalf("unexpected response code from server when %s: %d != %d", message, resp.StatusCode, http.StatusNoContent)
		}
		// NOTE(stevvooe): we really don't care about the body -- the format is
		// not standardized or supported, yet.
	}

	checkDown := func(t *testing.T, message string) {
		resp, err := http.Get(server.URL)
		if err != nil {
			t.Fatalf("error getting down status: %v", err)
		}
		defer resp.Body.Close()

		if resp.StatusCode != http.StatusServiceUnavailable {
			t.Fatalf("unexpected response code from server when %s: %d != %d", message, resp.StatusCode, http.StatusServiceUnavailable)
		}
	}

	// server should be up
	checkUp(t, "initial health check")

	// now, we fail the health check
	updater.Update(fmt.Errorf("the server is now out of commission"))
	checkDown(t, "server should be down") // should be down

	// bring server back up
	updater.Update(nil)
	checkUp(t, "when server is back up") // now we should be back up.
}
示例#25
0
文件: app.go 项目: jackwhit3/gotty
func (app *App) Run() error {
	if app.options.PermitWrite {
		log.Printf("Permitting clients to write input to the PTY.")
	}

	path := ""
	if app.options.RandomUrl {
		path += "/" + generateRandomString(8)
	}

	endpoint := net.JoinHostPort(app.options.Address, app.options.Port)

	wsHandler := http.HandlerFunc(app.handleWS)
	staticHandler := http.FileServer(
		&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"},
	)

	var siteMux = http.NewServeMux()
	siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler))
	siteMux.Handle(path+"/ws", wsHandler)

	siteHandler := http.Handler(siteMux)

	if app.options.Credential != "" {
		log.Printf("Using Basic Authentication")
		siteHandler = wrapBasicAuth(siteHandler, app.options.Credential)
	}

	siteHandler = wrapLogger(siteHandler)

	log.Printf(
		"Server is starting with command: %s",
		strings.Join(app.options.Command, " "),
	)
	if app.options.Address != "" {
		log.Printf(
			"URL: %s", (&url.URL{Scheme: "http", Host: endpoint, Path: path + "/"}).String(),
		)
	} else {
		for _, address := range listAddresses() {
			log.Printf(
				"URL: %s",
				(&url.URL{
					Scheme: "http",
					Host:   net.JoinHostPort(address, app.options.Port),
					Path:   path + "/",
				}).String(),
			)
		}
	}
	if err := http.ListenAndServe(endpoint, siteHandler); err != nil {
		return err
	}

	return nil
}
示例#26
0
文件: umsatz.go 项目: umsatz/api
func newUmsatzServer(db *sql.DB, currencyAddress string) http.Handler {
	r := http.DefaultServeMux

	r.Handle("/fiscalPeriods/", http.StripPrefix("/fiscalPeriods/", newFiscalPeriodApp(db)))
	r.Handle("/positions/", http.StripPrefix("/positions/", newPositionsApp(db, currencyAddress)))
	r.Handle("/accounts/", http.StripPrefix("/accounts/", newAccountingApp(db)))

	r.Handle("/", http.HandlerFunc(routingHandler))

	return http.Handler(logHandler(jsonHandler(r)))
}
示例#27
0
文件: server.go 项目: eklementev/esp
// NewServer construct rest server listening specific host and port and routes requests by passed routes
func NewServer(props properties.Properties, routes PathHandlers) error {
	bind := props.Get("rest.address") + ":" + props.Get("rest.port")

	log.Println("start rest server on", bind)
	listener, err := net.Listen("tcp", bind)
	if err != nil {
		return err
	}

	s := &server{
		listener: listener,
		m:        &sync.Mutex{},
		alive:    true,
		wg:       &sync.WaitGroup{},
	}

	kit.SafeGo(func() error {
		router := mux.NewRouter()
		for path := range routes {
			mh := handlers.MethodHandler{}
			for method := range routes[path] {
				log.Printf("setup rest handler %v %v\n", method, path)
				mh[method] = s.wrapHandler(routes[path][method])
			}
			router.Path(path).Handler(mh)
		}

		handler := http.Handler(router)

		compression, err := strconv.ParseBool(props.Get("rest.compression"))
		if err == nil && compression {
			log.Println("enable compression for rest server")
			handler = handlers.CompressHandler(handler)
		} else {
			log.Println("no compression for rest server")
		}

		log.Println("rest server serves")
		err = http.Serve(listener, handler)
		if err != nil {
			return err
		}

		return nil
	})

	kit.SafeGo(func() error {
		<-registry.DoneChannel()
		s.Stop()
		return nil
	})

	return nil
}
示例#28
0
func TestMain(m *testing.M) {
	cache, err := populateExchangeRateCache("data/eurofxref-hist.xml")
	if err != nil {
		log.Fatalf("Unable to populate cache: %v\n", err)
	}

	TestServer = testServer{
		server: httptest.NewServer(http.Handler(rateHTTP.Handler(cache))),
	}
	ret := m.Run()
	os.Exit(ret)
}
示例#29
0
// Router constructs the main Devd router that serves all requests
func (dd *Devd) Router(logger termlog.TermLog, templates *template.Template) (http.Handler, error) {
	mux := http.NewServeMux()
	hasGlobal := false

	ci := inject.CopyInject{}
	if dd.HasLivereload() {
		ci = livereload.Injector
	}

	for match, route := range dd.Routes {
		if match == "/" {
			hasGlobal = true
		}
		handler := dd.WrapHandler(
			logger,
			route.Endpoint.Handler(templates, ci),
		)
		handler = http.StripPrefix(route.Path, handler)
		mux.Handle(match, handler)
	}
	if dd.HasLivereload() {
		lr := livereload.NewServer("livereload", logger)
		mux.Handle(livereload.EndpointPath, lr)
		mux.Handle(livereload.ScriptPath, http.HandlerFunc(lr.ServeScript))
		if dd.LivereloadRoutes {
			err := WatchRoutes(dd.Routes, lr, dd.Excludes, logger)
			if err != nil {
				return nil, fmt.Errorf("Could not watch routes for livereload: %s", err)
			}
		}
		if len(dd.WatchPaths) > 0 {
			err := WatchPaths(dd.WatchPaths, dd.Excludes, lr, logger)
			if err != nil {
				return nil, fmt.Errorf("Could not watch path for livereload: %s", err)
			}
		}
		dd.lrserver = lr
	}
	if !hasGlobal {
		mux.Handle(
			"/",
			dd.WrapHandler(logger, HandleNotFound(templates)),
		)
	}
	var h = http.Handler(mux)
	if dd.Credentials != nil {
		h = httpauth.SimpleBasicAuth(
			dd.Credentials.username, dd.Credentials.password,
		)(h)
	}
	return hostPortStrip(h), nil
}
func TestComposeMiddlewareVariants(t *testing.T) {
	fn1 := nullHandlerFunc
	fn2 := http.HandlerFunc(nullHandlerFunc)
	fn3 := http.Handler(&stubHandler{})
	fn4 := stubMiddleware1
	fn5 := stubMiddleware2
	fn6 := stubMiddleware3
	fn7 := Middleware(&stubMiddleware{})
	fn8 := MiddlewareFunc(stubMiddleware2)
	fn9 := func(h http.Handler) http.Handler { return h }

	Compose(fn1, fn2, fn3, fn4, fn5, fn6, fn7, fn8, fn9)
}