-
Notifications
You must be signed in to change notification settings - Fork 1
/
theo.go
47 lines (40 loc) · 806 Bytes
/
theo.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
package main
import (
"encoding/json"
"github.com/gorilla/mux"
"io/ioutil"
"log"
"net/http"
"strconv"
)
type Insult struct {
ID int `json:"id"`
Text string `json:"text"`
}
func getInsults() []Insult {
raw, err := ioutil.ReadFile("./insults.json")
if err != nil {
panic(err)
}
var insults []Insult
err = json.Unmarshal(raw, &insults)
return insults
}
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", Index)
router.HandleFunc("/{id}", Index)
log.Fatal(http.ListenAndServe(":8080", router))
}
func Index(w http.ResponseWriter, r *http.Request) {
insults := getInsults()
vars := mux.Vars(r)
id := vars["id"]
if id != "" {
id_int, err := strconv.Atoi(id)
if err != nil {
panic(err)
}
json.NewEncoder(w).Encode(insults[id_int])
}
}