1
1
package routing
2
2
3
3
import (
4
+ "fmt"
4
5
"github.com/valyala/fasthttp"
5
6
"strings"
7
+ "time"
6
8
)
7
9
8
10
type Handler func (ctx * Context ) error
@@ -19,6 +21,14 @@ type Router struct {
19
21
middlewares map [string ][]Middleware
20
22
}
21
23
24
+ type Static struct {
25
+ Root string
26
+ Compress bool
27
+ ByteRange bool
28
+ IndexName string
29
+ CacheDuration time.Duration
30
+ }
31
+
22
32
func New () * Router {
23
33
return & Router {
24
34
routes : make (map [string ][]* Route ),
@@ -132,3 +142,60 @@ func (r *Route) match(path string) (bool, map[string]string) {
132
142
133
143
return true , params
134
144
}
145
+
146
+ func (options * Static ) notFoundHandler (ctx * fasthttp.RequestCtx ) {
147
+ ctx .SetStatusCode (fasthttp .StatusNotFound )
148
+ ctx .SetContentType ("text/plain; charset=utf-8" )
149
+ _ , err := fmt .Fprintf (ctx , "404 Not Found" )
150
+ if err != nil {
151
+ return
152
+ }
153
+ }
154
+
155
+ func (options * Static ) pathRewrite (ctx * fasthttp.RequestCtx ) []byte {
156
+ path := ctx .Path ()
157
+
158
+ if len (path ) > 1 && path [len (path )- 1 ] == '/' {
159
+ path = path [:len (path )- 1 ]
160
+ }
161
+
162
+ // Remove the last part of the path
163
+ parts := strings .Split (string (path ), "/" )
164
+ if len (parts ) > 1 {
165
+ parts = parts [:len (parts )- 1 ]
166
+ }
167
+ path = []byte (strings .Join (parts , "/" ))
168
+
169
+ if options .IndexName != "" {
170
+ // Append the index file name to the path
171
+ path = append (path , '/' )
172
+ path = append (path , options .IndexName ... )
173
+ }
174
+
175
+ return path
176
+ }
177
+
178
+ func (r * Router ) Static (prefix , root string , options * Static ) {
179
+ if options == nil {
180
+ options = & Static {}
181
+ }
182
+ if options .Root == "" {
183
+ options .Root = root
184
+ }
185
+ fs := fasthttp.FS {
186
+ Root : options .Root ,
187
+ IndexNames : []string {options .IndexName },
188
+ PathRewrite : options .pathRewrite ,
189
+ GenerateIndexPages : false ,
190
+ Compress : options .Compress ,
191
+ AcceptByteRange : options .ByteRange ,
192
+ CacheDuration : options .CacheDuration ,
193
+ PathNotFound : options .notFoundHandler , // Set custom error handler for undefined routes
194
+ }
195
+
196
+ r .Get (prefix , func (c * Context ) error {
197
+ fsHandler := fs .NewRequestHandler ()
198
+ fsHandler (c .RequestCtx )
199
+ return nil
200
+ })
201
+ }
0 commit comments