This repository has been archived by the owner on Nov 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve.go
executable file
·104 lines (90 loc) · 2.37 KB
/
serve.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
103
104
package ops
import (
"encoding/json"
"log"
"net"
"net/url"
"github.com/abdfnx/qjs"
"github.com/valyala/fasthttp"
)
// Renio.Serve listens for HTTP reqs to host and calls callback sequentially on every request.
func Serve(ctx *quickjs.Context, callback func(request quickjs.Value) (response string),
id quickjs.Value, host quickjs.Value) {
var (
reqs = make(chan *fasthttp.RequestCtx)
resps = make(chan Response)
errch = make(chan error, 1)
)
go func() {
httpHandler := func(ctx *fasthttp.RequestCtx) {
reqs <- ctx
resp := <-resps
ctx.SetStatusCode(int(resp.Status))
_, err := ctx.Write([]byte(resp.Body))
if err != nil {
log.Fatalf("%v", err)
}
}
errch <- fasthttp.ListenAndServe(host.String(), httpHandler)
close(reqs)
}()
for {
select {
case <-errch:
break
case req := <-reqs:
reqjson, _ := json.Marshal(Request{
Method: string(req.Method()),
URL: req.URI(),
Header: req.Request.Header,
Path: string(req.Path()),
Host: string(req.Host()),
QueryArgs: req.QueryArgs(),
PostArgs: req.PostArgs(),
PostForm: req.PostArgs(),
RemoteAddr: req.RemoteAddr(),
RequestURI: string(req.RequestURI()),
Referer: string(req.Referer()),
UserAgent: string(req.UserAgent()),
LocalAddr: req.LocalAddr(),
RemoteIP: req.RemoteIP(),
LocalIP: req.LocalIP(),
})
respjson := callback(ctx.String(string(reqjson)))
var resp Response
err := json.Unmarshal([]byte(respjson), &resp)
if err != nil {
log.Fatal(err)
}
resps <- resp
}
}
}
// Response response returned by callback from js
type Response struct {
// Status code
Status int32
// Body of the response
Body string
}
// Request request sent by client
type Request struct {
Method string
URL *fasthttp.URI
Path string
Header fasthttp.RequestHeader
ContentLength int64
TransferEncoding []string
Host string
Form url.Values
PostForm *fasthttp.Args
RemoteAddr net.Addr
RequestURI string
Referer string
UserAgent string
LocalAddr net.Addr
RemoteIP net.IP
LocalIP net.IP
PostArgs *fasthttp.Args
QueryArgs *fasthttp.Args
}