Пример #1
0
// launch unix and tcp servers
func init() {
	mux := http.NewServeMux()
	rpcserver.RegisterRPCFuncs(mux, Routes)
	wm := rpcserver.NewWebsocketManager(Routes, nil)
	mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
	go func() {
		_, err := rpcserver.StartHTTPServer(tcpAddr, mux)
		if err != nil {
			panic(err)
		}
	}()

	mux2 := http.NewServeMux()
	rpcserver.RegisterRPCFuncs(mux2, Routes)
	wm = rpcserver.NewWebsocketManager(Routes, nil)
	mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
	go func() {
		_, err := rpcserver.StartHTTPServer(unixAddr, mux2)
		if err != nil {
			panic(err)
		}
	}()

	// wait for servers to start
	time.Sleep(time.Second * 2)

}
Пример #2
0
// Load
func (p *Application) Load(fn ActionLoadFunc) {
	// hosts
	for _, m := range p.Hosts {
		if _, ok := muxList[m.Listen]; !ok {
			muxList[m.Listen] = http.NewServeMux()
		}

		if m.Path == "/" {
			muxList[m.Listen].Handle(m.Path, http.FileServer(http.Dir(m.Root)))
		} else {
			// To serve a directory on disk (/tmp) under an alternate URL
			// path (/tmpfiles/), use StripPrefix to modify the request
			// URL's path before the FileServer sees it:
			muxList[m.Listen].Handle(m.Path, http.StripPrefix(m.Path, http.FileServer(http.Dir(m.Root))))
		}
	}

	// modules
	for mName, m := range p.Modules {
		if _, ok := muxList[m.Listen]; !ok {
			muxList[m.Listen] = http.NewServeMux()
		}

		muxList[m.Listen].HandleFunc("/"+mName+"/", NewHandler(fn))
	}
}
Пример #3
0
func main() {
	cfg := new(Config)
	flagx.Parse(cfg)

	InitMongo(cfg.Mongo, cfg.Db)
	mux := http.NewServeMux()
	Handler(mux)
	if cfg.Key != "" {
		done := make(chan bool)
		go func() {
			err := http.ListenAndServeTLS(":443", cfg.Crt, cfg.Key, mux)
			if err != nil {
				logex.Error(err)
			}
			done <- err == nil
		}()
		d := true
		select {
		case <-time.After(time.Second):
		case d = <-done:
		}
		if d {
			mux := http.NewServeMux()
			RedirectHandler(mux)
			if err := http.ListenAndServe(cfg.Listen, mux); err != nil {
				logex.Error(err)
			}
			return
		}
	}
	if err := http.ListenAndServe(cfg.Listen, mux); err != nil {
		logex.Error(err)
	}
}
Пример #4
0
func TestIntegSingle(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {})
	srvr := httptest.NewServer(mux)

	u, err := url.Parse(srvr.URL)
	if err != nil {
		t.Fatal(err)
	}

	urls := []*url.URL{u}
	rule := &porter.Rule{"127.0.0.1", urls}

	p, err := porter.New([]*porter.Rule{rule})
	if err != nil {
		t.Fatal(err)
	}

	pMux := http.NewServeMux()
	pMux.Handle("/", p)
	pSrvr := httptest.NewServer(pMux)

	res, err := http.Get(pSrvr.URL + "/")
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()

	want := http.StatusOK
	got := res.StatusCode
	if want != got {
		t.Fatalf("want %d, got %d", want, got)
	}
}
Пример #5
0
// TestInstallSwaggerAPI verifies that the swagger api is added
// at the proper endpoint.
func TestInstallSwaggerAPI(t *testing.T) {
	etcdserver, _, assert := setUp(t)
	defer etcdserver.Terminate(t)

	mux := http.NewServeMux()
	server := &GenericAPIServer{}
	server.HandlerContainer = NewHandlerContainer(mux, nil)

	// Ensure swagger isn't installed without the call
	ws := server.HandlerContainer.RegisteredWebServices()
	if !assert.Equal(len(ws), 0) {
		for x := range ws {
			assert.NotEqual("/swaggerapi", ws[x].RootPath(), "SwaggerAPI was installed without a call to InstallSwaggerAPI()")
		}
	}

	// Install swagger and test
	server.InstallSwaggerAPI()
	ws = server.HandlerContainer.RegisteredWebServices()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}

	// Empty externalHost verification
	mux = http.NewServeMux()
	server.HandlerContainer = NewHandlerContainer(mux, nil)
	server.ExternalAddress = ""
	server.ClusterIP = net.IPv4(10, 10, 10, 10)
	server.PublicReadWritePort = 1010
	server.InstallSwaggerAPI()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}
}
Пример #6
0
func (s *TestHttpService) startPod() error {
	unsecurePodServer := http.NewServeMux()
	unsecurePodServer.HandleFunc("/", s.handleHelloPod)
	unsecurePodServer.HandleFunc("/"+s.PodTestPath, s.handleHelloPodTest)
	unsecurePodServer.Handle("/"+s.PodWebSocketPath, websocket.Handler(s.handleWebSocket))

	if err := s.startServing(s.PodHttpAddr, unsecurePodServer); err != nil {
		return err
	}

	alternatePodServer := http.NewServeMux()
	alternatePodServer.HandleFunc("/", s.handleHelloPod2)
	alternatePodServer.HandleFunc("/"+s.PodTestPath, s.handleHelloPod2)

	if err := s.startServing(s.AlternatePodHttpAddr, alternatePodServer); err != nil {
		return err
	}

	securePodServer := http.NewServeMux()
	securePodServer.HandleFunc("/", s.handleHelloPodSecure)
	securePodServer.HandleFunc("/"+s.PodTestPath, s.handleHelloPodTestSecure)
	securePodServer.Handle("/"+s.PodWebSocketPath, websocket.Handler(s.handleWebSocket))
	if err := s.startServingTLS(s.PodHttpsAddr, s.PodHttpsCert, s.PodHttpsKey, s.PodHttpsCaCert, securePodServer); err != nil {
		return err
	}

	return nil
}
Пример #7
0
func main() {
	// config parsing
	flag.Parse()
	err := parseConfigFile()
	if err != nil {
		l.Fatal(err)
	}

	// log configuration
	w, err := getLogWriter()
	if err != nil {
		l.Fatal(err)
	}
	defer (*w).Close()

	l = log.New(w, "", log.LstdFlags|log.Lshortfile)

	go handleSignals()
	go EventSourceClientQueryProcess()

	publicMux := http.NewServeMux()
	publicMux.HandleFunc("/", eventSourceHandler)
	go http.ListenAndServe(config.ListenPublic, publicMux)

	internalMux := http.NewServeMux()
	internalMux.HandleFunc("/message", internalHandler)
	l.Fatal(http.ListenAndServe(config.ListenInternal, internalMux))

}
Пример #8
0
func TestDispatchFailed(t *testing.T) {
	muxV1 := http.NewServeMux()
	muxV2 := http.NewServeMux()

	apiV1 := NewVersion("v1", muxV1)
	apiV2 := NewVersion("v2", muxV2)

	vendor, err := NewVendorMiddleware("mybusiness.com", apiV1, apiV2)
	if err != nil {
		t.Error("Unexpected error:", err)
		t.Fail()
	}

	_, err = vendor.version("v1")

	if err != nil {
		t.Error("Unexpected error:", err)
		t.Fail()
	}

	_, err = vendor.version("v2")

	if err != nil {
		t.Error("Unexpected error:", err)
		t.Fail()
	}

	_, err = vendor.version("v99")

	if err != ErrVersionNotFound {
		t.Error("Expected a not found error:", err)
		t.Fail()
	}
}
Пример #9
0
func (h WebserviceHandler) StartServer() {
	commonHandlers := alice.New(context.ClearHandler, h.LoggingHandler, h.RecoverHandler, h.NoCacheHandler)
	authHandlers := commonHandlers.Append(h.AuthHandler)
	h.mrouter = NewRouter()
	h.frouter = http.NewServeMux()
	h.frouter.Handle("/", http.FileServer(http.Dir(h.config.GetHTTPDir())))

	h.mrouter.Get("/item.html", authHandlers.ThenFunc(h.ItemHTML))
	h.mrouter.Get("/services/items", commonHandlers.ThenFunc(h.GetItems))
	h.mrouter.Get("/services/bestComments", commonHandlers.Append(h.GzipJsonHandler).ThenFunc(h.GetBestComments))
	h.mrouter.Post("/services/register", commonHandlers.ThenFunc(h.Register))
	h.mrouter.Post("/services/login", commonHandlers.ThenFunc(h.Login))
	h.mrouter.Get("/services/confirm", commonHandlers.ThenFunc(h.ConfirmEmail))
	h.mrouter.Get("/services/itemInfo", commonHandlers.Append(h.GzipJsonHandler).ThenFunc(h.GetItemInfo))
	h.mrouter.Get("/services/logout", authHandlers.ThenFunc(h.Logout))
	h.mrouter.Get("/services/like", authHandlers.ThenFunc(h.PostLike))
	h.mrouter.Post("/services/comment", authHandlers.ThenFunc(h.PostComment))
	h.mrouter.Get("/services/deletecomment", authHandlers.ThenFunc(h.DeleteComment))
	h.mrouter.Post("/services/deployFront", commonHandlers.Append(h.BasicAuth).ThenFunc(h.DeployFront))

	var err error

	r := http.NewServeMux()
	r.HandleFunc("/", h.FrontHandler)
	go func() {
		log.Infof("Server launched on port %s", h.config.GetServerPort())
		err = http.ListenAndServe(":"+h.config.GetServerPort(), r)
		if err != nil {
			panic(err.Error())
		}
	}()

}
Пример #10
0
// TestInstallSwaggerAPI verifies that the swagger api is added
// at the proper endpoint.
func TestInstallSwaggerAPI(t *testing.T) {
	master, _, assert := setUp(t)
	mux := http.NewServeMux()
	master.handlerContainer = NewHandlerContainer(mux)

	// Ensure swagger isn't installed without the call
	ws := master.handlerContainer.RegisteredWebServices()
	if !assert.Equal(len(ws), 0) {
		for x := range ws {
			assert.NotEqual("/swaggerapi", ws[x].RootPath(), "SwaggerAPI was installed without a call to InstallSwaggerAPI()")
		}
	}

	// Install swagger and test
	master.InstallSwaggerAPI()
	ws = master.handlerContainer.RegisteredWebServices()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}

	// Empty externalHost verification
	mux = http.NewServeMux()
	master.handlerContainer = NewHandlerContainer(mux)
	master.externalHost = ""
	master.clusterIP = net.IPv4(10, 10, 10, 10)
	master.publicReadWritePort = 1010
	master.InstallSwaggerAPI()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}
}
Пример #11
0
// StartHTTP start listen http.
func StartHTTP() {
	// external
	httpServeMux := http.NewServeMux()
	// 2
	httpServeMux.HandleFunc("/2/server/get", GetServer2)
	// 1.0
	httpServeMux.HandleFunc("/1/server/get", GetServer)
	httpServeMux.HandleFunc("/1/msg/get", GetOfflineMsg)
	httpServeMux.HandleFunc("/1/time/get", GetTime)
	// old
	httpServeMux.HandleFunc("/server/get", GetServer0)
	httpServeMux.HandleFunc("/msg/get", GetOfflineMsg0)
	httpServeMux.HandleFunc("/time/get", GetTime0)
	// internal
	httpAdminServeMux := http.NewServeMux()
	// 1.0
	httpAdminServeMux.HandleFunc("/1/admin/push/private", PushPrivate)
	httpAdminServeMux.HandleFunc("/1/admin/push/mprivate", PushMultiPrivate)
	httpAdminServeMux.HandleFunc("/1/admin/msg/del", DelPrivate)
	// old
	httpAdminServeMux.HandleFunc("/admin/push", PushPrivate)
	httpAdminServeMux.HandleFunc("/admin/msg/clean", DelPrivate)
	for _, bind := range Conf.HttpBind {
		log.Info("start http listen addr:\"%s\"", bind)
		go httpListen(httpServeMux, bind)
	}
	for _, bind := range Conf.AdminBind {
		log.Info("start admin http listen addr:\"%s\"", bind)
		go httpListen(httpAdminServeMux, bind)
	}
}
Пример #12
0
func (s *apiSvc) getMux() *http.ServeMux {
	mux := http.NewServeMux()

	getApiMux := http.NewServeMux()
	getApiMux.HandleFunc("/api/system/config", s.getSystemConfig)
	getApiMux.HandleFunc("/api/system/config/insync", s.getSystemConfigInSync)
	getApiMux.HandleFunc("/api/system/connections", s.getSystemConnections)
	getApiMux.HandleFunc("/api/system/pins/status", s.getPinStatus)
	getApiMux.HandleFunc("/api/verify/deviceid", s.getDeviceID) // id
	getApiMux.HandleFunc("/api/db/browse", s.getDBBrowse)       // folderID pathPrefix

	postApiMux := http.NewServeMux()
	postApiMux.HandleFunc("/api/system/config", s.postSystemConfig)       // <body>
	postApiMux.HandleFunc("/api/verify/humansize", s.postVerifyHumanSize) // <body>

	apiMux := getMethodHandler(getApiMux, postApiMux)
	mux.Handle("/api/", apiMux)

	// Serve compiled in assets unless an asset directory was set (for development)
	mux.Handle("/", embeddedStatic{
		assetDir: s.assetDir,
		assets:   autogenerated.Assets(),
	})

	return mux
}
Пример #13
0
func Start(config *Config) error {
	if err := clone(config); err != nil {
		return err
	}
	handler := handler(config)

	ops := http.NewServeMux()
	if config.AllowHooks {
		ops.Handle("/hooks/", prometheus.InstrumentHandler("hooks", http.StripPrefix("/hooks", hooksHandler(config))))
	}
	/*ops.Handle("/reflect/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer r.Body.Close()
		fmt.Fprintf(os.Stdout, "%s %s\n", r.Method, r.URL)
		io.Copy(os.Stdout, r.Body)
	}))*/
	ops.Handle("/metrics", prometheus.UninstrumentedHandler())
	healthz.InstallHandler(ops)

	mux := http.NewServeMux()
	mux.Handle("/", prometheus.InstrumentHandler("git", handler))
	mux.Handle("/_/", http.StripPrefix("/_", ops))

	log.Printf("Serving %s on %s", config.Home, config.Listen)
	return http.ListenAndServe(config.Listen, mux)
}
Пример #14
0
func TestAddRoute(t *testing.T) {
	m := NewMux("", http.NewServeMux())
	r := m.Add("GET", "products/{action}/{id}", dummy)
	assertEqual(t, r.Method, "GET")
	assertEqual(t, r.Pattern, "products/{action}/{id}")
	assertEqual(t, r.Name, "")
	if r.Handler == nil {
		t.Fatalf("Expected dummy handler, got nil")
	}
	if r.mux != m {
		t.Fatalf("Expected original muxer, got %v", r.mux)
	}

	m2 := NewMux("/api", http.NewServeMux())
	r2 := m2.Add("PUT", "/scores/{id}", dummy)
	assertEqual(t, r2.Method, "PUT")
	assertEqual(t, r2.Pattern, "scores/{id}")

	defer func() {
		if err := recover(); err == nil {
			t.Fatalf("Expected panic, got no error instead")
		}
	}()
	// should panic because of the same method + pattern
	m2.Add("PUT", "/scores/{id}", dummy)
}
Пример #15
0
// Start starts up the server.
func (a *App) Start() {
	a.gamekeeper.init()

	// Load all the html templates
	a.templates = template.Must(template.ParseFiles("static/index.html"))

	// Initialize the websocket upgrader
	a.upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	// Initialize the http servers.
	a.publicServer = http.Server{
		Addr:    publicListenAddress,
		Handler: http.HandlerFunc(a.servePublicHTTP),
	}
	a.internalServer = http.Server{
		Addr:    internalListenAddress,
		Handler: http.HandlerFunc(a.serveInternalHTTP),
	}
	a.publicMux = http.NewServeMux()
	a.internalMux = http.NewServeMux()

	// Setup the routes.
	a.publicMux.HandleFunc("/connect", a.websocketUpgradeRoute)
	a.publicMux.HandleFunc("/time", a.time)
	a.publicMux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
	a.publicMux.HandleFunc("/", a.index)

	go a.listenAndServe(&a.publicServer)
	go a.listenAndServe(&a.internalServer)

	a.stopped.Add(1)
}
func main() {
	var (
		httpAddr   = flag.String("http", "0.0.0.0:80", "HTTP service address.")
		healthAddr = flag.String("health", "0.0.0.0:81", "Health service address.")
		secret     = flag.String("secret", "secret", "JWT signing secret.")
	)
	flag.Parse()

	log.Println("Starting server...")
	log.Printf("Health service listening on %s", *healthAddr)
	log.Printf("HTTP service listening on %s", *httpAddr)

	errChan := make(chan error, 10)

	hmux := http.NewServeMux()
	hmux.HandleFunc("/healthz", health.HealthzHandler)
	hmux.HandleFunc("/readiness", health.ReadinessHandler)
	hmux.HandleFunc("/healthz/status", health.HealthzStatusHandler)
	hmux.HandleFunc("/readiness/status", health.ReadinessStatusHandler)
	healthServer := manners.NewServer()
	healthServer.Addr = *healthAddr
	healthServer.Handler = handlers.LoggingHandler(hmux)

	go func() {
		errChan <- healthServer.ListenAndServe()
	}()

	mux := http.NewServeMux()
	mux.HandleFunc("/", handlers.HelloHandler)
	mux.Handle("/login", handlers.LoginHandler(*secret, user.DB))
	mux.Handle("/secure", handlers.JWTAuthHandler(handlers.HelloHandler))
	mux.Handle("/version", handlers.VersionHandler(version))

	httpServer := manners.NewServer()
	httpServer.Addr = *httpAddr
	httpServer.Handler = handlers.LoggingHandler(mux)

	go func() {
		errChan <- httpServer.ListenAndServe()
	}()

	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

	for {
		select {
		case err := <-errChan:
			if err != nil {
				log.Fatal(err)
			}
		case s := <-signalChan:
			log.Println(fmt.Sprintf("Captured %v. Exiting...", s))
			health.SetReadinessStatus(http.StatusServiceUnavailable)
			httpServer.BlockingClose()
			os.Exit(0)
		}
	}
}
Пример #17
0
func TestHTTP_Fallback_Disabled(t *testing.T) {
	handler1 := http.NewServeMux()
	handler2 := http.NewServeMux()
	handler3 := http.NewServeMux()

	coreConfig := &vault.CoreConfig{
		LogicalBackends: map[string]logical.Factory{
			"transit": transit.Factory,
		},
		ClusterAddr: "empty",
	}

	// Chicken-and-egg: Handler needs a core. So we create handlers first, then
	// add routes chained to a Handler-created handler.
	cores := vault.TestCluster(t, []http.Handler{handler1, handler2, handler3}, coreConfig, true)
	for _, core := range cores {
		defer core.CloseListeners()
	}
	handler1.Handle("/", Handler(cores[0].Core))
	handler2.Handle("/", Handler(cores[1].Core))
	handler3.Handle("/", Handler(cores[2].Core))

	// make it easy to get access to the active
	core := cores[0].Core
	vault.TestWaitActive(t, core)

	root := cores[0].Root

	addrs := []string{
		fmt.Sprintf("https://127.0.0.1:%d", cores[1].Listeners[0].Address.Port),
		fmt.Sprintf("https://127.0.0.1:%d", cores[2].Listeners[0].Address.Port),
	}

	for _, addr := range addrs {
		config := api.DefaultConfig()
		config.Address = addr
		config.HttpClient = cleanhttp.DefaultClient()
		config.HttpClient.Transport.(*http.Transport).TLSClientConfig = cores[0].TLSConfig
		client, err := api.NewClient(config)
		if err != nil {
			t.Fatal(err)
		}
		client.SetToken(root)

		secret, err := client.Auth().Token().LookupSelf()
		if err != nil {
			t.Fatal(err)
		}
		if secret == nil {
			t.Fatal("secret is nil")
		}
		if secret.Data["id"].(string) != root {
			t.Fatal("token mismatch")
		}
	}
}
Пример #18
0
func main() {
	//Loads environment variables from a .env file
	godotenv.Load("environment")

	var (
		clientID     = getEnv("OAUTH2_CLIENT_ID", "client_id")
		clientSecret = getEnv("OAUTH2_CLIENT_SECRET", "client_secret")
		redirectURL  = getEnv("OAUTH2_REDIRECT_URL", "redirect_url")
	)

	secureMux := http.NewServeMux()

	// Routes that require a logged in user
	// can be protected by using a separate route handler
	// If the user is not authenticated, they will be
	// redirected to the login path.
	secureMux.HandleFunc("/restrict", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		fmt.Fprintf(w, "OK: %s", token.Access())
	})

	secure := negroni.New()
	secure.Use(oauth2.LoginRequired())
	secure.UseHandler(secureMux)

	n := negroni.New()
	n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123"))))
	n.Use(oauth2.Google(&oauth2.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		RedirectURL:  redirectURL,
		Scopes:       []string{"https://www.googleapis.com/auth/drive"},
	}))

	router := http.NewServeMux()

	//routes added to mux do not require authentication
	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		if token == nil || !token.Valid() {
			fmt.Fprintf(w, "not logged in, or the access token is expired")
			return
		}
		fmt.Fprintf(w, "logged in")
		return
	})

	//There is probably a nicer way to handle this than repeat the restricted routes again
	//of course, you could use something like gorilla/mux and define prefix / regex etc.
	router.Handle("/restrict", secure)

	n.UseHandler(router)

	n.Run(":3000")
}
Пример #19
0
func TestDiscoveryAtAPIS(t *testing.T) {
	master, etcdserver, config, assert := setUp(t)
	defer etcdserver.Terminate(t)

	// ================= preparation for master.init() ======================
	portRange := util.PortRange{Base: 10, Size: 10}
	master.serviceNodePortRange = portRange

	_, ipnet, err := net.ParseCIDR("192.168.1.1/24")
	if !assert.NoError(err) {
		t.Errorf("unexpected error: %v", err)
	}
	master.serviceClusterIPRange = ipnet

	mh := apiserver.MuxHelper{Mux: http.NewServeMux()}
	master.muxHelper = &mh
	master.rootWebService = new(restful.WebService)

	master.handlerContainer = restful.NewContainer()

	master.mux = http.NewServeMux()
	master.requestContextMapper = api.NewRequestContextMapper()
	// ======================= end of preparation ===========================

	master.init(&config)
	server := httptest.NewServer(master.handlerContainer.ServeMux)
	resp, err := http.Get(server.URL + "/apis")
	if !assert.NoError(err) {
		t.Errorf("unexpected error: %v", err)
	}

	assert.Equal(http.StatusOK, resp.StatusCode)

	groupList := unversioned.APIGroupList{}
	assert.NoError(decodeResponse(resp, &groupList))
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	expectGroupName := "extensions"
	expectVersions := []unversioned.GroupVersionForDiscovery{
		{
			GroupVersion: testapi.Extensions.GroupAndVersion(),
			Version:      testapi.Extensions.Version(),
		},
	}
	expectPreferredVersion := unversioned.GroupVersionForDiscovery{
		GroupVersion: config.StorageVersions["extensions"],
		Version:      apiutil.GetVersion(config.StorageVersions["extensions"]),
	}
	assert.Equal(expectGroupName, groupList.Groups[0].Name)
	assert.Equal(expectVersions, groupList.Groups[0].Versions)
	assert.Equal(expectPreferredVersion, groupList.Groups[0].PreferredVersion)
}
Пример #20
0
func init() {
	cmd := exec.Command("tsdbrelay", "-l=:5555", "-b=localhost:5557", "-r=localhost:6555", "-t=localhost:5556", "-denormalize=os.cpu__host")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Start()
	if err != nil {
		fatal(err)
	}
	relay1 = cmd.Process
	cmd = exec.Command("tsdbrelay", "-l=:6555", "-b=localhost:6557", "-r=localhost:5555", "-t=localhost:6556", "-denormalize=os.cpu__host")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err = cmd.Start()
	if err != nil {
		fatal(err)
	}
	relay2 = cmd.Process
	dc1BosunMux := http.NewServeMux()
	dc1BosunMux.HandleFunc("/api/index", handleBosun(dc1BosunReceived))
	dc1BosunMux.HandleFunc("/api/metadata/put", handleMeta(&gotMeta1))
	go func() {
		fatal("DC1-Bosun", http.ListenAndServe(":5557", dc1BosunMux))
	}()

	dc2BosunMux := http.NewServeMux()
	dc2BosunMux.HandleFunc("/api/index", handleBosun(dc2BosunReceived))
	dc2BosunMux.HandleFunc("/api/metadata/put", handleMeta(&gotMeta2))
	go func() {
		fatal("DC2-Bosun", http.ListenAndServe(":6557", dc2BosunMux))
	}()

	dc1TsdbMux := http.NewServeMux()
	dc1TsdbMux.HandleFunc("/api/put", handleTsdb(dc1TsdbReceived))

	go func() {
		fatal("DC1-TSDB", http.ListenAndServe(":5556", dc1TsdbMux))
	}()

	dc2TsdbMux := http.NewServeMux()
	dc2TsdbMux.HandleFunc("/api/put", handleTsdb(dc2TsdbReceived))
	go func() {
		fatal("DC3-TSDB", http.ListenAndServe(":6556", dc2TsdbMux))
	}()

	ch := make(chan os.Signal)
	signal.Notify(ch, os.Kill, os.Interrupt)
	go func() {
		<-ch
		fatal("INTERRUPT RECIEVED")
	}()
	time.Sleep(2 * time.Second)
}
Пример #21
0
func (s *StdWeb) initMux(settings *Settings) {
	s.authPath = fmt.Sprintf("/_stdweb/auth/%s", s.key)

	s.authMux = http.NewServeMux()
	s.authMux.HandleFunc("/", s.baseHandler)
	s.authMux.Handle("/_stdweb/s/", http.StripPrefix("/_stdweb/s/", http.FileServer(static.Resources(settings.StaticDir))))
	s.authMux.HandleFunc("/_stdweb/event", s.eventHandler)
	s.authMux.HandleFunc("/_stdweb/updates", s.updatesHandler)

	s.unauthMux = http.NewServeMux()
	s.unauthMux.Handle("/", s.checkAuth(s.authMux))
	s.unauthMux.HandleFunc(s.authPath, s.authHandler)
}
Пример #22
0
func TestVendorInitFailed(t *testing.T) {
	muxV1 := http.NewServeMux()
	muxV1Dup := http.NewServeMux()

	apiV1 := NewVersion("v1", muxV1)
	apiV1Dup := NewVersion("v1", muxV1Dup)

	_, err := NewVendorMiddleware("mybusiness.com", apiV1, apiV1Dup)
	if err != ErrVersionDuplicate {
		t.Error("Expected a duplicate error")
		t.Fail()
	}
}
Пример #23
0
func TestShowPosts(t *testing.T) {
	testutil.CleanUp()
	defer testutil.CleanUp()

	mux := http.NewServeMux()
	handleAuthenticatedUserItems(mux)
	handleTeams(mux)
	serverMine := httptest.NewServer(mux)
	defer serverMine.Close()
	mux = http.NewServeMux()
	handleAuthenticatedUserItemsWithTeam(mux)
	serverTeam := httptest.NewServer(mux)
	defer serverTeam.Close()
	err := os.Setenv("QIITA_ACCESS_TOKEN", "XXXXXXXXXXXX")
	if err != nil {
		log.Fatal(err)
	}
	client := api.NewClient(func(subDomain, path string) (url string) {
		switch subDomain {
		case "":
			url = fmt.Sprintf("%s%s%s", serverMine.URL, "/api/v2", path)
		case "increments":
			url = fmt.Sprintf("%s%s%s", serverTeam.URL, "/api/v2", path)
		default:
			log.Fatalf("wrong sub domain \"%s\"", subDomain)
		}
		return
	}, inf)

	testutil.ShouldExistFile(t, 0)

	buf := bytes.NewBuffer([]byte{})
	errBuf := bytes.NewBuffer([]byte{})
	app := command.New(inf, client, buf, errBuf)
	app.Run([]string{"qiitactl", "show", "posts"})
	e := errBuf.Bytes()
	if len(e) != 0 {
		t.Fatal(string(e))
	}

	testutil.ShouldExistFile(t, 0)

	if string(buf.Bytes()) != `Posts in Qiita:
4bd431809afb1bb99e4f 2000/01/01 Example Title
Posts in Qiita:Team (Increments Inc.):
4bd431809afb1bb99e4t 2015/09/25 Example Title in team
` {
		t.Errorf("written text is wrong: %s", buf.Bytes())
	}
}
Пример #24
0
func main() {

	var handlerInstance *HandlerObject = NewHandlerObject(123)

	var httpMux *http.ServeMux = http.NewServeMux()
	httpServer := &http.Server{
		Addr:           ":8080",
		Handler:        httpMux,
		ReadTimeout:    2 * time.Second,
		WriteTimeout:   2 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	var httpsMux *http.ServeMux = http.NewServeMux()
	httpsServer := &http.Server{
		Addr:           ":8443",
		Handler:        httpsMux,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	httpMux.Handle("/foo", handlerInstance)
	httpMux.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
		log.Printf("%+v", r)
		r.Body = http.MaxBytesReader(w, nopCloser{r.Body}, 1024)
		fmt.Fprintf(w, "HandlerFunc, %q", html.EscapeString(r.URL.Path))
	})

	httpsMux.Handle("/foo", handlerInstance)
	httpsMux.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
		log.Printf("%+v", r)
		r.Body = http.MaxBytesReader(w, nopCloser{r.Body}, 65536)
		fmt.Fprintf(w, "HandlerFunc, %q", html.EscapeString(r.URL.Path))
	})

	go func() {
		log.Println("Before starting HTTPS listener...")
		err := httpsServer.ListenAndServeTLS("server.crt", "server.key.insecure")
		if err != nil {
			log.Fatal("HTTPS listener couldn't start")
		}
	}()

	log.Println("Before starting HTTP listener...")
	err := httpServer.ListenAndServe()
	if err != nil {
		log.Fatal("HTTP listener couldn't start")
	}
}
Пример #25
0
// TestAddLink_NoTitle_Broadcast tests that a newly added link with no title
// (and which therefore needs to be fetched) is broadcasted to peers after
// fetching completes.
func TestAddLink_NoTitle_Broadcast(t *testing.T) {
	// Start a test server that returns a page with a <title> tag, so we can
	// fetch locally.
	var fetched bool
	fakeTitleMux := http.NewServeMux()
	fakeTitleMux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
		w.Write([]byte(`<title>Example</title>`))
		fetched = true
	})
	fakeTitleServer := httptest.NewServer(fakeTitleMux)
	defer fakeTitleServer.Close()

	link := `{"URL":"` + fakeTitleServer.URL + `"}`
	wantLink := `{"URL":"` + fakeTitleServer.URL + `","Title":"Example"}` + "\n"

	// Start a test server to receive the broadcasted link.
	var received bool
	fakePeerMux := http.NewServeMux()
	fakePeerMux.HandleFunc("/links", func(w http.ResponseWriter, r *http.Request) {
		received = true
		if body, _ := ioutil.ReadAll(r.Body); string(body) != wantLink {
			t.Errorf("got body %q, want %q", body, wantLink)
		}
	})
	fakePeerServer := httptest.NewServer(fakePeerMux)
	defer fakePeerServer.Close()

	// Add fake server to peers list.
	fakePeerURL, _ := url.Parse(fakePeerServer.URL)
	peers = map[string]struct{}{fakePeerURL.Host: struct{}{}}

	// Add the link to this server.
	resp := httptest.NewRecorder()
	req, _ := http.NewRequest("POST", "/links", strings.NewReader(link))
	h.ServeHTTP(resp, req)
	testStatusCode(t, "after adding a link with no title (with peers to broadcast to)", resp.Code, http.StatusOK)

	// Wait until the fetch and broadcast have (probably) finished.
	time.Sleep(time.Millisecond * 10)

	// Test that adding the link to this server fetched it and broadcasted it to
	// its peer.
	if !fetched {
		t.Error("link was not fetched")
	}
	if !received {
		t.Error("fake server did not receive broadcasted link")
	}
}
Пример #26
0
func ServeHttp(containerInstanceArn *string, taskEngine engine.TaskEngine, cfg *config.Config) {
	serverFunctions := map[string]func(w http.ResponseWriter, r *http.Request){
		"/v1/metadata": MetadataV1RequestHandlerMaker(containerInstanceArn, cfg),
		"/v1/tasks":    TasksV1RequestHandlerMaker(taskEngine),
		"/license":     LicenseHandler,
	}

	paths := make([]string, 0, len(serverFunctions))
	for path := range serverFunctions {
		paths = append(paths, path)
	}
	availableCommands := &RootResponse{paths}
	// Autogenerated list of the above serverFunctions paths
	availableCommandResponse, _ := json.Marshal(&availableCommands)

	defaultHandler := func(w http.ResponseWriter, r *http.Request) {
		w.Write(availableCommandResponse)
	}

	serverMux := http.NewServeMux()
	serverMux.HandleFunc("/", defaultHandler)
	for key, fn := range serverFunctions {
		serverMux.HandleFunc(key, fn)
	}

	// Log all requests and then pass through to serverMux
	loggingServeMux := http.NewServeMux()
	loggingServeMux.Handle("/", LoggingHandler{serverMux})

	server := http.Server{
		Addr:         ":" + strconv.Itoa(config.AGENT_INTROSPECTION_PORT),
		Handler:      loggingServeMux,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 5 * time.Second,
	}

	for {
		once := sync.Once{}
		utils.RetryWithBackoff(utils.NewSimpleBackoff(time.Second, time.Minute, 0.2, 2), func() error {
			// TODO, make this cancellable and use the passed in context; for
			// now, not critical if this gets interrupted
			err := server.ListenAndServe()
			once.Do(func() {
				log.Error("Error running http api", "err", err)
			})
			return err
		})
	}
}
Пример #27
0
func main() {
	mux1 := http.NewServeMux()
	mux1.HandleFunc("/foo", foo)

	mux2 := http.NewServeMux()
	mux2.HandleFunc("/bar", bar)

	go func() {
		fmt.Println("/foo listening on port 8081")
		http.ListenAndServe(":8081", mux1)
	}()

	fmt.Println("/bar listening on port 8082")
	http.ListenAndServe(":8082", mux2)
}
Пример #28
0
// NewServer it will create a server with all necessary
// settings to function properly
func NewServer() *Server {
	sm = http.NewServeMux()
	sm.Handle("/", http.FileServer(http.Dir("./public/")))
	s := http.NewServeMux()
	s.HandleFunc("/auth/login", makeHandler(controllers.LoginHandler))
	s.HandleFunc("/auth/signup", makeHandler(controllers.RegisterHandler))
	s.HandleFunc("/", HomeHandler)

	server := new(Server)
	server.Server = http.Server{
		Addr:    ":8080",
		Handler: s,
	}
	return server
}
Пример #29
0
func TestMain(m *testing.M) {
	metadataHandler = &fakeMetadataHandler{
		hosts: []metadata.Host{},
	}

	kubeHandler = &fakeKubeNodeHandler{
		nodes: map[string]*model.Node{},
	}

	metadataMux := http.NewServeMux()
	srv := http.Server{
		Addr:    "0.0.0.0:42500",
		Handler: metadataMux,
	}
	errChan := make(chan error, 1)
	metadataMux.Handle("/2015-12-19/hosts/", metadataHandler)
	srvLn, err := net.Listen("tcp", srv.Addr)
	if err != nil {
		log.Fatalf("Error listening on tcp port 42500: %v", err)
	}
	go func() {
		errChan <- srv.Serve(tcpKeepAliveListener{srvLn.(*net.TCPListener)})
	}()
	kubeMux := http.NewServeMux()
	ksrv := http.Server{
		Addr:    "0.0.0.0:42501",
		Handler: kubeMux,
	}
	kubeMux.Handle("/api/v1/nodes/", kubeHandler)
	ksrvLn, err := net.Listen("tcp", ksrv.Addr)
	if err != nil {
		log.Fatalf("Error listening on tcp port 42501: %v", err)
	}
	go func() {
		errChan <- ksrv.Serve(tcpKeepAliveListener{ksrvLn.(*net.TCPListener)})
	}()
	intChan := make(chan int, 1)
	go func() {
		intChan <- m.Run()
	}()
	var returnVal int
	select {
	case err := <-errChan:
		log.Fatalf("Error while running metadata/kuberserver, [%v]", err)
	case returnVal = <-intChan:
	}
	os.Exit(returnVal)
}
Пример #30
-1
func TestMain(m *testing.M) {
	generateMetrics()

	masterRouter := http.NewServeMux()
	masterRouter.HandleFunc("/metrics/snapshot", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(masterMetrics)
	})
	masterTestServer = httptest.NewServer(masterRouter)

	slaveRouter := http.NewServeMux()
	slaveRouter.HandleFunc("/metrics/snapshot", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(slaveMetrics)
	})
	slaveRouter.HandleFunc("/monitor/statistics", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode([]map[string]interface{}{slaveTaskMetrics})
	})
	slaveTestServer = httptest.NewServer(slaveRouter)

	rc := m.Run()

	masterTestServer.Close()
	slaveTestServer.Close()
	os.Exit(rc)
}