-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
59 lines (49 loc) · 1.36 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main
import (
"context"
"flag"
"fmt"
"log"
"math"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
var (
bindAddr string
defaultResponse string
)
func init() {
flag.StringVar(&bindAddr, "bind-address", ":8080", "ip:port where http requests are served")
flag.StringVar(&defaultResponse, "default-response", "yes\n", "what to respond when recpinged")
flag.Parse()
}
func main() {
started := time.Now()
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, syscall.SIGTERM, syscall.SIGINT)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
counter := r.URL.Query().Get("counter")
counter = strings.Replace(counter, "\n", "", -1)
counter = strings.Replace(counter, "\r", "", -1)
if counter != "" {
fmt.Printf("{\"message\": \"got request with counter: %s\", \"counter\": \"%s\"}\n", counter, counter)
}
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, defaultResponse)
})
http.HandleFunc("/for", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, fmt.Sprintf("%.0f seconds\n", math.RoundToEven(time.Now().Sub(started).Seconds())))
})
fmt.Println("running @", bindAddr)
go func() {
log.Fatal((&http.Server{Addr: bindAddr}).ListenAndServe())
}()
<-interrupt
fmt.Println("shutting down")
(&http.Server{Addr: bindAddr}).Shutdown(context.Background())
}