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


Golang http.TimeoutHandler函数代码示例

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


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

示例1: registerHandlers

func registerHandlers() {
	timeoutMsg := `{"error": {"code": 503,"message": "Request timeout."}}`

	// GET: http://server/allrankings
	allRankings := http.TimeoutHandler(wrapHandlerFunc("GET", allRankingsEndpoint,
		http.HandlerFunc(allRankingsHandler)), time.Duration(timeoutSecs)*time.Second,
		timeoutMsg)

	// GET: http://server/rankings?servers=ip1,ip2,ipn
	rankings := http.TimeoutHandler(wrapHandlerFunc("GET", rankingsEndpoint,
		http.HandlerFunc(rankingsHandler)), time.Duration(timeoutSecs)*time.Second,
		timeoutMsg)

	// GET: http://server/rankedservers
	rankedServers := http.TimeoutHandler(wrapHandlerFunc("GET", rankedServersEndpoint,
		http.HandlerFunc(rankedServersHandler)), time.Duration(timeoutSecs)*time.Second,
		timeoutMsg)

	if useGzip {
		http.Handle(allRankingsEndpoint, GzipHandler(allRankings))
		http.Handle(rankingsEndpoint, GzipHandler(rankings))
		http.Handle(rankedServersEndpoint, GzipHandler(rankedServers))
	} else {
		http.Handle(allRankingsEndpoint, allRankings)
		http.Handle(rankingsEndpoint, rankings)
		http.Handle(rankedServersEndpoint, rankedServers)
	}
}
开发者ID:syncore,项目名称:qlsbridge,代码行数:28,代码来源:handlers.go

示例2: 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

示例3: Run

func Run(config *config.APIConfig, ctx *context.RouteContext, st *utils.Stopper) {
	defer st.End()

	// Do not run the API service if there is no config.
	if config == nil {
		log.Infof("main API service is disabled.")
		return
	}
	log.Infof("starting main API on port %d.", config.Port)

	tlsConfig, err := tlsClientConfig(config.CAFile)
	if err != nil {
		log.Fatalf("could not initialize client cert authentication: %s\n", err)
	}
	if tlsConfig != nil {
		log.Info("main API configured with client certificate authentication")
	}

	srv := &graceful.Server{
		Timeout:          0,    // Already handled by our TimeOut middleware
		NoSignalHandling: true, // We want to use our own Stopper
		Server: &http.Server{
			Addr:      ":" + strconv.Itoa(config.Port),
			TLSConfig: tlsConfig,
			Handler:   http.TimeoutHandler(newAPIHandler(ctx), config.Timeout, timeoutResponse),
		},
	}

	listenAndServeWithStopper(srv, st, config.CertFile, config.KeyFile)

	log.Info("main API stopped")
}
开发者ID:robinjha,项目名称:clair,代码行数:32,代码来源:api.go

示例4: main

func main() {
	mux := mux.NewRouter()
	mux.HandleFunc("/", rootHandler)

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

	http.ListenAndServe(":18080", muxWithMiddlewares)
}
开发者ID:szqh97,项目名称:test,代码行数:8,代码来源:mux_t.go

示例5: Timeout

// Timeout limits a request handler to run for max time of the duration
// Timeout( 15 * time.Second ) will limit the request to run no longer tan 15 seconds
// When the request times out, the request will send a 503 response
func Timeout(duration time.Duration) Middleware {
	return func(next ContextHandler) ContextHandler {
		return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) {

			h := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
				next(ctx, rw, req)
			})

			http.TimeoutHandler(h, duration, "Server request timeout").ServeHTTP(rw, req)
		}
	}
}
开发者ID:mbict,项目名称:webapp,代码行数:15,代码来源:middleware.go

示例6: Start

//start server TODO: run server with goroutine
func (s *HttpServer) Start() error {
	var err error

	if Logger == nil {
		Logger = log.New(os.Stdout, "gomvc", log.Ldate|log.Ltime)
	}
	Logger.Println("gomvc http server start")

	err = s.Config.Check()
	if err != nil {
		Logger.Fatalln("gomvc check config error:", err)
		return err
	}
	Logger.Println("gomvc http server config:")
	Logger.Println(s.Config)

	if s.Filters == nil || len(s.Filters) == 0 {
		Logger.Println("gomvc http server invalid http filters")
		return ErrInvalidFilters
	}

	mux := http.NewServeMux()
	if s.Config.EnableProfile {
		Logger.Println("handle http profile on /debug/pprof")
		mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
		mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
		mux.Handle("/debug/pprof/heap", pprof.Handler("heap"))
		mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
	}

	if s.Config.Timeout > 0 {
		http.TimeoutHandler(s, time.Duration(s.Config.Timeout)*time.Second, MsgServerTimeout)
	} else {
		mux.Handle("/", s)
	}

	l, err := net.Listen("tcp", s.Config.Address)
	if err != nil {
		Logger.Fatalln("gomvc http server listen error:", err)
		return err
	}

	//TODO: run server with go func(){...}()
	s.Listener = l
	err = http.Serve(s.Listener, mux)
	if err != nil {
		Logger.Fatalln("gomvc http server start error:", err)
		return err
	}

	return nil
}
开发者ID:0xff8574,项目名称:gomvc,代码行数:53,代码来源:gomvc.go

示例7: Handler

func Handler(w http.ResponseWriter, r *http.Request) {
	t := time.Now()
	log.Println(r.RequestURI)

	// ResponseWriter wrapper
	w.Header().Set("Server", "YAG")
	w.Header().Set("Content-Type", "application/json")
	rw := &RenderResponseWriter{w: w}

	// Handler composition
	http.TimeoutHandler(&RenderHandler{}, time.Duration(config.Cfg.Webserver.Timeout)*time.Second,
		http.StatusText(http.StatusRequestTimeout)).ServeHTTP(rw, r)

	log.Printf("[%v] in %v\n", rw.Code, time.Now().Sub(t))
}
开发者ID:porjo,项目名称:yag,代码行数:15,代码来源:render.go

示例8: startApp

func startApp(port string) {
	// Load environment variables
	envVars := loadEnvVars()

	app, _, 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)
	}

	// TODO add better timeout message. By default it will just say "Timeout"
	http.ListenAndServe(":"+port, http.TimeoutHandler(context.ClearHandler(app), time.Second*5, ""))
}
开发者ID:dlapiduz,项目名称:cf-deck,代码行数:16,代码来源:server.go

示例9: newRouter

func newRouter() *mux.Router {
	r := mux.NewRouter().StrictSlash(true)
	for _, ar := range apiRoutes {
		handler := http.TimeoutHandler(compressGzip(ar.handlerFunc, config.Config.WebConfig.CompressResponses),
			time.Duration(config.Config.WebConfig.APIWebTimeout)*time.Second,
			`{"error": {"code": 503,"message": "Request timeout."}}`)
		handler = logger.LogWebRequest(handler, ar.name)

		r.Methods(ar.method).
			MatcherFunc(pathQStrToLowerMatcherFunc(r, ar.path, ar.queryStrings,
				getRequiredQryStringCount(ar.queryStrings))).
			Name(ar.name).
			Handler(handler)
	}
	return r
}
开发者ID:syncore,项目名称:a2sapi,代码行数:16,代码来源:router.go

示例10: main

func main() {
	c := readConfig()
	var w io.Writer
	if c.LogFilePath == "" {
		w = os.Stdout
	} else {
		fp, err := os.OpenFile(c.LogFilePath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
		if err != nil {
			panic("file open error")
		}
		w = fp
	}
	g_log = loggerProc(w, 16)

	if c.Heartbeat {
		// ハートビートを有効化
		heartbeat := &http.Server{
			Addr:           ":80",
			Handler:        &heartbeatHandle{text: "やっはろー"},
			ReadTimeout:    time.Duration(c.ReadTimeoutSec) * time.Second,
			WriteTimeout:   time.Duration(c.WriteTimeoutSec) * time.Second,
			MaxHeaderBytes: c.MaxHeaderBytes,
		}
		go heartbeat.ListenAndServe()
	}

	t := time.Duration(c.ProxyTimeoutSec) * time.Second
	myHandler := &SummaryHandle{
		conf:    c,
		timeout: t,
		f:       createDialTimeout(t),
		lb:      loadBalancing(c.BalanceList),
		sesCh:   sesProc(),
		ipCh:    cacheIP(time.Duration(c.IPCacheTimeSec)*time.Second, t),
	}
	server := &http.Server{
		Addr:           fmt.Sprintf("%s:%d", c.Addr, c.Port),
		Handler:        http.TimeoutHandler(myHandler, time.Duration(c.ServerTimeoutSec)*time.Second, "timeout!!!"),
		ReadTimeout:    time.Duration(c.ReadTimeoutSec) * time.Second,
		WriteTimeout:   time.Duration(c.WriteTimeoutSec) * time.Second,
		MaxHeaderBytes: c.MaxHeaderBytes,
	}
	// サーバ起動
	server.ListenAndServe()
}
开发者ID:tanaton,项目名称:salami,代码行数:45,代码来源:salami.go

示例11: main

func main() {
	pflag.Parse()
	if maxStorage > 1*bytesize.EB {
		log.Fatalf("Specified a maximum storage size that would overflow int64!")
	}
	if maxSize > 1*bytesize.EB {
		log.Fatalf("Specified a maximum paste size that would overflow int64!")
	}
	loadTemplates()
	var handler httpHandler
	handler.stats = &storage.Stats{
		MaxNumber:  *maxNumber,
		MaxStorage: int64(maxStorage),
	}
	log.Printf("siteURL    = %s", *siteURL)
	log.Printf("listen     = %s", *listen)
	log.Printf("lifeTime   = %s", *lifeTime)
	log.Printf("maxSize    = %s", maxSize)
	log.Printf("maxNumber  = %d", *maxNumber)
	log.Printf("maxStorage = %s", maxStorage)

	args := pflag.Args()
	if len(args) == 0 {
		args = []string{"fs"}
	}
	if err := handler.setupStore(*lifeTime, args[0], args[1:]); err != nil {
		log.Fatalf("Could not setup paste store: %v", err)
	}

	ticker := time.NewTicker(reportInterval)
	go func() {
		logStats(handler.stats)
		for range ticker.C {
			logStats(handler.stats)
		}
	}()
	var finalHandler http.Handler = handler
	if *timeout > 0 {
		finalHandler = http.TimeoutHandler(finalHandler, *timeout, "")
	}
	http.Handle("/", finalHandler)
	log.Println("Up and running!")
	log.Fatal(http.ListenAndServe(*listen, nil))
}
开发者ID:go-denji,项目名称:pastecat,代码行数:44,代码来源:pastecat.go

示例12: RunFunc

func RunFunc() {
	r := render.New()
	mux, store := InitServerMux(r)
	n := negroni.Classic()
	n.Use(negroni.HandlerFunc(CookieMiddleware(store)))
	n.Use(negroni.HandlerFunc(RecoveryErr()))
	timeourHandler := http.TimeoutHandler(context.ClearHandler(mux), time.Duration(3*time.Second), timeoutErrMessage)
	n.UseHandler(timeourHandler)
	//All the middlerware we used
	l := log.New(os.Stdout, "[negroni] ", 0)
	l.Printf("listening on :80")
	server := http.Server{Addr: ":80", Handler: n}
	server.SetKeepAlivesEnabled(true)
	go MainMonitor()
	InitSchoolDB()
	InitCourseMap()
	InitSchoolStructs()
	l.Fatal(server.ListenAndServe())
}
开发者ID:XingLong9630,项目名称:DHUCourseSelection,代码行数:19,代码来源:Middleware.go

示例13: initNegroni

// initNegroni initializes Negroni with all the middleware and starts it.
func initNegroni(routes Routes, config ServiceConfig) (*RestServiceInfo, error) {
	var err error
	// Create negroni
	negroni := negroni.New()

	// Add content-negotiation middleware.
	// This is an example of using a middleware.
	// This will modify the response header to the
	// negotiated content type, and can then be used as
	// ct := w.Header().Get("Content-Type")
	// where w is http.ResponseWriter
	negroni.Use(NewNegotiator())
	// Unmarshal data from the content-type format
	// into a map
	negroni.Use(NewUnmarshaller())
	pubKeyLocation := config.Common.Api.AuthPublic
	if pubKeyLocation != "" {
		log.Infof("Reading public key from %s", pubKeyLocation)
		config.Common.PublicKey, err = ioutil.ReadFile(pubKeyLocation)
	}
	if err != nil {
		return nil, err
	}
	// We use the public key of root server to check the token.
	authMiddleware := AuthMiddleware{PublicKey: config.Common.PublicKey}
	negroni.Use(authMiddleware)

	timeoutMillis := getTimeoutMillis(config.Common)
	var dur time.Duration
	var readWriteDur time.Duration
	timeoutStr := fmt.Sprintf("%dms", timeoutMillis)
	dur, _ = time.ParseDuration(timeoutStr)
	timeoutStr = fmt.Sprintf("%dms", timeoutMillis+ReadWriteTimeoutDelta)
	readWriteDur, _ = time.ParseDuration(timeoutStr)

	router := newRouter(routes)
	timeoutHandler := http.TimeoutHandler(router, dur, TimeoutMessage)
	negroni.UseHandler(timeoutHandler)

	hostPort := config.Common.Api.GetHostPort()
	svcInfo, err := RunNegroni(negroni, hostPort, readWriteDur)
	return svcInfo, err
}
开发者ID:romana,项目名称:core,代码行数:44,代码来源:service.go

示例14: main

func main() {
	NotFollowRedirect = errors.New("Not Follow Redirect")

	client = &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error { return NotFollowRedirect },
		Timeout:       timeout}
	server := http.NewServeMux()
	filter = GetFilter(rules)

	//状态信息
	server.HandleFunc("/status", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Number Of Goroutines: %d", runtime.NumGoroutine())
	})
	//Proxy
	server.HandleFunc("/", proxy)

	http.TimeoutHandler(server, timeout, "Timeout")

	panic(http.ListenAndServe(":3000", server))
}
开发者ID:linexjlin,项目名称:google_proxy_by_golang,代码行数:20,代码来源:proxy.go

示例15: main

func main() {
	flag.Parse()
	//mime.AddExtensionType(".js", "application/javascript; charset=utf-8");
	mime.AddExtensionType(".js", "text/javascript; charset=utf-8")
	http.Handle("/error/404", http.NotFoundHandler())
	http.Handle("/error/timeout", http.TimeoutHandler(&NeverHandler{}, timeout, "Timeout"))
	//http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("./"))))
	http.Handle("/", http.FileServer(http.Dir("./")))
	srvname := *name
	displayname := srvname
	if displayname == "" {
		displayname = "localhost"
	}
	srvname = srvname + ":" + *port
	displayname = displayname + ":" + *port
	log.Println("Serving test webpage at http://" + displayname + "/tests.html")
	if err := http.ListenAndServe(srvname, nil); err != nil {
		log.Fatal("ListenAndServe: %v", err)
	}
}
开发者ID:pyramids,项目名称:needjs,代码行数:20,代码来源:testserver.go


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