pages-server/server/setup_fasthttp.go

47 lines
1.5 KiB
Go
Raw Normal View History

2022-07-15 16:10:41 +00:00
//go:build fasthttp
package server
import (
"net/http"
2022-08-28 14:21:37 +00:00
"strings"
2022-07-15 16:10:41 +00:00
"time"
"github.com/valyala/fasthttp"
"codeberg.org/codeberg/pages/server/cache"
"codeberg.org/codeberg/pages/server/utils"
)
func SetupServer(handler fasthttp.RequestHandler) *fasthttp.Server {
// Enable compression by wrapping the handler with the compression function provided by FastHTTP
compressedHandler := fasthttp.CompressHandlerBrotliLevel(handler, fasthttp.CompressBrotliBestSpeed, fasthttp.CompressBestSpeed)
return &fasthttp.Server{
Handler: compressedHandler,
DisablePreParseMultipartForm: true,
NoDefaultServerHeader: true,
NoDefaultDate: true,
ReadTimeout: 30 * time.Second, // needs to be this high for ACME certificates with ZeroSSL & HTTP-01 challenge
}
}
func SetupHTTPACMEChallengeServer(challengeCache cache.SetGetKey) *fasthttp.Server {
2022-08-28 14:21:37 +00:00
challengePath := "/.well-known/acme-challenge/"
2022-07-15 16:10:41 +00:00
return &fasthttp.Server{
Handler: func(ctx *fasthttp.RequestCtx) {
2022-08-28 14:21:37 +00:00
if strings.HasPrefix(string(ctx.Path()), challengePath) {
challenge, ok := challengeCache.Get(utils.TrimHostPort(string(ctx.Host())) + "/" + strings.TrimPrefix(string(ctx.Path()), challengePath))
2022-07-15 16:10:41 +00:00
if !ok || challenge == nil {
ctx.SetStatusCode(http.StatusNotFound)
ctx.SetBodyString("no challenge for this token")
}
ctx.SetBodyString(challenge.(string))
} else {
ctx.Redirect("https://"+string(ctx.Host())+string(ctx.RequestURI()), http.StatusMovedPermanently)
}
},
}
}