Skip to content

Instantly share code, notes, and snippets.

@sandipb
Last active March 22, 2018 00:54
Show Gist options
  • Save sandipb/9f1f4cc97c8ca686f284f0618743bbf3 to your computer and use it in GitHub Desktop.
Save sandipb/9f1f4cc97c8ca686f284f0618743bbf3 to your computer and use it in GitHub Desktop.
Golang web handlers and sigpipe
package main
import (
"bytes"
"flag"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
)
func handler(w http.ResponseWriter, r *http.Request) {
log.Println("Handling ", r.URL.Path)
w.Header().Set("Content-type", "text/plain")
var data bytes.Buffer
for i := 0; i < *count*1000; i++ {
data.Write([]byte(strconv.Itoa(i+1) + "\n"))
}
w.Write(data.Bytes())
}
var count = flag.Int("count", 100, "How many 1000 of numbers to print")
var catchSignal = flag.Bool("catch", false, "Should we catch sigpipe? defaults to false")
func main() {
flag.Parse()
if *catchSignal {
log.Println("Will catch sigpipe")
schan := make(chan os.Signal, 1)
signal.Notify(schan, os.Signal(syscall.SIGPIPE))
go func() {
for sig := range schan {
log.Println("Received signal ", sig)
}
}()
}
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}

No problem for your http handler with sigpipes without having to set up a handler

$ ./serve2pipe -count 1000 &
[1] 25909

$ curl -s localhost:8080|head -n 10
2018/03/21 17:50:54 Handling  /
1
2
3
4
5
6
7
8
9
10

If however you add a signal handler, you will get a callback!

$ ./serve2pipe -count 1000 -catch &
[1] 25919
[2018/03/21 17:51:46 Will catch sigpipe

$ curl -s localhost:8080|head -n 10
2018/03/21 17:51:56 Handling  /
1
2
3
4
5
6
7
8
9
10
2018/03/21 17:51:57 Received signal  broken pipe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment