Skip to content

Instantly share code, notes, and snippets.

@sandipb sandipb/main.go
Last active Mar 22, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.