forked from bstick12/goflake-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
59 lines (48 loc) · 1.15 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/bstick12/goflake"
"github.com/gorilla/mux"
)
var generator = goflake.GoFlakeInstanceUsingUnique("D01Z01")
var started = time.Now()
func main() {
startServer()
}
func startServer() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/ids", Id)
router.Queries("count", "{count:[0-9]+}")
router.HandleFunc("/healthz", Health)
log.Fatal(http.ListenAndServe(":8080", router))
}
func Id(w http.ResponseWriter, r *http.Request) {
values := r.URL.Query()
countVar := values["count"]
var count = 2
if len(countVar) == 1 {
count, _ = strconv.Atoi(countVar[0])
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
ids := []string{}
for i := 0; i < count; i++ {
ids = append(ids, generator.GetBase64UUID())
}
json.NewEncoder(w).Encode(ids)
}
func Health(w http.ResponseWriter, r *http.Request) {
duration := time.Since(started)
if duration.Seconds() > 30 {
w.WriteHeader(500)
w.Write([]byte(fmt.Sprintf("error: %v", duration.Seconds())))
} else {
w.WriteHeader(200)
w.Write([]byte("ok"))
}
}