-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
219 lines (186 loc) · 4.98 KB
/
server.go
File metadata and controls
219 lines (186 loc) · 4.98 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"github.com/atye/wikitable2json/pkg/client"
"github.com/atye/wikitable2json/pkg/client/status"
)
const (
defaultLang = "en"
)
type TableGetter interface {
GetMatrix(ctx context.Context, page string, lang string, options ...client.TableOption) ([][][]string, error)
GetMatrixVerbose(ctx context.Context, page string, lang string, options ...client.TableOption) ([][][]client.Verbose, error)
GetKeyValue(ctx context.Context, page string, lang string, keyRows int, options ...client.TableOption) ([][]map[string]string, error)
GetKeyValueVerbose(ctx context.Context, page string, lang string, keyRows int, options ...client.TableOption) ([][]map[string]client.Verbose, error)
SetUserAgent(string)
}
type Server struct {
client TableGetter
cache *Cache
}
func NewServer(client TableGetter, cache *Cache) *Server {
if client == nil || cache == nil {
panic("client or cache is nil")
}
return &Server{
client: client,
cache: cache,
}
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var err error
page, ok := ctx.Value(pageKey).(string)
if !ok {
writeError(w, status.NewStatus("something went wrong. no page in request context", http.StatusInternalServerError))
return
}
qv, ok := ctx.Value(queryKey).(queryValues)
if !ok {
writeError(w, status.NewStatus("something went wrong. no query values in request context", http.StatusInternalServerError))
return
}
key := buildCacheKey(page, qv)
data, ok := s.cache.Get(key)
if ok {
err = json.NewEncoder(w).Encode(data)
if err != nil {
writeError(w, status.NewStatus(err.Error(), http.StatusInternalServerError))
return
}
return
}
opts := []client.TableOption{
client.WithTables(qv.tables...),
client.WithSections(qv.sections...),
}
if qv.cleanRef {
opts = append(opts, client.WithCleanReferences())
}
if qv.brNewLine {
opts = append(opts, client.WithBRNewLine())
}
s.client.SetUserAgent(r.Header.Get("User-Agent"))
var resp interface{}
if qv.keyRows >= 1 {
if qv.verbose {
resp, err = s.client.GetKeyValueVerbose(ctx, page, qv.lang, qv.keyRows, opts...)
} else {
resp, err = s.client.GetKeyValue(ctx, page, qv.lang, qv.keyRows, opts...)
}
} else {
if qv.verbose {
resp, err = s.client.GetMatrixVerbose(ctx, page, qv.lang, opts...)
} else {
resp, err = s.client.GetMatrix(ctx, page, qv.lang, opts...)
}
}
if err != nil {
writeError(w, err)
return
}
defer func() {
_ = s.cache.Add(key, resp)
}()
err = json.NewEncoder(w).Encode(resp)
if err != nil {
writeError(w, status.NewStatus(err.Error(), http.StatusInternalServerError))
return
}
}
type queryValues struct {
lang string
tables []int
sections []string
cleanRef bool
keyRows int
verbose bool
brNewLine bool
}
func (q queryValues) string() string {
tables := "all"
if len(q.tables) > 0 {
tmp := ""
for _, v := range q.tables {
tmp = tmp + strconv.Itoa(v)
}
tables = tmp
}
sections := "nil"
if len(q.sections) > 0 {
tmp := ""
for _, v := range q.sections {
tmp = tmp + v
}
sections = tmp
}
return fmt.Sprintf("%s-%s-%s-%t-%d-%t-%t", q.lang, tables, sections, q.cleanRef, q.keyRows, q.verbose, q.brNewLine)
}
func parseParameters(r *http.Request) (queryValues, error) {
var qv queryValues
qv.lang = defaultLang
params := r.URL.Query()
if v := params.Get("lang"); v != "" {
qv.lang = v
}
if v, ok := params["table"]; ok {
for _, table := range v {
t, err := strconv.Atoi(table)
if err != nil {
return queryValues{}, status.NewStatus(err.Error(), http.StatusBadRequest)
}
qv.tables = append(qv.tables, t)
}
}
if v, ok := params["section"]; ok {
qv.sections = v
}
if v := params.Get("cleanRef"); v == "true" {
qv.cleanRef = true
}
if v := params.Get("verbose"); v == "true" {
qv.verbose = true
}
if v := params.Get("brNewLine"); v == "true" {
qv.brNewLine = true
}
if v := params.Get("keyRows"); v != "" {
n, err := strconv.Atoi(v)
if err != nil {
return queryValues{}, status.NewStatus(err.Error(), http.StatusBadRequest)
}
if n < 1 {
return queryValues{}, status.NewStatus("keyRows must be at least 1", http.StatusBadRequest)
}
qv.keyRows = n
}
return qv, nil
}
func buildCacheKey(page string, qv queryValues) string {
return fmt.Sprintf("%s-%s", page, qv.string())
}
func writeError(w http.ResponseWriter, err error) {
var s status.Status
if errors.As(err, &s) {
code := s.Code
if code == 0 {
code = http.StatusInternalServerError
}
w.WriteHeader(code)
err = json.NewEncoder(w).Encode(s)
if err != nil {
http.Error(w, fmt.Sprintf("error marshaling error response: %v", err), http.StatusInternalServerError)
}
} else {
w.WriteHeader(http.StatusInternalServerError)
err = json.NewEncoder(w).Encode(status.NewStatus(err.Error(), http.StatusInternalServerError))
if err != nil {
http.Error(w, fmt.Sprintf("error marshaling error response: %v", err), http.StatusInternalServerError)
}
}
}