2012-06-05 06:21:10 +08:00
|
|
|
// Command gracedemo implements a demo server showing how to gracefully
|
2014-04-03 05:59:35 +08:00
|
|
|
// terminate an HTTP server using grace.
|
2012-06-05 06:21:10 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"flag"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2013-03-26 05:54:13 +08:00
|
|
|
"os"
|
2012-06-05 06:21:10 +08:00
|
|
|
"time"
|
2014-04-03 02:52:43 +08:00
|
|
|
|
|
|
|
"github.com/facebookgo/grace/gracehttp"
|
2012-06-05 06:21:10 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
address0 = flag.String("a0", ":48567", "Zero address to bind to.")
|
|
|
|
address1 = flag.String("a1", ":48568", "First address to bind to.")
|
|
|
|
address2 = flag.String("a2", ":48569", "Second address to bind to.")
|
|
|
|
now = time.Now()
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
flag.Parse()
|
|
|
|
gracehttp.Serve(
|
2013-05-10 00:28:09 +08:00
|
|
|
&http.Server{Addr: *address0, Handler: newHandler("Zero ")},
|
|
|
|
&http.Server{Addr: *address1, Handler: newHandler("First ")},
|
|
|
|
&http.Server{Addr: *address2, Handler: newHandler("Second")},
|
2012-06-05 06:21:10 +08:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
func newHandler(name string) http.Handler {
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("/sleep/", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
duration, err := time.ParseDuration(r.FormValue("duration"))
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), 400)
|
2013-03-26 05:59:40 +08:00
|
|
|
return
|
2012-06-05 06:21:10 +08:00
|
|
|
}
|
|
|
|
time.Sleep(duration)
|
2013-03-26 05:51:46 +08:00
|
|
|
fmt.Fprintf(
|
|
|
|
w,
|
2013-03-26 05:54:13 +08:00
|
|
|
"%s started at %s slept for %d nanoseconds from pid %d.\n",
|
2012-06-05 06:21:10 +08:00
|
|
|
name,
|
|
|
|
now,
|
2013-03-26 05:51:46 +08:00
|
|
|
duration.Nanoseconds(),
|
2013-03-26 05:54:13 +08:00
|
|
|
os.Getpid(),
|
2013-03-26 05:51:46 +08:00
|
|
|
)
|
2012-06-05 06:21:10 +08:00
|
|
|
})
|
|
|
|
return mux
|
|
|
|
}
|