-
Notifications
You must be signed in to change notification settings - Fork 1
/
minion.go
121 lines (98 loc) · 2.29 KB
/
minion.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
package minion
import (
"fmt"
"log"
"net"
"net/http"
"os"
"sync"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/jwtauth"
"github.com/rs/cors"
"github.com/unrolled/render"
)
var l = log.New(os.Stdout, "[minion] ", 0)
type HandlerFunc func(*Context)
type Middleware func(http.Handler) http.Handler
var tokenAuth *jwtauth.JWTAuth
type App struct {
*Router
c *Context
pool sync.Pool
options Options
}
// Options defines the options to start the API
type Options struct {
Cors []string
JWTToken string
UnauthenticatedRoutes []string
Namespace string
Headers []string
Authenticator func(next http.Handler) http.Handler
}
func New(opts Options) *App {
namespace := opts.Namespace
if len(namespace) == 0 {
namespace = "/"
}
app := &App{}
app.Router = &Router{
app: app,
mux: chi.NewRouter(),
}
app.options = opts
app.pool.New = func() interface{} {
ctx := &Context{
app: app,
render: render.New(render.Options{
Layout: "layout",
}),
}
return ctx
}
return app
}
// Classic returns a new Engine instance with basic middlewares
// Recovery, Logger, CORS and JWT
func Classic(opts Options) *App {
app := New(opts)
if opts.Headers == nil {
opts.Headers = []string{"Authorization", "Origin", "X-Requested-With", "Content-Type", "Accept"}
}
crs := cors.New(cors.Options{
AllowedOrigins: app.options.Cors,
AllowedHeaders: app.options.Headers,
AllowCredentials: true,
})
tokenAuth = jwtauth.New("HS256", []byte(opts.JWTToken), nil)
ctx := app.pool.Get().(*Context)
app.Use(middleware.Recoverer)
app.Use(Logger)
app.Use(crs.Handler)
app.Use(jwtauth.Verifier(tokenAuth))
if opts.Authenticator != nil {
app.Use(opts.Authenticator)
} else {
app.Use(ctx.Authenticator)
}
return app
}
func (app *App) Use(md Middleware) {
app.Router.mux.Use(md)
}
func (app *App) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
app.Router.mux.ServeHTTP(rw, req)
}
func (app *App) Run(port int) error {
addr := fmt.Sprintf(":%d", port)
log.Printf("Starting server on port [%d]\n", port)
listen, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return http.Serve(listen, app)
}
func (app *App) reuseContext(ctx *Context) {
app.pool.Put(ctx)
}