-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
102 lines (86 loc) · 2.41 KB
/
main.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
"syscall/js"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/checker/decls"
celext "github.com/google/cel-go/ext"
)
func main() {
c := make(chan struct{}, 0)
js.Global().Set("cel", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
if len(args) != 2 {
return ""
}
req := args[0].String()
expression := args[1].String()
r, body, err := readHTTP(req)
if err != nil {
return fmt.Errorf("error reading HTTP file: %s", err)
}
evalContext, err := makeEvalContext(body, r.Header, r.URL.String())
if err != nil {
return fmt.Sprintf("error making eval context: %s", err)
}
mapStrDyn := decls.NewMapType(decls.String, decls.Dyn)
env, err := cel.NewEnv(
celext.Strings(),
celext.Encoders(),
cel.Declarations(
decls.NewVar("body", mapStrDyn),
decls.NewVar("header", mapStrDyn),
decls.NewVar("requestURL", decls.String),
))
if err != nil {
log.Fatal(err)
}
parsed, issues := env.Parse(expression)
if issues != nil && issues.Err() != nil {
return fmt.Sprintf("failed to parse expression %#v: %s", expression, issues.Err())
}
checked, issues := env.Check(parsed)
if issues != nil && issues.Err() != nil {
return fmt.Sprintf("expression %#v check failed: %s", expression, issues.Err())
}
prg, err := env.Program(checked)
if err != nil {
return fmt.Sprintf("expression %#v failed to create a Program: %s", expression, err)
}
out, _, err := prg.Eval(evalContext)
if err != nil {
return fmt.Sprintf("expression %#v failed to evaluate: %s", expression, err)
}
return fmt.Sprintf("%v", out)
}))
<-c
}
func readHTTP(input string) (*http.Request, []byte, error) {
req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(input)))
if err != nil {
return nil, nil, fmt.Errorf("error reading request: %s", err)
}
defer req.Body.Close()
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, nil, fmt.Errorf("error reading HTTP body: %s", err)
}
return req, body, nil
}
func makeEvalContext(body []byte, h http.Header, url string) (map[string]interface{}, error) {
var jsonMap map[string]interface{}
err := json.Unmarshal(body, &jsonMap)
if err != nil {
return nil, fmt.Errorf("failed to parse the body as JSON: %s", err)
}
return map[string]interface{}{
"body": jsonMap,
"header": h,
"requestURL": url,
}, nil
}