forked from squat/drae
-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.go
51 lines (43 loc) · 1.05 KB
/
commands.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
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
log "github.com/Sirupsen/logrus"
"github.com/squat/drae/pkg/drae"
)
func api(port int, l *log.Logger) {
http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
word := r.URL.Path[5:]
err := encode(w, word)
if err != nil {
l.Errorf("failed to define word: %v", err)
if _, ok := err.(drae.NotFoundError); ok {
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusInternalServerError)
}
})
http.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
l.Infof("starting drae on port %d", port)
l.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}
func define(word string, l *log.Logger) {
if err := encode(os.Stdout, word); err != nil {
l.Fatalf("failed to define word: %v", err)
}
}
func encode(writer io.Writer, word string) error {
enc := json.NewEncoder(writer)
response, err := drae.Define(word)
if err != nil {
return err
}
enc.Encode(response)
return nil
}