2017-05-29 29 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") 
    } 

謝謝。