当前位置: 首页>>代码示例>>Golang>>正文


Golang context.ClearHandler函数代码示例

本文整理汇总了Golang中github.com/gorilla/context.ClearHandler函数的典型用法代码示例。如果您正苦于以下问题:Golang ClearHandler函数的具体用法?Golang ClearHandler怎么用?Golang ClearHandler使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ClearHandler函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Run

func (a *Api) Run() error {
	globalMux := http.NewServeMux()

	authRouter := mux.NewRouter()
	authRouter.HandleFunc("/auth/login", a.login).Methods("GET")
	authRouter.HandleFunc("/auth/logout", a.logout).Methods("GET")
	authRouter.HandleFunc("/auth/callback", a.authCallback).Methods("GET")

	apiRouter := mux.NewRouter()

	apiRouter.Handle("/api/domains", a.authRequiredMiddleware(http.HandlerFunc(a.domains))).Methods("GET")
	apiRouter.Handle("/api/domains", a.authRequiredMiddleware(http.HandlerFunc(a.addDomain))).Methods("POST")
	apiRouter.Handle("/api/domains/{prefix:.*}", a.authRequiredMiddleware(http.HandlerFunc(a.removeDomain))).Methods("DELETE")
	apiRouter.HandleFunc("/api/ip", a.getIP).Methods("GET")

	//globalMux.Handle("/api/", apiRouter)
	globalMux.Handle("/api/", apiRouter)
	globalMux.Handle("/auth/", authRouter)

	// global handler
	globalMux.Handle("/", http.FileServer(http.Dir("static")))

	s := &http.Server{
		Addr:    a.listenAddr,
		Handler: context.ClearHandler(globalMux),
	}

	if err := s.ListenAndServe(); err != nil {
		return err
	}

	return http.ListenAndServe(a.listenAddr, context.ClearHandler(globalMux))
}
开发者ID:cncodog,项目名称:shpd,代码行数:33,代码来源:api.go

示例2: main

func main() {
	flag.Parse()
	s, err := susigo.NewSusi(*susiaddr, *cert, *key)
	if err != nil {
		log.Printf("Error while creating susi connection: %v", err)
		return
	}
	susi = s
	log.Println("successfully create susi connection")
	sessionTimeouts = make(map[string]time.Time)

	if *user == "" && *pass == "" {
		http.HandleFunc("/publish", publishHandler)
		http.HandleFunc("/upload", uploadHandler)
		http.Handle("/ws", websocket.Handler(websocketHandler))
		http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))))
		http.HandleFunc("/", redirectToIndex)
	} else {
		http.HandleFunc("/publish", BasicAuth(publishHandler))
		http.HandleFunc("/upload", BasicAuth(uploadHandler))
		http.HandleFunc("/ws", BasicAuth(websocket.Handler(websocketHandler).ServeHTTP))
		http.HandleFunc("/assets/", BasicAuth(http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))).ServeHTTP))
		http.HandleFunc("/", BasicAuth(redirectToIndex))
	}

	log.Printf("starting http server on %v...", *webaddr)
	if *useHTTPS {
		log.Fatal(http.ListenAndServeTLS(*webaddr, *cert, *key, context.ClearHandler(http.DefaultServeMux)))
	} else {
		log.Fatal(http.ListenAndServe(*webaddr, context.ClearHandler(http.DefaultServeMux)))
	}
}
开发者ID:webvariants,项目名称:susi-gowebstack,代码行数:32,代码来源:susi-webstack.go

示例3: main

func main() {
	//Setup the logger
	logger.InitLogger(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)

	//Read configuration information from server_config.json
	config.ReadServerConf()

	//The port our server listens on
	listenPort := config.ServerConf.Port

	logger.Info.Printf("Sever Starting - Listing on port %d - (Version - %s)", listenPort, consts.SERVER_VERSION)

	//Create router
	router := mux.NewRouter()

	//Setup our routes
	router.Handle("/people",
		handlers.Execute(&handlers.PeopleHandler{},
			handlers.AuthHandlerAdapter(),
			handlers.DBConnAdapter())).Methods("GET")

	router.Handle("/places",
		handlers.Execute(&handlers.PlacesHandler{},
			handlers.AuthHandlerAdapter(),
			handlers.DBConnAdapter())).Methods("GET")

	//Listen for connections and serve content
	logger.Info.Println(http.ListenAndServe(":"+strconv.Itoa(listenPort),
		context.ClearHandler(logger.HttpLog(router))))
}
开发者ID:redsofa,项目名称:middleware-test,代码行数:30,代码来源:main.go

示例4: Load

// Load the web server
func Load(c interfaces.Configuration) {
	log.Debugln("Loading HTTP server")
	config = c
	auth.InitStore(config)
	misc.Init(config)
	util.Init(config)

	http.HandleFunc("/history/", misc.History)
	http.HandleFunc("/script/", misc.Script)
	http.HandleFunc("/network/", misc.Network)
	http.HandleFunc("/settings/", misc.Settings)
	http.HandleFunc("/auth/login", auth.Login)
	http.HandleFunc("/auth/confirm", auth.EmailConfirm)
	http.HandleFunc("/auth/password/reset", auth.PasswordReset)
	http.HandleFunc("/auth/password/forgot", auth.PasswordForgot)
	http.HandleFunc("/auth/password/change", auth.PasswordChange)
	http.HandleFunc("/auth/register", auth.Register)
	http.HandleFunc("/auth/check", auth.HTTPCheck)
	http.HandleFunc("/socket", socket.Serve)
	err := http.ListenAndServe(config.GetAddr(), context.ClearHandler(http.DefaultServeMux))
	if err != nil {
		log.Fatalf("Failed to listen to %s: %s", config.GetAddr(), err)
		log.Parent.Close()
		os.Exit(4)
	}
}
开发者ID:tulir293,项目名称:mauirc-server,代码行数:27,代码来源:web.go

示例5: main

func main() {
	globalMux := http.NewServeMux()
	dockerUrl := "tcp://127.0.0.1:5554"
	tlsCaCert := ""
	tlsCert := ""
	tlsKey := ""
	allowInsecure := true
	log.SetLevel(log.DebugLevel)
	client, err := utils.GetClient(dockerUrl, tlsCaCert, tlsCert, tlsKey, allowInsecure)
	if err != nil {
		log.Fatal(err)
	}
	a := &Api{client, true, true, &sync.Mutex{}}

	globalMux.Handle("/", http.FileServer(http.Dir("static")))
	globalMux.Handle("/exec", websocket.Handler(a.execContainer))
	globalMux.Handle("/ws", websocket.Handler(a.execContainer))
	s := &http.Server{
		Addr:    "0.0.0.0:8081",
		Handler: context.ClearHandler(globalMux),
	}
	var runErr error
	runErr = s.ListenAndServe()
	if runErr != nil {
		log.Fatal(runErr)
	}

}
开发者ID:humboldt-xie,项目名称:dockertty,代码行数:28,代码来源:main.go

示例6: main

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)),
	))
}
开发者ID:mshockwave,项目名称:nthuaplus-backend,代码行数:27,代码来源:main.go

示例7: startApp

func startApp(port string) {
	// Load environment variables
	envVars := loadEnvVars()
	// Override with cloud foundry user provided service credentials if specified.
	loadUPSVars(&envVars)

	app, settings, err := controllers.InitApp(envVars)
	if err != nil {
		// Print the error.
		fmt.Println(err.Error())
		// Terminate the program with a non-zero value number.
		// Need this for testing purposes.
		os.Exit(1)
	}
	if settings.PProfEnabled {
		pprof.InitPProfRouter(app)
	}

	if envVars.NewRelicLicense != "" {
		fmt.Println("starting monitoring...")
		startMonitoring(envVars.NewRelicLicense)
	}

	fmt.Println("starting app now...")

	// TODO add better timeout message. By default it will just say "Timeout"
	protect := csrf.Protect([]byte(envVars.SessionKey), csrf.Secure(settings.SecureCookies))
	http.ListenAndServe(":"+port, protect(
		http.TimeoutHandler(context.ClearHandler(app), helpers.TimeoutConstant, ""),
	))
}
开发者ID:18F,项目名称:cg-dashboard,代码行数:31,代码来源:server.go

示例8: main

func main() {
	fmt.Println("")
	fmt.Println("")
	fmt.Println("-------------------------STARTUP OF SERVER-------------------------")

	if len(os.Args) < 2 {
		panic("Cannot startup, the first argument must be the config path")
	}

	settings := NewDefaultSettings(os.Args[1])
	ctx := RouterContext.New(settings)

	router := mux.NewRouter()
	setRouteDefinitions(ctx, router)

	n := negroni.New(getNegroniHandlers(ctx, router)...) //negroni.Classic()
	n.UseHandler(context.ClearHandler(router))

	ctx.Logger.Info("Now serving on %s", settings.ServerBackendUrl())

	backendUrl, err := url.Parse(settings.ServerBackendUrl())
	CheckError(err)
	hostWithPossiblePortOnly := backendUrl.Host
	if settings.IsDevMode() {
		graceful.Run(hostWithPossiblePortOnly, 0, n)
	} else {
		graceful.Run(hostWithPossiblePortOnly, 5*time.Second, n) //Graceful shutdown to allow 5 seconds to close connections
	}
}
开发者ID:francoishill,项目名称:windows-startup-manager,代码行数:29,代码来源:server.go

示例9: constructHTTPHandler

func (cmd *ATCCommand) constructHTTPHandler(
	webHandler http.Handler,
	apiHandler http.Handler,
	oauthHandler http.Handler,
) http.Handler {
	webMux := http.NewServeMux()
	webMux.Handle("/api/v1/", apiHandler)
	webMux.Handle("/auth/", oauthHandler)
	webMux.Handle("/", webHandler)

	var httpHandler http.Handler

	httpHandler = webMux

	// proxy Authorization header to/from auth cookie,
	// to support auth from JS (EventSource) and custom JWT auth
	httpHandler = auth.CookieSetHandler{
		Handler: httpHandler,
	}

	// don't leak gorilla context per-request
	httpHandler = context.ClearHandler(httpHandler)

	return httpHandler
}
开发者ID:xoebus,项目名称:checkin,代码行数:25,代码来源:command.go

示例10: main

func main() {
	var (
		confPath string
	)

	flag.StringVar(&confPath, "f", "./ipcapcom.conf", "path to config file")
	flag.Parse()
	err := gcfg.ReadFileInto(&cfg, confPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error reading config file: %v\n", err)
		os.Exit(1)
	}

	r := mux.NewRouter()
	r.HandleFunc("/ping", handlePing).Methods("GET")
	r.HandleFunc("/apply", handleApply).Methods("POST")
	r.HandleFunc("/purge", handlePurge).Methods("GET")
	r.PathPrefix("/").Handler(http.FileServer(http.Dir(cfg.General.StaticDir)))
	http.Handle("/", context.ClearHandler(r))
	go reaper()
	err = http.ListenAndServe(":"+cfg.General.ListenPort, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(1)
	}
}
开发者ID:ameihm0912,项目名称:ipcapcom,代码行数:26,代码来源:ipcapcom.go

示例11: main

func main() {
	flag.Parse()
	var cfg Config
	_, err := toml.DecodeFile(*configFilePath, &cfg)
	if err != nil {
		log.Fatal("Failed reading config file:", err)
	}

	if cfg.Log.Path != "" {
		lf, err := os.Create(cfg.Log.Path)
		if err != nil {
			log.Fatal("Failed opening log file:", err)
		}
		log.SetOutput(lf)
	}

	if cfg.Server.BaseURL == "" {
		log.Fatal("Missing required base-url setting")
	}

	// CSRF defeat: JSON-only API (reject non-JSON content types)
	s := http.Server{
		Addr:    cfg.Server.Bind,
		Handler: newJsonVerifier(context.ClearHandler(NewProxy(&cfg))),
	}

	log.Println("Proxy server listening on", cfg.Server.Bind)
	err = s.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
开发者ID:paulrosania,项目名称:oauth-token-proxy,代码行数:32,代码来源:server.go

示例12: setupRoutes

func (s *setupStruct) setupRoutes() {
	commonMids := commonMiddlewares()
	authMids := authMiddlewares()

	normal := func(h http.HandlerFunc) httprouter.Handle {
		return xhttp.Adapt(commonMids(h))
	}

	auth := func(h http.HandlerFunc) httprouter.Handle {
		return xhttp.Adapt(commonMids(authMids(h)))
	}

	router := httprouter.New()
	itemStore := stores.NewItemStore(s.Rethink)
	userStore := stores.NewUserStore(s.Rethink)

	{
		itemCtrl := handlers.NewItemCtrl(itemStore)
		router.GET("/v1/item", normal(itemCtrl.List))
		router.GET("/v1/item/:id", normal(itemCtrl.Get))
		router.POST("/v1/item", auth(itemCtrl.Create))
	}

	{
		userCtrl := handlers.NewUserCtrl(userStore)
		router.GET("/v1/user", normal(userCtrl.List))
		router.GET("/v1/user/:id", normal(userCtrl.Get))
		router.POST("/v1/user", auth(userCtrl.Create))
	}

	s.Handler = context.ClearHandler(router)
}
开发者ID:khoinguyen2992,项目名称:grox,代码行数:32,代码来源:setup.go

示例13: NewRouter

func NewRouter(appContext *ApplicationContext) *mux.Router {

	opts := &respond.Options{
		Before: func(w http.ResponseWriter, r *http.Request, status int, data interface{}) (int, interface{}) {
			dataEnvelope := map[string]interface{}{"code": status}
			if err, ok := data.(error); ok {
				dataEnvelope["error"] = err.Error()
				dataEnvelope["success"] = false
			} else {
				dataEnvelope["data"] = data
				dataEnvelope["success"] = true
			}
			return status, dataEnvelope
		},
	}

	router := mux.NewRouter()
	for _, route := range routes {
		var handler http.Handler
		handler = opts.Handler(route.Handler)
		handler = CORSHandler(ContextAwareHandler(handler, appContext), route)
		handler = context.ClearHandler(handler)

		router.
			Methods([]string{route.Method, "OPTIONS"}...).
			Path(route.Pattern).
			Name(route.Name).
			Handler(handler)
	}

	return router
}
开发者ID:fairlance,项目名称:backend,代码行数:32,代码来源:router.go

示例14: TestNewSession

func TestNewSession(t *testing.T) {
	store := sessions.NewCookieStore([]byte("secret"))
	fn := func(c web.C, w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok"))
	}
	mux := web.New()
	mux.Handle("/*", fn)
	mux.Use(Middleware("session", store))
	ts := httptest.NewServer(context.ClearHandler(mux))
	defer ts.Close()

	var err error

	var resp *http.Response
	resp, err = http.Get(ts.URL)
	if err != nil {
		t.Fatal(err)
	}

	cookie := resp.Header.Get("Set-Cookie")
	t.Logf("Set-Cookie: %v", cookie)
	if cookie == "" {
		t.Fatal("\"Set-Cookie\" header missing")
	}

	matches := sessionPattern.FindStringSubmatch(cookie)
	if len(matches) != 2 {
		t.Fatal("session cookie missing")
	}
}
开发者ID:faultier,项目名称:goji-session,代码行数:30,代码来源:middleware_test.go

示例15: registerRoutes

func registerRoutes() http.Handler {
	h := http.NewServeMux()
	mux := pat.New()

	// register routes
	mux.Get("/", http.HandlerFunc(root))
	mux.Get("/upload", oauthWrapper(http.HandlerFunc(uploadPage)))
	mux.Post("/upload", oauthWrapper(http.HandlerFunc(uploadHandler)))
	mux.Get("/auth", http.HandlerFunc(oauthRedirectHandler))

	mux.Get("/search", http.HandlerFunc(searchPage))
	mux.Get("/image/:hash", http.HandlerFunc(imagePage))

	mux.Get("/:hash", http.HandlerFunc(getImageHandler))
	mux.Get("/:hash/:width", http.HandlerFunc(getImageHandlerWidth))

	mux.Get("/", http.HandlerFunc(root))

	h.Handle("/", loggerMiddlerware(mux))
	h.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))

	// load templates
	templates = loadTemplates()

	return context.ClearHandler(h)
}
开发者ID:kir-dev,项目名称:warp-drive,代码行数:26,代码来源:web.go


注:本文中的github.com/gorilla/context.ClearHandler函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。