This repository has been archived by the owner on Dec 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
async.go
66 lines (59 loc) · 1.42 KB
/
async.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
package proxy
import (
"bytes"
"encoding/gob"
"net/http"
"github.com/nats-io/nats.go"
)
type AsyncRequest struct {
RawRequest *http.Request
FuncName string
Callback string
}
type AsyncCallbackRequest struct {
Status int
Body []byte
}
func (p *Proxy) asyncSubChannel() {
for {
select {
case async := <-p.asyncQueue:
p.asyncSend(async)
case <-p.asyncClose:
return
}
}
}
func (p *Proxy) asyncSubNats(msg *nats.Msg) {
evt := p.log.With().Str("action", "async-request").Logger()
buffer := bytes.NewBuffer(msg.Data)
var async = &AsyncRequest{}
if err := gob.NewDecoder(buffer).Decode(&async); err != nil {
evt.Err(err).Msg("decode msg error!")
return
}
p.asyncSend(async)
}
func (p *Proxy) asyncSend(async *AsyncRequest) {
evt := p.log.With().Str("action", "async-request").Logger()
resp, err := p.send(async.RawRequest)
if err != nil {
evt.Err(err).Msg("invoke function failed")
return
}
defer resp.Body.Close()
callbackReq, err := http.NewRequest(http.MethodPost, async.Callback, resp.Body)
if err != nil {
evt.Err(err).Str("callback", async.Callback).Msg("invalid callback")
return
}
callbackResp, err := p.send(callbackReq)
if err != nil {
evt.Err(err).Str("callback", async.Callback).Msg("invoke callback error")
return
}
if callbackResp.StatusCode < 200 || callbackResp.StatusCode >= 300 {
evt.Error().Str("callback", async.Callback).Msg("invoke callback error")
return
}
}