aboutsummaryrefslogtreecommitdiff
path: root/handlers.go
blob: 024a8d62f08cdaadd1b0557a9822cc79b020cfb2 (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main

import (
	"encoding/json"
	"github.com/julienschmidt/httprouter"
	"golang.org/x/net/dict"
	"log"
	"net/http"
	"strconv"
	"strings"
)

type jsonError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func render(w http.ResponseWriter, status int, body interface{}) {
	w.WriteHeader(status)
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	json.NewEncoder(w).Encode(body)
}

func formatError(e error) jsonError {
	parts := strings.SplitN(e.Error(), "[", 2)
	log.Printf("Error %s", parts[0])
	parts = strings.SplitN(parts[0], " ", 2)
	code, err := strconv.Atoi(parts[0])
	if err != nil {
		return jsonError{
			Code:    500,
			Message: "Error parsing error o_0",
		}
	}
	return jsonError{
		Code:    code,
		Message: strings.TrimSpace(parts[1]),
	}
}

func formatDefinitions(defs []*dict.Defn) ([]definition, error) {
	definitions := make([]definition, len(defs))
	for i, def := range defs {
		definitions[i] = definition{
			Dictionary: def.Dict.Desc,
			Word:       def.Word,
			Definition: string(def.Text[:]),
		}
	}
	return definitions, nil
}

func dictDatabases(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	client, err := getDictClient()
	if err != nil {
		log.Printf("Unable to connect to dict server at %s", dictServer)
		render(w, 500, jsonError{420, "Server temporarily unavailable"})
		return
	}

	defer client.Close()

	dicts, err := getDictionaries(client)
	if err != nil {
		render(w, 400, formatError(err))
		return
	}
	render(w, 200, dicts)
}

func dictDefine(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	client, err := getDictClient()
	if err != nil {
		render(w, 500, jsonError{420, "Server temporarily unavailable"})
		return
	}
	defer client.Close()

	word := ps.ByName("word")
	queryValues := r.URL.Query()
	d := queryValues.Get("dict")

	var dict string

	if d != "" {
		dict = d
	} else {
		dict = "*"
	}

	defs, err := client.Define(dict, word)
	if err != nil {
		render(w, 400, formatError(err))
		return
	}

	definitions, err := formatDefinitions(defs)
	if err != nil {
		render(w, 500, err)
		return
	}
	render(w, 200, definitions)
}