-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
84 lines (73 loc) · 2.27 KB
/
http.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"net/http"
"github.com/thecsw/katya/analysis"
)
const (
csvHeaderForFind = "normal"
csvHeaderForFrequencies = "freq"
)
var (
// csvHeader is the CSV header when we serve a CSV file
csvHeaders = map[string][]string{
csvHeaderForFind: {
"reverse left", "reverse center",
"left", "center", "right", "source",
"title", "scraped",
},
csvHeaderForFrequencies: {
"lemma", "hits",
},
}
)
// httpMessageReturn defines a generic HTTP return message.
type httpMessageReturn struct {
Message interface{} `json:"message"`
}
// httpErrorReturn defines a generic HTTP error message.
type httpErrorReturn struct {
Error string `json:"error"`
}
// httpCSVFindResults sends the results of SearchResult in a CSV formatted string
func httpCSVFindResults(w http.ResponseWriter, results []SearchResult, status int) {
w.Header().Set("Content-Type", "application/csv")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
toWrite := make([][]string, 0, len(results)+1)
toWrite = append(toWrite, csvHeaders[csvHeaderForFind])
for _, v := range results {
toWrite = append(toWrite, []string{
v.LeftReverse, v.CenterReverse, v.Left, v.Center, v.Right, v.Source, v.Title, v.Scraped,
})
}
_ = csv.NewWriter(w).WriteAll(toWrite)
}
func httpCSVFreqResults(w http.ResponseWriter, results map[string]uint, status int) {
w.Header().Set("Content-Type", "application/csv")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
toWrite := append(
[][]string{csvHeaders[csvHeaderForFrequencies]},
analysis.FilterStopwordsSimple(results, analysis.StopwordsRU)...,
)
_ = csv.NewWriter(w).WriteAll(toWrite)
}
// httpJSON is a generic http object passer.
func httpJSON(w http.ResponseWriter, data interface{}, status int, err error) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
if err != nil && status >= 400 && status < 600 {
_ = json.NewEncoder(w).Encode(httpErrorReturn{Error: err.Error()})
return
}
_ = json.NewEncoder(w).Encode(data)
}
// httpHTML sends a good HTML response.
func httpHTML(w http.ResponseWriter, data interface{}) {
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprint(w, data)
}