Forked from andreadipersio/go-server-timeout-handler.go
Created
February 23, 2018 08:35
-
-
Save xpzouying/b6257f5ad6acfedae8cef8c7653e9cc3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"flag" | |
"time" | |
"net/http" | |
) | |
const ( | |
timeout = time.Duration(1 * time.Second) | |
timeoutMsg = "your request has timed out" | |
) | |
var ( | |
port int | |
) | |
type MyHandler struct {} | |
func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
// this request will always timeout! | |
time.Sleep(timeout) | |
} | |
func init() { | |
flag.IntVar(&port, "port", 8080, "HTTP Server Port") | |
flag.Parse() | |
} | |
func main() { | |
httpAddr := fmt.Sprintf(":%v", port) | |
log.Printf("Listening to %v", httpAddr) | |
rootHandler := &MyHandler{} | |
// http://golang.org/pkg/net/http/#TimeoutHandler | |
http.Handle("/", http.TimeoutHandler(rootHandler, timeout, timeoutMsg)) | |
log.Fatal(http.ListenAndServe(httpAddr, nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment