-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhello.go
73 lines (61 loc) · 1.32 KB
/
hello.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
const (
port = 8080
version = 1
timeout = 2 * time.Second
)
type Info struct {
Version uint
Port uint
Hostname string
}
func jsonHandler(w http.ResponseWriter, r *http.Request) {
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
info := Info{version, port, hostname}
js, err := json.Marshal(info)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func pingHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "pong\n")
}
func hostHandler(w http.ResponseWriter, r *http.Request) {
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
fmt.Fprintf(w, "%s\n", hostname)
}
func versionHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%d\n", version)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/ping", pingHandler)
mux.HandleFunc("/host", hostHandler)
mux.HandleFunc("/version", versionHandler)
mux.HandleFunc("/json", jsonHandler)
s := http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: mux,
ReadTimeout: timeout,
WriteTimeout: timeout,
IdleTimeout: timeout,
ReadHeaderTimeout: timeout,
}
s.ListenAndServe()
}