-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
171 lines (148 loc) · 4.74 KB
/
context.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
package server
import (
"encoding/json"
"errors"
log "github.com/Sirupsen/logrus"
"github.com/garyburd/redigo/redis"
"github.com/gocraft/web"
"github.com/microbay/server/core"
"github.com/microbay/server/proxy"
"io/ioutil"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
// Root context
type Context struct {
*core.Renderer
Config API
Resource *Resource
Redis redis.Conn
Params core.URLParams
}
// LoggerMiddleware is generic middleware that will log requests to Logger (by default, Stdout).
func (c *Context) LoggerMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
startTime := time.Now()
next(rw, req)
core.LogRequest(rw, req, startTime)
}
// Assigns global config to context --> must be a better way to pass that onto context
func (c *Context) ConfigMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
c.Config = Config
next(rw, req)
}
// Redis Middleware
func (c *Context) RedisMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
c.Redis = redisPool.Get()
defer c.Redis.Close()
next(rw, req)
}
// 403 on API root
func (c *Context) RootMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
if req.URL.Path == "/" {
c.RenderError(rw, errors.New(c.Config.Name+" root access forbidden"), "", http.StatusForbidden)
} else {
next(rw, req)
}
}
func (c *Context) ResourceConfigMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
var err error
c.Resource, err = c.Config.FindResourceByRequest(req.Request)
if err != nil {
if err.Error() == "Method" {
rw.Header().Set("Allow", strings.Join(c.Resource.Methods, ", "))
c.RenderError(rw, errors.New("Method Not Allowed"), "", http.StatusMethodNotAllowed)
} else {
c.RenderError(rw, errors.New("Access Forbidden"), "", http.StatusForbidden)
}
} else {
c.Params = core.Params(req.URL.Path, c.Resource.Regex, c.Resource.Keys)
next(rw, req)
}
}
func (c *Context) PluginMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
for i := range c.Resource.Plugins {
if _, err := c.Resource.Middleware[i].Inbound(rw, req); err != nil {
return
}
}
next(rw, req)
}
type CompoundResponse struct {
Response *http.Response
Error error
Key string
}
// Reverse proxies and load-balances backend micro services
func (c *Context) BalancedProxy(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
numRequests := len(c.Resource.Backends)
// Proxy if single request
if numRequests == 1 {
for batchKey := range c.Resource.Backends {
u := c.Resource.Backends[batchKey].Choose().String()
for key := range c.Params {
u = strings.Replace(u, ":"+key, c.Params[key], 1)
}
serverUrl, err := url.Parse(u)
if err != nil {
log.Error("URL failed to parse")
c.RenderError(rw, errors.New("Internal Server Error"), "", http.StatusInternalServerError)
}
reverseProxy := proxy.New(serverUrl, &c.Resource.Middleware)
startTime := time.Now()
res, err := reverseProxy.ServeHTTP(req.Request)
if err != nil {
c.RenderError(rw, err, "", http.StatusInternalServerError)
} else {
if res.StatusCode > 499 {
c.RenderError(rw, errors.New("Internal Server Error"), "", http.StatusInternalServerError)
} else {
reverseProxy.CopyAndClose(rw, res)
}
}
core.LogBackendRequest(err, res, req.Method, serverUrl.String(), startTime)
}
return
}
// Otherwise compound backend calls
var wg sync.WaitGroup
respones := make(chan *CompoundResponse, numRequests)
for batchKey := range c.Resource.Backends {
wg.Add(1)
go func(batchKey string) {
defer wg.Done()
u := c.Resource.Backends[batchKey].Choose().String()
for key := range c.Params {
u = strings.Replace(u, ":"+key, c.Params[key], 1)
}
startTime := time.Now()
res, err := http.Get(u)
core.LogBackendRequest(err, res, req.Method, req.URL.String(), startTime)
respones <- &CompoundResponse{res, err, batchKey}
}(batchKey)
}
wg.Wait()
close(respones)
// Create Compound response
output := make(map[string]interface{})
for composite := range respones {
// Bail out for entire request
// TODO Add choosable behaviours so devs can choose graceful errors if not all components are erroring.
if composite.Error != nil {
c.RenderError(rw, errors.New("Internal Server Error"), "", http.StatusInternalServerError)
return
}
defer composite.Response.Body.Close()
body, err := ioutil.ReadAll(composite.Response.Body)
var data interface{}
err = json.Unmarshal(body, &data)
if err != nil {
c.RenderError(rw, errors.New("Internal Server Error"), "", http.StatusInternalServerError)
return
}
output[composite.Key] = data
}
c.Render(rw, output, http.StatusOK)
}