grace/gracedemo/demo.go

86 lines
2.1 KiB
Go
Raw Normal View History

2012-06-05 06:21:10 +08:00
// Command gracedemo implements a demo server showing how to gracefully
// terminate an HTTP server using grace.
2012-06-05 06:21:10 +08:00
package main
import (
"flag"
"fmt"
"grace/gracedemo/manifest"
"log"
2012-06-05 06:21:10 +08:00
"net/http"
2013-03-26 05:54:13 +08:00
"os"
"strconv"
2012-06-05 06:21:10 +08:00
"time"
2014-04-03 02:52:43 +08:00
"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.SetLogger(log.Default())
_ = os.WriteFile("./_pid", []byte(strconv.Itoa(os.Getpid())), os.ModePerm)
log.Println("server start:", os.Getppid(), os.Getpid(), getManifest())
err := gracehttp.Serve(
&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
)
if err != nil {
log.Println(err)
}
log.Println("server shutdown:", os.Getppid(), os.Getpid(), getManifest())
}
func getManifest() string {
return fmt.Sprintf("Version: %s Branch: %s Commit: %s Static:%s", manifest.Version, manifest.Branch, manifest.Commit, manifest.Static)
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"))
//log.Println(r.URL)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
time.Sleep(duration)
fmt.Fprintf(
w,
"+ %s started at %s slept for %d nanoseconds from pid %d. %s\n",
name,
now,
duration.Nanoseconds(),
os.Getpid(),
getManifest(),
)
})
//syscall.SetsockoptInt()
mux.HandleFunc("/restart", func(w http.ResponseWriter, r *http.Request) {
2012-06-05 06:21:10 +08:00
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,
"+ %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
})
2012-06-05 06:21:10 +08:00
return mux
}