This repository has been archived by the owner on May 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
158 lines (143 loc) · 4.58 KB
/
main.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
// 🚀 Fiber is an Express inspired web framework written in Go with 💖
// 📌 API Documentation: https://fiber.wiki
// 📝 Github Repository: https://github.com/gofiber/fiber
package adaptor
import (
"io/ioutil"
"net"
"net/http"
"reflect"
"unsafe"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpadaptor"
)
// HTTPHandlerFunc wraps net/http handler func to fiber handler
func HTTPHandlerFunc(h http.HandlerFunc) fiber.Handler {
return HTTPHandler(h)
}
// HTTPHandler wraps net/http handler to fiber handler
func HTTPHandler(h http.Handler) fiber.Handler {
return func(c *fiber.Ctx) error {
handler := fasthttpadaptor.NewFastHTTPHandler(h)
handler(c.Context())
return nil
}
}
// CopyContextToFiberContext copies the values of context.Context to a fasthttp.RequestCtx
func CopyContextToFiberContext(context interface{}, requestContext *fasthttp.RequestCtx) {
contextValues := reflect.ValueOf(context).Elem()
contextKeys := reflect.TypeOf(context).Elem()
if contextKeys.Kind() == reflect.Struct {
var lastKey interface{}
for i := 0; i < contextValues.NumField(); i++ {
reflectValue := contextValues.Field(i)
/* #nosec */
reflectValue = reflect.NewAt(reflectValue.Type(), unsafe.Pointer(reflectValue.UnsafeAddr())).Elem()
reflectField := contextKeys.Field(i)
if reflectField.Name == "noCopy" {
break
} else if reflectField.Name == "Context" {
CopyContextToFiberContext(reflectValue.Interface(), requestContext)
} else if reflectField.Name == "key" {
lastKey = reflectValue.Interface()
} else if lastKey != nil && reflectField.Name == "val" {
requestContext.SetUserValue(lastKey, reflectValue.Interface())
} else {
lastKey = nil
}
}
}
}
// HTTPMiddleware wraps net/http middleware to fiber middleware
func HTTPMiddleware(mw func(http.Handler) http.Handler) fiber.Handler {
return func(c *fiber.Ctx) error {
var next bool
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next = true
// Convert again in case request may modify by middleware
c.Request().Header.SetMethod(r.Method)
c.Request().SetRequestURI(r.RequestURI)
c.Request().SetHost(r.Host)
for key, val := range r.Header {
for _, v := range val {
c.Request().Header.Set(key, v)
}
}
CopyContextToFiberContext(r.Context(), c.Context())
})
_ = HTTPHandler(mw(nextHandler))(c)
if next {
return c.Next()
}
return nil
}
}
// FiberHandler wraps fiber handler to net/http handler
func FiberHandler(h fiber.Handler) http.Handler {
return FiberHandlerFunc(h)
}
// FiberHandlerFunc wraps fiber handler to net/http handler func
func FiberHandlerFunc(h fiber.Handler) http.HandlerFunc {
return handlerFunc(fiber.New(), h)
}
// FiberApp wraps fiber app to net/http handler func
func FiberApp(app *fiber.App) http.HandlerFunc {
return handlerFunc(app)
}
func handlerFunc(app *fiber.App, h ...fiber.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// New fasthttp request
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
// Convert net/http -> fasthttp request
if r.Body != nil {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, utils.StatusMessage(fiber.StatusInternalServerError), fiber.StatusInternalServerError)
return
}
req.Header.SetContentLength(len(body))
_, _ = req.BodyWriter().Write(body)
}
req.Header.SetMethod(r.Method)
req.SetRequestURI(r.RequestURI)
req.SetHost(r.Host)
for key, val := range r.Header {
for _, v := range val {
req.Header.Set(key, v)
}
}
if _, _, err := net.SplitHostPort(r.RemoteAddr); err != nil && err.(*net.AddrError).Err == "missing port in address" {
r.RemoteAddr = net.JoinHostPort(r.RemoteAddr, "80")
}
remoteAddr, err := net.ResolveTCPAddr("tcp", r.RemoteAddr)
if err != nil {
http.Error(w, utils.StatusMessage(fiber.StatusInternalServerError), fiber.StatusInternalServerError)
return
}
// New fasthttp Ctx
var fctx fasthttp.RequestCtx
fctx.Init(req, remoteAddr, nil)
if len(h) > 0 {
// New fiber Ctx
ctx := app.AcquireCtx(&fctx)
defer app.ReleaseCtx(ctx)
// Execute fiber Ctx
err := h[0](ctx)
if err != nil {
_ = app.Config().ErrorHandler(ctx, err)
}
} else {
// Execute fasthttp Ctx though app.Handler
app.Handler()(&fctx)
}
// Convert fasthttp Ctx > net/http
fctx.Response.Header.VisitAll(func(k, v []byte) {
w.Header().Add(string(k), string(v))
})
w.WriteHeader(fctx.Response.StatusCode())
_, _ = w.Write(fctx.Response.Body())
}
}