Skip to content

Instantly share code, notes, and snippets.

@valyala
Created December 31, 2015 07:22
Show Gist options
  • Save valyala/02156e6a35a35c8724dd to your computer and use it in GitHub Desktop.
Save valyala/02156e6a35a35c8724dd to your computer and use it in GitHub Desktop.
// 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