-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
46 lines (40 loc) · 972 Bytes
/
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
package main
import (
"encoding/json"
"net/http"
"strconv"
"strings"
)
func christmas(w http.ResponseWriter, r *http.Request) {
generateCharacters(w, r, "christmas")
}
func halloween(w http.ResponseWriter, r *http.Request) {
generateCharacters(w, r, "halloween")
}
func easter(w http.ResponseWriter, r *http.Request) {
generateCharacters(w, r, "easter")
}
func generateCharacters(w http.ResponseWriter, r *http.Request, theme string) {
num := extractNumFromURL(r.URL.Path)
characters := make([]Character, num)
for i := 0; i < num; i++ {
character, err := generateRandomCharacter(theme)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
characters[i] = character
}
json.NewEncoder(w).Encode(characters)
}
func extractNumFromURL(urlPath string) int {
parts := strings.Split(urlPath, "/")
if len(parts) < 3 {
return 1
}
num, err := strconv.Atoi(parts[2])
if err != nil || num <= 0 {
return 1
}
return num
}