/
handle.go
224 lines (195 loc) · 6.21 KB
/
handle.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// Copyright 2018 github.com/xiaoenai. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package http
import (
"bytes"
"encoding/json"
"fmt"
"time"
"github.com/henrylee2cn/goutil"
tp "github.com/henrylee2cn/teleport"
"github.com/henrylee2cn/teleport/codec"
"github.com/henrylee2cn/teleport/plugin"
"github.com/valyala/fasthttp"
"github.com/xiaoenai/tp-micro/gateway/logic"
"github.com/xiaoenai/tp-micro/gateway/logic/hosts"
)
const (
// SEQ the packet sequence query parameter specified by the client
SEQ = "seq_"
)
var (
allowCross bool
gwHostsUri string
)
func handler(ctx *fasthttp.RequestCtx) {
(&requestHandler{ctx: ctx}).handle()
}
type requestHandler struct {
ctx *fasthttp.RequestCtx
errMsg []byte
}
var rerrInternalServerError = tp.NewRerror(tp.CodeInternalServerError, tp.CodeText(tp.CodeInternalServerError), "")
func (r *requestHandler) handle() {
var ctx = r.ctx
var h = r.Header()
var contentType = goutil.BytesToString(h.ContentType())
var bodyCodec = GetBodyCodec(contentType, codec.ID_PLAIN)
var acceptBodyCodec = GetBodyCodec(goutil.BytesToString(h.Peek("Accept")), bodyCodec)
var query = r.ctx.QueryArgs()
var bodyBytes = ctx.Request.Body()
var reply []byte
var label plugin.ProxyLabel
label.Uri = goutil.BytesToString(ctx.Path())
// set real ip
if xRealIp := h.Peek("X-Real-IP"); len(xRealIp) > 0 {
label.RealIp = string(xRealIp)
} else if xForwardedFor := h.Peek("X-Forwarded-For"); len(xForwardedFor) > 0 {
label.RealIp = string(bytes.Split(xForwardedFor, []byte{','})[0])
}
if len(label.RealIp) == 0 {
label.RealIp = ctx.RemoteAddr().String()
}
start := time.Now()
defer func() {
if p := recover(); p != nil {
r.replyError(rerrInternalServerError.Copy().SetDetail(fmt.Sprint(p)))
}
r.runlog(start, &label, goutil.BytesToString(query.Peek(SEQ)), bodyBytes, &reply)
}()
// cross
if allowCross && r.crossDomainFilter() {
return
}
// gw hosts
if label.Uri == gwHostsUri {
switch acceptBodyCodec {
case codec.ID_PROTOBUF:
b, _ := codec.ProtoMarshal(hosts.GwHosts())
r.ctx.Success("application/x-protobuf", b)
default:
b, _ := json.Marshal(hosts.GwHosts())
r.ctx.Success("application/json", b)
}
return
}
// verify access token
accessToken, settings, rerr := logic.HttpHooks().OnRequest(r, bodyBytes, logic.AuthFunc())
if rerr != nil {
r.replyError(rerr)
return
}
// set header
h.VisitAll(func(key, value []byte) {
settings = append(settings, tp.WithAddMeta(string(key), string(value)))
})
// set body codec
settings = append(settings, tp.WithBodyCodec(bodyCodec))
// set accept body codec
if acceptBodyCodec != bodyCodec {
settings = append(settings, tp.WithAcceptBodyCodec(acceptBodyCodec))
}
// set session id
if accessToken == nil {
label.SessionId = ctx.RemoteAddr().String()
} else {
label.SessionId = accessToken.SessionId()
if info := accessToken.AddedQuery(); info != nil {
info.VisitAll(func(key, value []byte) {
query.AddBytesKV(key, value)
})
}
}
settings = append(settings, tp.WithAddMeta(tp.MetaRealIp, label.RealIp))
// set seq
if seqBytes := query.Peek(SEQ); len(seqBytes) > 0 {
settings = append(settings, tp.WithSeq(label.RealIp+"@"+goutil.BytesToString(seqBytes)))
}
if query.Len() > 0 {
label.Uri += "?" + query.String()
}
pullcmd := logic.
ProxySelector(&label).
Pull(label.Uri, bodyBytes, &reply, settings...)
// fail
if rerr := pullcmd.Rerror(); rerr != nil {
pullcmd.InputMeta().VisitAll(func(key, value []byte) {
k := goutil.BytesToString(key)
v := goutil.BytesToString(value)
ctx.Response.Header.Add(k, v)
})
r.replyError(rerr)
return
}
// succ
var hasRespContentType bool
pullcmd.InputMeta().VisitAll(func(key, value []byte) {
k := goutil.BytesToString(key)
v := goutil.BytesToString(value)
if k == "Content-Type" {
hasRespContentType = true
ctx.Response.Header.Set(k, v)
} else {
ctx.Response.Header.Add(k, v)
}
})
if !hasRespContentType {
ctx.Response.Header.Add(
"Content-Type",
GetContentType(pullcmd.InputBodyCodec(), contentType),
)
}
ctx.SetBody(reply)
}
var optionsBytes = []byte("OPTIONS")
func (r *requestHandler) crossDomainFilter() bool {
r.ctx.Response.Header.Set("Access-Control-Allow-Origin", string(r.ctx.Request.Header.Peek("Origin")))
r.ctx.Response.Header.Set("Access-Control-Allow-Credentials", "true")
r.ctx.Response.Header.Set("Access-Control-Allow-Methods", string(r.ctx.Request.Header.Peek("Access-Control-Request-Method")))
// r.ctx.Response.Header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
r.ctx.Response.Header.Set("Access-Control-Allow-Headers", string(r.ctx.Request.Header.Peek("Access-Control-Request-Headers")))
// r.ctx.Response.Header.Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
r.ctx.Response.Header.Set("Access-Control-Max-Age", "-1")
// r.ctx.Response.Header.Set("Access-Control-Max-Age", "172800")
if !bytes.Equal(r.ctx.Method(), optionsBytes) {
return false
}
r.ctx.SetStatusCode(204)
return true
}
func (r *requestHandler) replyError(rerr *tp.Rerror) {
var statusCode int
if rerr.Code < 200 {
// Internal communication error
statusCode = 500
} else if rerr.Code < 600 {
// Custom HTTP error
statusCode = int(rerr.Code)
} else {
// Business error
statusCode = 299
}
r.errMsg, _ = rerr.MarshalJSON()
r.ctx.SetStatusCode(statusCode)
r.ctx.SetContentType("application/json")
r.ctx.SetBody(r.errMsg)
}
// QueryArgs returns the query arguments object of request.
func (r *requestHandler) QueryArgs() *fasthttp.Args {
return r.ctx.QueryArgs()
}
// Header returns the header object of request.
func (r *requestHandler) Header() *fasthttp.RequestHeader {
return &r.ctx.Request.Header
}