本文整理汇总了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)
}
}
示例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, ""),
))
}
示例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")
}
示例4: main
func main() {
mux := mux.NewRouter()
mux.HandleFunc("/", rootHandler)
muxWithMiddlewares := http.TimeoutHandler(mux, time.Second*39, "Timeout!")
http.ListenAndServe(":18080", muxWithMiddlewares)
}
示例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)
}
}
}
示例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
}
示例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))
}
示例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, ""))
}
示例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
}
示例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()
}
示例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))
}
示例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())
}
示例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
}
示例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))
}
示例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)
}
}