-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaggregate.go
65 lines (60 loc) · 1.37 KB
/
aggregate.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"github.com/albrow/forms"
)
func aggregateHandler(w http.ResponseWriter, r *http.Request) {
var (
userID int
err error
)
if NeedAuth {
userID, err = verifyBearerAuth(r.Header.Get("Authorization"))
if err != nil {
c := Container{false, nil, 203}
http.Error(w, c.toJSON(), http.StatusUnauthorized)
return
}
} else {
userID = staticUserID
}
data, err := forms.Parse(r)
if err != nil {
log.Println(err)
}
val := data.Validator()
val.Require("calls")
if val.HasErrors() {
log.Printf("%s: Form passed lacks of necessary key(s).", r.URL.Path)
for k, v := range val.ErrorMap() {
log.Printf("%s: %s\n", k, v)
}
return
}
var calls []AggCall
container := Container{true, nil, 0}
results := []AggResult{}
json.Unmarshal([]byte(data.Get("calls")), &calls)
for _, call := range calls {
endPoint := strings.Split(call.EndPoint, "?")[0]
handler, ok := InsideHandler[endPoint]
if !ok {
log.Println("Unknow request endpoint ", call.EndPoint)
results = append(results, AggResult{call.ID, &EmptyList{}})
continue
}
tojson, err := handler(userID, r)
if err != nil {
container.Success = false
log.Println(err)
break
}
results = append(results, AggResult{call.ID, tojson})
}
container.Value = (*AggContainer)(&results)
fmt.Fprintln(w, container.toJSON())
}