-
-
Save partkyle/404b3d305e69ea11172e to your computer and use it in GitHub Desktop.
golang net/http panic when using timeout handler
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 ( | |
"flag" | |
"io/ioutil" | |
"log" | |
"net" | |
"net/http" | |
"time" | |
) | |
var ( | |
addr = flag.String("addr", ":8080", "address to listen HTTP") | |
timeout = flag.Duration("timeout", 200*time.Millisecond, "timeout duration") | |
) | |
func main() { | |
flag.Parse() | |
handler := http.TimeoutHandler(http.HandlerFunc(FileReadingHandler), *timeout, "http timeout") | |
http.Handle("/", handler) | |
listener, err := net.Listen("tcp", *addr) | |
if err != nil { | |
log.Fatalf("could not listen: %s", err) | |
} | |
log.Printf("listening addr=%s", listener.Addr()) | |
http.Serve(listener, nil) | |
} | |
func FileReadingHandler(w http.ResponseWriter, r *http.Request) { | |
time.Sleep(*timeout) | |
file, _, err := r.FormFile("f") | |
if err != nil { | |
log.Printf("error reading file: %s", err) | |
} | |
n, err := ioutil.ReadAll(file) | |
log.Printf("n=%d err=%q", n, err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment