-
Notifications
You must be signed in to change notification settings - Fork 1
/
handlers.go
68 lines (57 loc) · 1.57 KB
/
handlers.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"github.com/gorilla/mux"
)
type InfoResponse struct {
Title string `json:"title"`
Version string `json:"version"`
Hostname string `json:"hostname"`
Message string `json:"message"`
}
// CalculateHandler is One-shot math operation (square root)
func CalculateHandler(w http.ResponseWriter, r *http.Request) {
var (
payload map[string]interface{}
)
vars := mux.Vars(r)
if vars["number"] != "" {
if s, err := strconv.ParseFloat(vars["number"], 32); err == nil {
payload = map[string]interface{}{
"message": fmt.Sprintf("The square root of %s is %f", vars["number"], SquareRootOf(s)),
}
}
} else {
payload = map[string]interface{}{
"message": SquareRoot(),
}
}
if err := json.NewEncoder(w).Encode(payload); err != nil {
logger.Error().Err(err).Msg("Failed to encode JSON")
}
}
func StatusHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(map[string]interface{}{"status": "OK"}); err != nil {
logger.Error().Err(err).Msg("Failed to encode JSON")
}
}
func InfoHandler(w http.ResponseWriter, r *http.Request) {
host, err := os.Hostname()
if err != nil {
logger.Error().Err(err).Msg("Host name reported by the kernel")
}
response := InfoResponse{
Title: "Home | go-gena",
Hostname: host,
Message: fmt.Sprintf("Hello from %s", AppName),
Version: AppVersion,
}
if err := json.NewEncoder(w).Encode(response); err != nil {
logger.Error().Err(err).Msg("Failed to encode JSON")
}
}