Created
December 31, 2015 07:22
-
-
Save valyala/02156e6a35a35c8724dd to your computer and use it in GitHub Desktop.
fileserver requested by Grez at http://dou.ua/forums/topic/16012/?ref=email&utm_source=transactional&utm_medium=email&utm_campaign=reply-comment#841957
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example static file server. Serves static files from the given directory. | |
package main | |
import ( | |
"flag" | |
"fmt" | |
"log" | |
"strconv" | |
"strings" | |
"github.com/valyala/fasthttp" | |
) | |
var ( | |
addr = flag.String("addr", ":8080", "TCP address to listen to") | |
compress = flag.Bool("compress", false, "Enables transparent response compression if set to true") | |
dir = flag.String("dir", "/usr/share/nginx/html", "Directory to serve static files from") | |
generateIndexPages = flag.Bool("generateIndexPages", true, "Whether to generate directory index pages") | |
) | |
func main() { | |
flag.Parse() | |
fs := &fasthttp.FS{ | |
Root: *dir, | |
IndexNames: []string{"index.html"}, | |
GenerateIndexPages: *generateIndexPages, | |
Compress: *compress, | |
} | |
h := fs.NewRequestHandler() | |
h = DOURequestHandler(h) | |
if err := fasthttp.ListenAndServe(*addr, h); err != nil { | |
log.Fatalf("error in ListenAndServe: %s", err) | |
} | |
} | |
func DOURequestHandler(fsHandler fasthttp.RequestHandler) fasthttp.RequestHandler { | |
return func(ctx *fasthttp.RequestCtx) { | |
path := string(ctx.Path()) | |
if strings.HasPrefix(path, "/plus/") { | |
b := path[len("/plus/"):] | |
sum := 0 | |
for _, s := range strings.Split(b, "/") { | |
n, err := strconv.Atoi(s) | |
if err != nil { | |
fmt.Fprintf(ctx, "cannot parse number %q in the path %q: %s", s, path, err) | |
ctx.SetStatusCode(fasthttp.StatusBadRequest) | |
return | |
} | |
sum += n | |
} | |
fmt.Fprintf(ctx, "%d", sum) | |
} else { | |
fsHandler(ctx) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment