2017-05-29 26 views
0

我有这样的代码,重定向HTTP/S请求到登录页面,它的工作原理除了TimeoutHandler有没有效果,我指的是会话3秒后不超时:Golang1.8.1:TimeoutHandler不影响多路复用器

func main(){ 

     mux := http.NewServeMux() 
     rh := http.RedirectHandler("http://10.130.0.10:820/login", 307) 
     mux.Handle("/", rh) 
     tmux := http.TimeoutHandler(mux, time.Second*3, "Timeout!") 
     go http.ListenAndServe("10.130.0.10:818", tmux) 
     go http.ListenAndServeTLS("10.130.0.10:821", "server.pem", "server.key", tmux) 
     var input string 
     fmt.Scanln(&input) 
     fmt.Println("done") 
} 

任何意见将不胜感激。

+0

你有没有试过看看如果在goroutine里面没有运行ListenAndServe时项目超时?要测试注释掉ListenAndServeTLS,运行ListenAndServe而不启动单独的例程。 – reticentroot

回答

0

http.TimeoutHandler不是让会话在某段时间后过期。相反,它用于限制处理程序的执行时间,即如果给定时间已过,它将返回503 Service Unavailable给HTTP客户端。下面是这种用法的一个例子:

func handlerNoTimeout(w http.ResponseWriter, r *http.Request) { 
    //This handler takes 1 second to finished, won't timeout 
    time.Sleep(1 * time.Second) 
    w.Write([]byte("Handler OK")) 
} 

func handlerTimeout(w http.ResponseWriter, r *http.Request) { 
    //This handler takes 4 seconds to finished. 
    //Before finished, it will timeout, 
    //503 response will be sent to client + given message (i.e. Timeout!) 
    time.Sleep(4 * time.Second) 
    w.Write([]byte("Handler timeout (never executed)")) 
} 

func main() { 

    mux := http.NewServeMux() 
    rh := http.RedirectHandler("http://10.130.0.10:820/login", 307) 
    mux.Handle("/", rh) 
    mux.HandleFunc("/timeout", handlerTimeout) 
    mux.HandleFunc("/notimeout", handlerNoTimeout) 
    tmux := http.TimeoutHandler(mux, time.Second*3, "Timeout!") 
    go http.ListenAndServe(":818", tmux) 
    go http.ListenAndServeTLS(":821", "server.pem", "server.key", tmux) 
    var input string 
    fmt.Scanln(&input) 
    fmt.Println("done") 
} 

如果您的接入/timeout,你会得到503与超时消息,但如果你访问/notimeout,HTTP响应将是200 OK

会话是的状态服务器存储,不处理步骤/任务/作业这可能需要一段时间来完成。除非您在后台定义了一个函数/方法/处理程序,否则会话将不会过期,并定期查看会话创建时间,如果经过一段时间,则将其标记为已过期。

在您的代码中,如果重定向处理程序(即登录处理程序)需要超过3秒,它将会超时。

0

我想通了,我不得不使用ReadTimeout和WriteTimeout,这里是一个工作的例子。

func main(){ 
     mux := http.NewServeMux() 
     rh := http.RedirectHandler("http://10.103.0.10:8020/login", 307) 
     mux.Handle("/", rh) 
     s := &http.Server{ 
      Addr:  "10.103.0.10:818", 
      Handler:  mux, 
      ReadTimeout: 5 * time.Second, 
      WriteTimeout: 5 * time.Second, 
     } 
     ss := &http.Server{ 
      Addr:  "10.103.0.10:821", 
      Handler:  mux, 
      ReadTimeout: 5 * time.Second, 
      WriteTimeout: 5 * time.Second, 
     } 
     go s.ListenAndServe() 
     go ss.ListenAndServeTLS("server.pem", "server.key") 

     var input string 
     fmt.Scanln(&input) 
     fmt.Println("done") 
    } 

谢谢。