-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
66 lines (58 loc) · 1.37 KB
/
main.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
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/translate/{kind}/{name}", translatePokemon).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", r))
}
func translatePokemon(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
kind := vars["kind"]
name := vars["name"]
if kind != "pokemon" {
w.WriteHeader(http.StatusBadRequest)
resp := apiError{
Error: apiErrorDetails{
Message: "invalid kind: only 'pokemon' is supported",
Code: "bad request",
},
}
e := json.NewEncoder(w)
e.Encode(resp)
return
}
if description, err := getDescription(name); err != nil {
resp := apiError{
Error: apiErrorDetails{
Message: err.Error(),
Code: StringOrInt("failed to get description for " + name),
},
}
w.WriteHeader(http.StatusFailedDependency)
e := json.NewEncoder(w)
e.Encode(resp)
} else if translation, err := getTranslation(description); err != nil {
resp := apiError{
Error: apiErrorDetails{
Message: err.Error(),
Code: StringOrInt("failed to get translation for " + name),
},
}
w.WriteHeader(http.StatusFailedDependency)
e := json.NewEncoder(w)
e.Encode(resp)
} else {
resp := apiReply{
Name: name,
Desc: translation,
}
w.WriteHeader(http.StatusOK)
e := json.NewEncoder(w)
e.Encode(resp)
}
}