mirror of
https://github.com/tarampampam/error-pages.git
synced 2024-08-30 18:22:40 +00:00
Compare commits
8 Commits
v3.0.0
...
v3.0.0-alp
Author | SHA1 | Date | |
---|---|---|---|
746ce05ae7 | |||
5698daa36c | |||
075bc8f57c | |||
5a2e678d33 | |||
ae73819644 | |||
ed427d614f | |||
0f221d4016 | |||
d5a51e22e2 |
@ -1,18 +0,0 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/devcontainers/spec/main/schemas/devContainer.base.schema.json",
|
||||
"name": "default",
|
||||
"image": "golang:1.22-bookworm",
|
||||
"features": {
|
||||
"ghcr.io/guiyomh/features/golangci-lint:0": {},
|
||||
"ghcr.io/devcontainers/features/github-cli:1": {},
|
||||
"ghcr.io/devcontainers/features/sshd:1": {}
|
||||
},
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
"streetsidesoftware.code-spell-checker"
|
||||
]
|
||||
}
|
||||
},
|
||||
"postCreateCommand": "go mod download"
|
||||
}
|
19
.github/workflows/release.yml
vendored
19
.github/workflows/release.yml
vendored
@ -93,12 +93,13 @@ jobs:
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm/v7,linux/arm64/v8
|
||||
build-args: "APP_VERSION=${{ steps.slug.outputs.version }}"
|
||||
tags: |
|
||||
tarampampam/error-pages:latest
|
||||
tarampampam/error-pages:${{ steps.slug.outputs.version }}
|
||||
tarampampam/error-pages:${{ steps.slug.outputs.version-major }}.${{ steps.slug.outputs.version-minor }}
|
||||
tarampampam/error-pages:${{ steps.slug.outputs.version-major }}
|
||||
ghcr.io/${{ github.actor }}/${{ github.event.repository.name }}:latest
|
||||
ghcr.io/${{ github.actor }}/${{ github.event.repository.name }}:${{ steps.slug.outputs.version }}
|
||||
ghcr.io/${{ github.actor }}/${{ github.event.repository.name }}:${{ steps.slug.outputs.version-major }}.${{ steps.slug.outputs.version-minor }}
|
||||
ghcr.io/${{ github.actor }}/${{ github.event.repository.name }}:${{ steps.slug.outputs.version-major }}
|
||||
tags: ghcr.io/${{ github.actor }}/${{ github.event.repository.name }}:${{ steps.slug.outputs.version }}
|
||||
# tags: | # TODO: uncomment after the stable release
|
||||
# tarampampam/error-pages:latest
|
||||
# tarampampam/error-pages:${{ steps.slug.outputs.version }}
|
||||
# tarampampam/error-pages:${{ steps.slug.outputs.version-major }}.${{ steps.slug.outputs.version-minor }}
|
||||
# tarampampam/error-pages:${{ steps.slug.outputs.version-major }}
|
||||
# ghcr.io/${{ github.actor }}/${{ github.event.repository.name }}:latest
|
||||
# ghcr.io/${{ github.actor }}/${{ github.event.repository.name }}:${{ steps.slug.outputs.version }}
|
||||
# ghcr.io/${{ github.actor }}/${{ github.event.repository.name }}:${{ steps.slug.outputs.version-major }}.${{ steps.slug.outputs.version-minor }}
|
||||
# ghcr.io/${{ github.actor }}/${{ github.event.repository.name }}:${{ steps.slug.outputs.version-major }}
|
||||
|
@ -3,7 +3,7 @@
|
||||
# -✂- this stage is used to develop and build the application locally -------------------------------------------------
|
||||
FROM docker.io/library/golang:1.22-bookworm AS develop
|
||||
|
||||
# use the /var/tmp/go as the GOPATH to reuse the modules cache
|
||||
# use the /var/tmp as the GOPATH to reuse the modules cache
|
||||
ENV GOPATH="/var/tmp/go"
|
||||
|
||||
RUN set -x \
|
||||
@ -45,7 +45,7 @@ FROM docker.io/library/alpine:3.20 AS rootfs
|
||||
WORKDIR /tmp/rootfs
|
||||
|
||||
# prepare rootfs for runtime
|
||||
RUN set -x \
|
||||
RUN --mount=type=bind,source=.,target=/src set -x \
|
||||
&& mkdir -p ./etc ./bin \
|
||||
&& echo 'appuser:x:10001:10001::/nonexistent:/sbin/nologin' > ./etc/passwd \
|
||||
&& echo 'appuser:x:10001:' > ./etc/group
|
||||
@ -69,7 +69,7 @@ ARG APP_VERSION="undefined@docker"
|
||||
LABEL \
|
||||
# docs: https://github.com/opencontainers/image-spec/blob/master/annotations.md
|
||||
org.opencontainers.image.title="error-pages" \
|
||||
org.opencontainers.image.description="Pretty server's error pages" \
|
||||
org.opencontainers.image.description="Static server error pages in the docker image" \
|
||||
org.opencontainers.image.url="https://github.com/tarampampam/error-pages" \
|
||||
org.opencontainers.image.source="https://github.com/tarampampam/error-pages" \
|
||||
org.opencontainers.image.vendor="tarampampam" \
|
||||
@ -87,8 +87,6 @@ WORKDIR /opt
|
||||
# to find out which environment variables and CLI arguments are supported by the application, run the app
|
||||
# with the `--help` flag or refer to the documentation at https://github.com/tarampampam/error-pages#readme
|
||||
|
||||
ENV LOG_LEVEL="warn"
|
||||
|
||||
# docs: https://docs.docker.com/reference/dockerfile/#healthcheck
|
||||
HEALTHCHECK --interval=10s --start-interval=1s --start-period=5s --timeout=2s CMD [\
|
||||
"/bin/error-pages", "--log-format", "json", "healthcheck" \
|
||||
|
@ -25,7 +25,7 @@ func NewApp(appName string) *cli.Command { //nolint:funlen
|
||||
logLevelFlag = cli.StringFlag{
|
||||
Name: "log-level",
|
||||
Value: logger.InfoLevel.String(),
|
||||
Usage: "Logging level (" + strings.Join(logger.LevelStrings(), "/") + ")",
|
||||
Usage: "logging level (" + strings.Join(logger.LevelStrings(), "/") + ")",
|
||||
Sources: cli.EnvVars("LOG_LEVEL"),
|
||||
OnlyOnce: true,
|
||||
Config: cli.StringConfig{TrimSpace: true},
|
||||
@ -41,7 +41,7 @@ func NewApp(appName string) *cli.Command { //nolint:funlen
|
||||
logFormatFlag = cli.StringFlag{
|
||||
Name: "log-format",
|
||||
Value: logger.ConsoleFormat.String(),
|
||||
Usage: "Logging format (" + strings.Join(logger.FormatStrings(), "/") + ")",
|
||||
Usage: "logging format (" + strings.Join(logger.FormatStrings(), "/") + ")",
|
||||
Sources: cli.EnvVars("LOG_FORMAT"),
|
||||
OnlyOnce: true,
|
||||
Config: cli.StringConfig{TrimSpace: true},
|
||||
@ -80,7 +80,7 @@ func NewApp(appName string) *cli.Command { //nolint:funlen
|
||||
serve.NewCommand(log),
|
||||
build.NewCommand(log),
|
||||
healthcheck.NewCommand(log, healthcheck.NewHTTPHealthChecker()),
|
||||
perftest.NewCommand(),
|
||||
perftest.NewCommand(log),
|
||||
},
|
||||
Version: fmt.Sprintf("%s (%s)", appmeta.Version(), runtime.Version()),
|
||||
Flags: []cli.Flag{ // global flags
|
||||
|
@ -44,18 +44,16 @@ func NewCommand(log *logger.Logger) *cli.Command { //nolint:funlen,gocognit
|
||||
addCodeFlag = shared.AddHTTPCodesFlag
|
||||
disableL10nFlag = shared.DisableL10nFlag
|
||||
createIndexFlag = cli.BoolFlag{
|
||||
Name: "index",
|
||||
Aliases: []string{"i"},
|
||||
Usage: "Generate index.html file with links to all error pages",
|
||||
Category: shared.CategoryBuild,
|
||||
Name: "index",
|
||||
Aliases: []string{"i"},
|
||||
Usage: "generate index.html file with links to all error pages",
|
||||
}
|
||||
targetDirFlag = cli.StringFlag{
|
||||
Name: "target-dir",
|
||||
Aliases: []string{"out", "dir", "o"},
|
||||
Usage: "Directory to put the built error pages into",
|
||||
Usage: "directory to put the built error pages into",
|
||||
Value: ".", // current directory by default
|
||||
Config: cli.StringConfig{TrimSpace: true},
|
||||
Category: shared.CategoryBuild,
|
||||
OnlyOnce: true,
|
||||
Validator: func(dir string) error {
|
||||
if dir == "" {
|
||||
|
@ -1,59 +1,32 @@
|
||||
package perftest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"os/exec"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
|
||||
"gh.tarampamp.am/error-pages/internal/cli/shared"
|
||||
"gh.tarampamp.am/error-pages/internal/logger"
|
||||
)
|
||||
|
||||
const wrkOneCodeTestLua = `
|
||||
local formats = { 'application/json', 'application/xml', 'text/html', 'text/plain' }
|
||||
|
||||
request = function()
|
||||
wrk.headers["User-Agent"] = "wrk"
|
||||
wrk.headers["X-Namespace"] = "NAMESPACE_" .. tostring(math.random(0, 99999999))
|
||||
wrk.headers["X-Request-ID"] = "REQ_ID_" .. tostring(math.random(0, 99999999))
|
||||
wrk.headers["Content-Type"] = formats[ math.random( 0, #formats - 1 ) ]
|
||||
|
||||
return wrk.format("GET", "/500.html?rnd=" .. tostring(math.random(0, 99999999)), nil, nil)
|
||||
end
|
||||
`
|
||||
|
||||
//nolint:lll
|
||||
const bombDifferentCodes = `
|
||||
local formats = { 'application/json', 'application/xml', 'text/html', 'text/plain' }
|
||||
|
||||
request = function()
|
||||
wrk.headers["User-Agent"] = "wrk"
|
||||
wrk.headers["X-Namespace"] = "NAMESPACE_" .. tostring(math.random(0, 99999999))
|
||||
wrk.headers["X-Request-ID"] = "REQ_ID_" .. tostring(math.random(0, 99999999))
|
||||
wrk.headers["Content-Type"] = formats[ math.random( 0, #formats - 1 ) ]
|
||||
|
||||
return wrk.format("GET", "/" .. tostring(math.random(400, 599)) .. ".html?rnd=" .. tostring(math.random(0, 99999999)), nil, nil)
|
||||
end
|
||||
`
|
||||
|
||||
// NewCommand creates `perftest` command.
|
||||
func NewCommand() *cli.Command { //nolint:funlen
|
||||
func NewCommand(log *logger.Logger) *cli.Command { //nolint:funlen,gocognit
|
||||
var (
|
||||
portFlag = shared.ListenPortFlag
|
||||
durationFlag = cli.DurationFlag{
|
||||
Name: "duration",
|
||||
Aliases: []string{"d"},
|
||||
Usage: "Duration of test",
|
||||
Value: 15 * time.Second, //nolint:mnd
|
||||
Usage: "duration of the test",
|
||||
Value: 10 * time.Second, //nolint:mnd
|
||||
Validator: func(d time.Duration) error {
|
||||
if d <= time.Second {
|
||||
return errors.New("duration can't be less than 1 second")
|
||||
@ -65,28 +38,11 @@ func NewCommand() *cli.Command { //nolint:funlen
|
||||
threadsFlag = cli.UintFlag{
|
||||
Name: "threads",
|
||||
Aliases: []string{"t"},
|
||||
Usage: "Number of threads to use",
|
||||
Value: max(2, uint64(math.Round(float64(runtime.NumCPU())/1.3))), //nolint:mnd
|
||||
Usage: "number of threads",
|
||||
Value: max(2, uint64(runtime.NumCPU()/2)), //nolint:mnd
|
||||
Validator: func(u uint64) error {
|
||||
if u == 0 {
|
||||
return errors.New("threads number can't be zero")
|
||||
} else if u > math.MaxUint16 {
|
||||
return errors.New("threads number can't be greater than 65535")
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
connectionsFlag = cli.UintFlag{
|
||||
Name: "connections",
|
||||
Aliases: []string{"c"},
|
||||
Usage: "Number of connections to keep open",
|
||||
Value: max(16, uint64(runtime.NumCPU()*25)), //nolint:mnd
|
||||
Validator: func(u uint64) error {
|
||||
if u == 0 {
|
||||
return errors.New("threads number can't be zero")
|
||||
} else if u > math.MaxUint16 {
|
||||
return errors.New("threads number can't be greater than 65535")
|
||||
}
|
||||
|
||||
return nil
|
||||
@ -96,47 +52,97 @@ func NewCommand() *cli.Command { //nolint:funlen
|
||||
|
||||
return &cli.Command{
|
||||
Name: "perftest",
|
||||
Aliases: []string{"perf", "benchmark", "bench"},
|
||||
Aliases: []string{"perf", "test"},
|
||||
Hidden: true,
|
||||
Usage: "Performance (load) test for the HTTP server (locally installed wrk is required)",
|
||||
Action: func(ctx context.Context, c *cli.Command) error {
|
||||
var wrkBinPath, lErr = exec.LookPath("wrk")
|
||||
if lErr != nil {
|
||||
return fmt.Errorf("seems like wrk (https://github.com/wg/wrk) is not installed: %w", lErr)
|
||||
Usage: "Simple performance (load) test for the HTTP server",
|
||||
Action: func(ctx context.Context, c *cli.Command) error { // TODO: use fasthttp.Client
|
||||
var (
|
||||
perfCtx, cancel = context.WithTimeout(ctx, c.Duration(durationFlag.Name))
|
||||
startedAt = time.Now()
|
||||
|
||||
wg sync.WaitGroup
|
||||
success atomic.Uint64
|
||||
failed atomic.Uint64
|
||||
)
|
||||
|
||||
defer func() {
|
||||
cancel()
|
||||
|
||||
log.Info("Summary",
|
||||
logger.Uint64("success", success.Load()),
|
||||
logger.Uint64("failed", failed.Load()),
|
||||
logger.Duration("duration", time.Since(startedAt)),
|
||||
logger.Float64("RPS", float64(success.Load()+failed.Load())/time.Since(startedAt).Seconds()),
|
||||
logger.Float64("errors rate", float64(failed.Load())/float64(success.Load()+failed.Load())*100), //nolint:mnd
|
||||
)
|
||||
}()
|
||||
|
||||
log.Info("Running test",
|
||||
logger.Uint64("threads", c.Uint(threadsFlag.Name)),
|
||||
logger.Duration("duration", c.Duration(durationFlag.Name)),
|
||||
)
|
||||
|
||||
var httpClient = &http.Client{
|
||||
Transport: &http.Transport{MaxConnsPerHost: max(2, int(c.Uint(threadsFlag.Name))-1)}, //nolint:mnd
|
||||
Timeout: c.Duration(durationFlag.Name) + time.Second,
|
||||
}
|
||||
|
||||
var runTest = func(scriptContent string) error {
|
||||
if stdOut, stdErr, err := wrkRunTest(ctx,
|
||||
wrkBinPath,
|
||||
uint16(c.Uint(threadsFlag.Name)),
|
||||
uint16(c.Uint(connectionsFlag.Name)),
|
||||
c.Duration(durationFlag.Name),
|
||||
uint16(c.Uint(portFlag.Name)),
|
||||
scriptContent,
|
||||
); err != nil {
|
||||
var errData, _ = io.ReadAll(stdErr)
|
||||
for i := uint64(0); i < c.Uint(threadsFlag.Name); i++ {
|
||||
wg.Add(1)
|
||||
|
||||
return fmt.Errorf("failed to execute the test: %w (%s)", err, string(errData))
|
||||
} else {
|
||||
var outData, _ = io.ReadAll(stdOut)
|
||||
go func(log *logger.Logger) {
|
||||
defer wg.Done()
|
||||
|
||||
printf("Test completed successfully. Here is the output:\n\n%s\n", string(outData))
|
||||
}
|
||||
if perfCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return nil
|
||||
var req, rErr = makeRequest(perfCtx, uint16(c.Uint(portFlag.Name)))
|
||||
if rErr != nil {
|
||||
log.Error("Failed to create a new request", logger.Error(rErr))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
var sentAt = time.Now()
|
||||
|
||||
var resp, respErr = httpClient.Do(req)
|
||||
if resp != nil {
|
||||
if _, err := io.Copy(io.Discard, resp.Body); err != nil && !errIsDone(err) {
|
||||
log.Error("Failed to read response body", logger.Error(err))
|
||||
}
|
||||
|
||||
if err := resp.Body.Close(); err != nil && !errIsDone(err) {
|
||||
log.Error("Failed to close response body", logger.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
if respErr != nil {
|
||||
if errIsDone(respErr) {
|
||||
return
|
||||
}
|
||||
|
||||
log.Error("Request failed", logger.Error(respErr))
|
||||
failed.Add(1)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
log.Debug("Response received",
|
||||
logger.String("status", resp.Status),
|
||||
logger.Duration("duration", time.Since(sentAt)),
|
||||
logger.Int64("size", resp.ContentLength),
|
||||
logger.Uint64("success", success.Load()),
|
||||
logger.Uint64("failed", failed.Load()),
|
||||
)
|
||||
|
||||
success.Add(1)
|
||||
}
|
||||
}(log.Named(fmt.Sprintf("thread-%d", i)))
|
||||
}
|
||||
|
||||
printf("Starting the test to bomb ONE PAGE (code). Please, be patient...\n")
|
||||
|
||||
if err := runTest(wrkOneCodeTestLua); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
printf("Starting the test to bomb DIFFERENT PAGES (codes). Please, be patient...\n")
|
||||
|
||||
if err := runTest(bombDifferentCodes); err != nil {
|
||||
return err
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
return nil
|
||||
},
|
||||
@ -144,51 +150,54 @@ func NewCommand() *cli.Command { //nolint:funlen
|
||||
&portFlag,
|
||||
&durationFlag,
|
||||
&threadsFlag,
|
||||
&connectionsFlag,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func printf(format string, args ...any) { fmt.Printf(format, args...) } //nolint:forbidigo
|
||||
// randomIntBetween returns a random integer between min and max.
|
||||
func randomIntBetween(min, max int) int { return min + rand.Intn(max-min) } //nolint:gosec
|
||||
|
||||
func wrkRunTest(
|
||||
ctx context.Context,
|
||||
wrkBinPath string,
|
||||
threadsCount, connectionsCount uint16,
|
||||
duration time.Duration,
|
||||
port uint16,
|
||||
scriptContent string,
|
||||
) (io.Reader, io.Reader, error) {
|
||||
var tmpFile, tErr = os.CreateTemp("", "ep-perf-one-page")
|
||||
if tErr != nil {
|
||||
return nil, nil, fmt.Errorf("failed to create a temporary file: %w", tErr)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = tmpFile.Close()
|
||||
_ = os.Remove(tmpFile.Name())
|
||||
}()
|
||||
|
||||
if _, err := tmpFile.WriteString(scriptContent); err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to write to a temporary file: %w", err)
|
||||
}
|
||||
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
var cmd = exec.CommandContext(ctx, wrkBinPath, //nolint:gosec
|
||||
"--timeout", "1s",
|
||||
"--threads", strconv.FormatUint(uint64(threadsCount), 10),
|
||||
"--connections", strconv.FormatUint(uint64(connectionsCount), 10),
|
||||
"--duration", duration.String(),
|
||||
"--script", tmpFile.Name(),
|
||||
fmt.Sprintf("http://127.0.0.1:%d/", port),
|
||||
// makeRequest creates a new HTTP request for the performance test.
|
||||
func makeRequest(ctx context.Context, port uint16) (*http.Request, error) {
|
||||
var req, rErr = http.NewRequestWithContext(ctx,
|
||||
http.MethodGet,
|
||||
fmt.Sprintf(
|
||||
"http://127.0.0.1:%d/%d.html?rnd=%d", // for load testing purposes only
|
||||
port,
|
||||
randomIntBetween(400, 418), //nolint:mnd
|
||||
randomIntBetween(1, 999_999_999), //nolint:mnd
|
||||
),
|
||||
http.NoBody,
|
||||
)
|
||||
|
||||
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||
if rErr != nil {
|
||||
return nil, rErr
|
||||
}
|
||||
|
||||
return &stdout, &stderr, cmd.Run() // execute
|
||||
req.Header.Set("Connection", "keep-alive")
|
||||
req.Header.Set("User-Agent", "perftest")
|
||||
req.Header.Set("X-Namespace", fmt.Sprintf("namespace-%d", randomIntBetween(1, 999_999_999))) //nolint:mnd
|
||||
req.Header.Set("X-Request-ID", fmt.Sprintf("req-id-%d", randomIntBetween(1, 999_999_999))) //nolint:mnd
|
||||
|
||||
var contentType string
|
||||
|
||||
switch randomIntBetween(1, 4) { //nolint:mnd
|
||||
case 1:
|
||||
contentType = "application/json"
|
||||
case 2: //nolint:mnd
|
||||
contentType = "application/xml"
|
||||
case 3: //nolint:mnd
|
||||
contentType = "text/html"
|
||||
default:
|
||||
contentType = "text/plain"
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// errIsDone checks if the error is a context.DeadlineExceeded or context.Canceled.
|
||||
func errIsDone(err error) bool {
|
||||
return errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)
|
||||
}
|
||||
|
@ -46,28 +46,25 @@ func NewCommand(log *logger.Logger) *cli.Command { //nolint:funlen,gocognit,gocy
|
||||
disableL10nFlag = shared.DisableL10nFlag
|
||||
jsonFormatFlag = cli.StringFlag{
|
||||
Name: "json-format",
|
||||
Usage: "Override the default error page response in JSON format (Go templates are supported; the error " +
|
||||
Usage: "override the default error page response in JSON format (Go templates are supported; the error " +
|
||||
"page will use this template if the client requests JSON content type)",
|
||||
Sources: env("RESPONSE_JSON_FORMAT"),
|
||||
Category: shared.CategoryFormats,
|
||||
OnlyOnce: true,
|
||||
Config: trim,
|
||||
}
|
||||
xmlFormatFlag = cli.StringFlag{
|
||||
Name: "xml-format",
|
||||
Usage: "Override the default error page response in XML format (Go templates are supported; the error " +
|
||||
Usage: "override the default error page response in XML format (Go templates are supported; the error " +
|
||||
"page will use this template if the client requests XML content type)",
|
||||
Sources: env("RESPONSE_XML_FORMAT"),
|
||||
Category: shared.CategoryFormats,
|
||||
OnlyOnce: true,
|
||||
Config: trim,
|
||||
}
|
||||
plainTextFormatFlag = cli.StringFlag{
|
||||
Name: "plaintext-format",
|
||||
Usage: "Override the default error page response in plain text format (Go templates are supported; the " +
|
||||
Usage: "override the default error page response in plain text format (Go templates are supported; the " +
|
||||
"error page will use this template if the client requests plain text content type or does not specify any)",
|
||||
Sources: env("RESPONSE_PLAINTEXT_FORMAT"),
|
||||
Category: shared.CategoryFormats,
|
||||
OnlyOnce: true,
|
||||
Config: trim,
|
||||
}
|
||||
@ -75,19 +72,17 @@ func NewCommand(log *logger.Logger) *cli.Command { //nolint:funlen,gocognit,gocy
|
||||
Name: "template-name",
|
||||
Aliases: []string{"t"},
|
||||
Value: cfg.TemplateName,
|
||||
Usage: "Name of the template to use for rendering error pages (built-in templates: " +
|
||||
Usage: "name of the template to use for rendering error pages (built-in templates: " +
|
||||
strings.Join(cfg.Templates.Names(), ", ") + ")",
|
||||
Sources: env("TEMPLATE_NAME"),
|
||||
Category: shared.CategoryTemplates,
|
||||
OnlyOnce: true,
|
||||
Config: trim,
|
||||
}
|
||||
defaultCodeToRenderFlag = cli.UintFlag{
|
||||
Name: "default-error-page",
|
||||
Usage: "The code of the default (index page, when a code is not specified) error page to render",
|
||||
Value: uint64(cfg.DefaultCodeToRender),
|
||||
Sources: env("DEFAULT_ERROR_PAGE"),
|
||||
Category: shared.CategoryCodes,
|
||||
Name: "default-error-page",
|
||||
Usage: "the code of the default (index page, when a code is not specified) error page to render",
|
||||
Value: uint64(cfg.DefaultCodeToRender),
|
||||
Sources: env("DEFAULT_ERROR_PAGE"),
|
||||
Validator: func(code uint64) error {
|
||||
if code > 999 { //nolint:mnd
|
||||
return fmt.Errorf("wrong HTTP code [%d] for the default error page", code)
|
||||
@ -99,19 +94,17 @@ func NewCommand(log *logger.Logger) *cli.Command { //nolint:funlen,gocognit,gocy
|
||||
}
|
||||
sendSameHTTPCodeFlag = cli.BoolFlag{
|
||||
Name: "send-same-http-code",
|
||||
Usage: "The HTTP response should have the same status code as the requested error page (by default, " +
|
||||
Usage: "the HTTP response should have the same status code as the requested error page (by default, " +
|
||||
"every response with an error page will have a status code of 200)",
|
||||
Value: cfg.RespondWithSameHTTPCode,
|
||||
Sources: env("SEND_SAME_HTTP_CODE"),
|
||||
Category: shared.CategoryOther,
|
||||
OnlyOnce: true,
|
||||
}
|
||||
showDetailsFlag = cli.BoolFlag{
|
||||
Name: "show-details",
|
||||
Usage: "Show request details in the error page response (if supported by the template)",
|
||||
Usage: "show request details in the error page response (if supported by the template)",
|
||||
Value: cfg.ShowDetails,
|
||||
Sources: env("SHOW_DETAILS"),
|
||||
Category: shared.CategoryOther,
|
||||
OnlyOnce: true,
|
||||
}
|
||||
proxyHeadersListFlag = cli.StringFlag{
|
||||
@ -129,16 +122,14 @@ func NewCommand(log *logger.Logger) *cli.Command { //nolint:funlen,gocognit,gocy
|
||||
|
||||
return nil
|
||||
},
|
||||
Category: shared.CategoryOther,
|
||||
OnlyOnce: true,
|
||||
Config: trim,
|
||||
}
|
||||
rotationModeFlag = cli.StringFlag{
|
||||
Name: "rotation-mode",
|
||||
Value: config.RotationModeDisabled.String(),
|
||||
Usage: "Templates automatic rotation mode (" + strings.Join(config.RotationModeStrings(), "/") + ")",
|
||||
Usage: "templates automatic rotation mode (" + strings.Join(config.RotationModeStrings(), "/") + ")",
|
||||
Sources: env("TEMPLATES_ROTATION_MODE"),
|
||||
Category: shared.CategoryTemplates,
|
||||
OnlyOnce: true,
|
||||
Config: trim,
|
||||
Validator: func(s string) error {
|
||||
@ -151,27 +142,26 @@ func NewCommand(log *logger.Logger) *cli.Command { //nolint:funlen,gocognit,gocy
|
||||
}
|
||||
readBufferSizeFlag = cli.UintFlag{
|
||||
Name: "read-buffer-size",
|
||||
Usage: "Per-connection buffer size in bytes for reading requests, this also limits the maximum header size " +
|
||||
Usage: "per-connection buffer size in bytes for reading requests, this also limits the maximum header size " +
|
||||
"(increase this buffer if your clients send multi-KB Request URIs and/or multi-KB headers (e.g., " +
|
||||
"large cookies), note that increasing this value will increase memory consumption)",
|
||||
Value: 1024 * 5, //nolint:mnd // 5 KB
|
||||
Sources: env("READ_BUFFER_SIZE"),
|
||||
Category: shared.CategoryOther,
|
||||
OnlyOnce: true,
|
||||
}
|
||||
)
|
||||
|
||||
// override some flag usage messages
|
||||
addrFlag.Usage = "The HTTP server will listen on this IP (v4 or v6) address (set 127.0.0.1/::1 for localhost, " +
|
||||
addrFlag.Usage = "the HTTP server will listen on this IP (v4 or v6) address (set 127.0.0.1 for localhost, " +
|
||||
"0.0.0.0 to listen on all interfaces, or specify a custom IP)"
|
||||
portFlag.Usage = "The TCP port number for the HTTP server to listen on (0-65535)"
|
||||
portFlag.Usage = "the TCP port number for the HTTP server to listen on (0-65535)"
|
||||
|
||||
disableL10nFlag.Value = cfg.L10n.Disable // set the default value depending on the configuration
|
||||
|
||||
cmd.c = &cli.Command{
|
||||
Name: "serve",
|
||||
Aliases: []string{"s", "server", "http"},
|
||||
Usage: "Please start the HTTP server to serve the error pages. You can configure various options - please RTFM :D",
|
||||
Usage: "Start HTTP server",
|
||||
Suggest: true,
|
||||
Action: func(ctx context.Context, c *cli.Command) error {
|
||||
cmd.opt.http.addr = c.String(addrFlag.Name)
|
||||
|
@ -36,7 +36,7 @@ func TestCommand_Run(t *testing.T) {
|
||||
"--add-template", "./testdata/foo-template.html",
|
||||
"--disable-template", "ghost",
|
||||
"--disable-template", "<unknown>",
|
||||
"--add-code", "200=Code/Description",
|
||||
"--add-http-code", "200=Code/Description",
|
||||
"--json-format", "json format",
|
||||
"--xml-format", "xml format",
|
||||
"--plaintext-format", "plaintext format",
|
||||
|
@ -11,15 +11,6 @@ import (
|
||||
"gh.tarampamp.am/error-pages/internal/config"
|
||||
)
|
||||
|
||||
const (
|
||||
CategoryHTTP = "HTTP:"
|
||||
CategoryTemplates = "TEMPLATES:"
|
||||
CategoryCodes = "HTTP CODES:"
|
||||
CategoryFormats = "FORMATS:"
|
||||
CategoryBuild = "BUILD:"
|
||||
CategoryOther = "OTHER:"
|
||||
)
|
||||
|
||||
// Note: Don't use pointers for flags, because they have own state which is not thread-safe.
|
||||
// https://github.com/urfave/cli/issues/1926
|
||||
|
||||
@ -29,7 +20,6 @@ var ListenAddrFlag = cli.StringFlag{
|
||||
Usage: "IP (v4 or v6) address to listen on",
|
||||
Value: "0.0.0.0", // bind to all interfaces by default
|
||||
Sources: cli.EnvVars("LISTEN_ADDR"),
|
||||
Category: CategoryHTTP,
|
||||
OnlyOnce: true,
|
||||
Config: cli.StringConfig{TrimSpace: true},
|
||||
Validator: func(ip string) error {
|
||||
@ -51,7 +41,6 @@ var ListenPortFlag = cli.UintFlag{
|
||||
Usage: "TCP port number",
|
||||
Value: 8080, // default port number
|
||||
Sources: cli.EnvVars("LISTEN_PORT"),
|
||||
Category: CategoryHTTP,
|
||||
OnlyOnce: true,
|
||||
Validator: func(port uint64) error {
|
||||
if port == 0 || port > 65535 {
|
||||
@ -64,10 +53,9 @@ var ListenPortFlag = cli.UintFlag{
|
||||
|
||||
var AddTemplatesFlag = cli.StringSliceFlag{
|
||||
Name: "add-template",
|
||||
Usage: "To add a new template, provide the path to the file using this flag (the filename without the extension " +
|
||||
Usage: "to add a new template, provide the path to the file using this flag (the filename without the extension " +
|
||||
"will be used as the template name)",
|
||||
Config: cli.StringConfig{TrimSpace: true},
|
||||
Category: CategoryTemplates,
|
||||
Config: cli.StringConfig{TrimSpace: true},
|
||||
Validator: func(paths []string) error {
|
||||
for _, path := range paths {
|
||||
if path == "" {
|
||||
@ -84,19 +72,18 @@ var AddTemplatesFlag = cli.StringSliceFlag{
|
||||
}
|
||||
|
||||
var DisableTemplateNamesFlag = cli.StringSliceFlag{
|
||||
Name: "disable-template",
|
||||
Usage: "Disable the specified template by its name (useful to disable the built-in templates and use only custom ones)",
|
||||
Config: cli.StringConfig{TrimSpace: true},
|
||||
Category: CategoryTemplates,
|
||||
Name: "disable-template",
|
||||
Usage: "disable the specified template by its name (useful to disable the built-in templates and use only custom ones)",
|
||||
Config: cli.StringConfig{TrimSpace: true},
|
||||
}
|
||||
|
||||
var AddHTTPCodesFlag = cli.StringMapFlag{
|
||||
Name: "add-code",
|
||||
Usage: "To add a new HTTP status code, provide the code and its message/description using this flag (the format " +
|
||||
Name: "add-http-code",
|
||||
Aliases: []string{"add-code"},
|
||||
Usage: "to add a new HTTP status code, provide the code and its message/description using this flag (the format " +
|
||||
"should be '%code%=%message%/%description%'; the code may contain a wildcard '*' to cover multiple codes at " +
|
||||
"once, for example, '4**' will cover all 4xx codes unless a more specific code is described previously)",
|
||||
Config: cli.StringConfig{TrimSpace: true},
|
||||
Category: CategoryCodes,
|
||||
Config: cli.StringConfig{TrimSpace: true},
|
||||
Validator: func(codes map[string]string) error {
|
||||
for code, msgAndDesc := range codes {
|
||||
if code == "" {
|
||||
@ -141,8 +128,7 @@ func ParseHTTPCodes(codes map[string]string) map[string]config.CodeDescription {
|
||||
|
||||
var DisableL10nFlag = cli.BoolFlag{
|
||||
Name: "disable-l10n",
|
||||
Usage: "Disable localization of error pages (if the template supports localization)",
|
||||
Usage: "disable localization of error pages (if the template supports localization)",
|
||||
Sources: cli.EnvVars("DISABLE_L10N"),
|
||||
Category: CategoryOther,
|
||||
OnlyOnce: true,
|
||||
}
|
||||
|
@ -122,7 +122,7 @@ func TestAddHTTPCodesFlag(t *testing.T) {
|
||||
|
||||
var flag = shared.AddHTTPCodesFlag
|
||||
|
||||
assert.Equal(t, "add-code", flag.Name)
|
||||
assert.Equal(t, "add-http-code", flag.Name)
|
||||
|
||||
for name, tt := range map[string]struct {
|
||||
giveValue map[string]string
|
||||
|
@ -51,7 +51,7 @@ func NewServer(log *logger.Logger, readBufferSize uint) Server {
|
||||
}
|
||||
|
||||
// Register server handlers, middlewares, etc.
|
||||
func (s *Server) Register(cfg *config.Config) error { //nolint:funlen
|
||||
func (s *Server) Register(cfg *config.Config) error {
|
||||
var (
|
||||
liveHandler = live.New()
|
||||
versionHandler = version.New(appmeta.Version())
|
||||
@ -71,7 +71,7 @@ func (s *Server) Register(cfg *config.Config) error { //nolint:funlen
|
||||
|
||||
switch {
|
||||
// live endpoints
|
||||
case url == "/healthz" || url == "/health/live" || url == "/health" || url == "/live":
|
||||
case url == "/health/live" || url == "/health" || url == "/healthz" || url == "/live":
|
||||
liveHandler(ctx)
|
||||
|
||||
// version endpoint
|
||||
@ -87,9 +87,8 @@ func (s *Server) Register(cfg *config.Config) error { //nolint:funlen
|
||||
// - /{code}.html
|
||||
// - /{code}.htm
|
||||
// - /{code}
|
||||
//
|
||||
// the HTTP method is not limited to GET and HEAD - it can be any
|
||||
case url == "/" || ep.URLContainsCode(url) || ep.HeadersContainCode(&ctx.Request.Header):
|
||||
case method == fasthttp.MethodGet &&
|
||||
(url == "/" || ep.URLContainsCode(url) || ep.HeadersContainCode(&ctx.Request.Header)):
|
||||
errorPagesHandler(ctx)
|
||||
|
||||
// wrong requests handling
|
||||
|
@ -221,16 +221,6 @@ func TestRouting(t *testing.T) {
|
||||
assert.Contains(t, string(body), "404: Not Found")
|
||||
assert.Contains(t, headers.Get("Content-Type"), "text/plain")
|
||||
})
|
||||
|
||||
t.Run("other HTTP methods", func(t *testing.T) {
|
||||
for _, method := range []string{http.MethodDelete, http.MethodPatch, http.MethodPost, http.MethodPut} {
|
||||
var status, body, headers = sendRequest(t, method, baseUrl+"/404.html")
|
||||
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
assert.Contains(t, string(body), "404: Not Found")
|
||||
assert.Contains(t, headers.Get("Content-Type"), "text/plain")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("failure", func(t *testing.T) {
|
||||
@ -274,6 +264,15 @@ func TestRouting(t *testing.T) {
|
||||
assert.Equal(t, http.StatusNotFound, status)
|
||||
assertIsNotErrorPage(t, body)
|
||||
})
|
||||
|
||||
t.Run("invalid HTTP methods", func(t *testing.T) {
|
||||
for _, method := range []string{http.MethodDelete, http.MethodPatch, http.MethodPost, http.MethodPut} {
|
||||
var status, body, _ = sendRequest(t, method, baseUrl+"/404.html")
|
||||
|
||||
assert.Equal(t, http.StatusMethodNotAllowed, status)
|
||||
assertIsNotErrorPage(t, body)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
Reference in New Issue
Block a user