-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
75 lines (64 loc) · 2 KB
/
handler.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
package bigqueryudf
import (
"encoding/json"
"fmt"
"net/http"
"golang.org/x/sync/errgroup"
)
// NewHandler function is a wrapper for bigquery functional cloud function that works inside UDF (User Defined Function).
func NewHandler(transformationFunc func(input []byte) (any, error)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var response bqResponse
var request bqRequest
if err := decodeRequestBody(r, &request); err != nil {
response.ErrorMessage = fmt.Sprintf("internal Error: error decoding request body: %s", err.Error())
handleJSONResponse(w, response, http.StatusBadRequest)
return
}
replies := make([]string, len(request.Calls))
errGroup := errgroup.Group{}
for i, call := range request.Calls {
i := i
call := call
errGroup.Go(func() error {
rawxml, ok := call[0].(string)
if !ok {
return fmt.Errorf("error invalid call type: %T. Call must be a string", call)
}
transformedData, err := transformationFunc([]byte(rawxml))
if err != nil {
return fmt.Errorf("error parsing xml: %w", err)
}
transformedDataEncoded, err := json.Marshal(transformedData)
if err != nil {
return fmt.Errorf("error marshaling response: %w", err)
}
replies[i] = string(transformedDataEncoded)
return nil
})
}
if err := errGroup.Wait(); err != nil {
handleJSONResponse(w, response, http.StatusInternalServerError)
return
}
response.Replies = replies
handleJSONResponse(w, response, http.StatusOK)
}
}
func decodeRequestBody(r *http.Request, request any) error {
defer func() {
_ = r.Body.Close()
}()
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
err := dec.Decode(&request)
if err != nil {
return fmt.Errorf("decoding http request body: %w", err)
}
return nil
}
func handleJSONResponse(w http.ResponseWriter, response any, statusCode int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
_ = json.NewEncoder(w).Encode(response)
}