-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathserver.go
85 lines (69 loc) · 1.84 KB
/
server.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
_ "net/http/pprof"
"github.com/fukata/golang-stats-api-handler"
)
const (
// DefaultPort is default port to listen
DefaultPort = "8080"
// EnvPort is environmental variable to change port to listen
EnvPort = "PORT"
)
// Server is used for various debugging.
// It opens runtime stats, pprof and appliclation stats.
type Server struct {
Logger *log.Logger
Stats *Stats
}
// Start starts listening.
func (s *Server) Start() {
http.HandleFunc("/", index)
http.Handle("/stats/app", &statsHandler{
stats: s.Stats,
logger: s.Logger,
})
http.HandleFunc("/stats/runtime", stats_api.Handler)
port := DefaultPort
if p := os.Getenv(EnvPort); p != "" {
port = p
}
s.Logger.Printf("[INFO] Start server listening on :%s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
s.Logger.Printf("[ERROR] Failed to start varz-server: %s", err)
}
}
func index(w http.ResponseWriter, _ *http.Request) {
body := `
<a href="https://github.com/rakutentech/kafka-firehose-nozzle">kafka-firehose-nozzle</a>
<ul>
<li><a href="/stats/runtime">stats/runtime</a></li>
<li><a href="/stats/app">stats/app</a></li>
<li><a href="/debug/pprof/">pprof</a></li>
</ul>
`
w.Header().Set("Content-type", "text/html")
w.WriteHeader(http.StatusOK)
w.Write([]byte(body))
}
type statsHandler struct {
stats *Stats
logger *log.Logger
}
func (h *statsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
body, err := h.stats.Json()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Internal Server Error: %s\n", err)
return
}
h.logger.Printf("[DEBUG] Stats response body: %s", string(body))
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Contentt-Length", strconv.Itoa(len(body)))
w.WriteHeader(http.StatusOK)
w.Write(body)
}