chore(deps)!: migrate from echo v4 to echo v5

This commit is contained in:
Julien Neuhart
2026-09-16 19:38:45 +02:00
parent 8e850b1c93
commit 2f9020455a
18 changed files with 356 additions and 164 deletions

View File

@@ -13,9 +13,8 @@ import (
"github.com/alexliesenfeld/health"
"github.com/dlclark/regexp2"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v5"
flag "github.com/spf13/pflag"
"golang.org/x/net/http2"
"golang.org/x/sync/errgroup"
"github.com/gotenberg/gotenberg/v8/pkg/gotenberg"
@@ -58,6 +57,12 @@ type Api struct {
fs *gotenberg.FileSystem
logger *slog.Logger
srv *echo.Echo
// shutdownCancel triggers the graceful shutdown of the server started by
// [echo.StartConfig]. Echo v5 drives shutdown from a context instead of an
// Echo.Shutdown method. serveDone closes once that shutdown completed.
shutdownCancel context.CancelFunc
serveDone chan struct{}
}
type downloadFromConfig struct {
@@ -134,7 +139,7 @@ const (
// middleware := Middleware{
// Handler: func() echo.MiddlewareFunc {
// return func(next echo.HandlerFunc) echo.HandlerFunc {
// return func(c echo.Context) error {
// return func(c *echo.Context) error {
// rootPath := c.Get("rootPath").(string)
// healthURI := fmt.Sprintf("%shealth", rootPath)
//
@@ -536,16 +541,29 @@ func (a *Api) Validate() error {
return nil
}
// newEchoServer builds the [echo.Echo] instance with the settings Gotenberg
// relies on, independently of the routes and middlewares added by [Api.Start].
func newEchoServer() *echo.Echo {
srv := echo.New()
srv.HTTPErrorHandler = httpErrorHandler()
// Echo v5 serves files through Echo.Filesystem, an [fs.FS] rooted at the
// working directory, and [fs.FS] rejects absolute names. Every output file
// lives under the request's temporary directory, so Context.Attachment gets
// an absolute path and the default filesystem answers 404 for every
// conversion. Rooting at "/" restores the v4 behavior, where the path was
// opened as-is.
srv.Filesystem = echo.NewDefaultFS("/")
// Echo v5 dropped the X-Forwarded-For and X-Real-IP fallbacks from
// Context.RealIP. Keep the previous behavior so that the access log still
// reports the client IP when Gotenberg sits behind a reverse proxy.
srv.IPExtractor = echo.LegacyIPExtractor()
return srv
}
// Start starts the HTTP server.
func (a *Api) Start() error {
a.srv = echo.New()
a.srv.HideBanner = true
a.srv.HidePort = true
a.srv.Server.ReadTimeout = a.timeout
a.srv.Server.IdleTimeout = a.timeout
// See https://github.com/gotenberg/gotenberg/issues/396.
a.srv.Server.WriteTimeout = a.timeout + a.timeout
a.srv.HTTPErrorHandler = httpErrorHandler()
a.srv = newEchoServer()
// Let's prepare the modules' routes.
var disableTelemetryForPaths []string
@@ -609,7 +627,7 @@ func (a *Api) Start() error {
securityMiddleware = oidcAuthMiddleware(verifier)
default:
securityMiddleware = func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return func(c *echo.Context) error {
return next(c)
}
}
@@ -641,7 +659,7 @@ func (a *Api) Start() error {
// Root route.
a.srv.GET(
a.rootPath,
func(c echo.Context) error {
func(c *echo.Context) error {
return c.HTML(http.StatusOK, `Hey, Gotenberg has no UI, it's an API. Head to the <a href="https://gotenberg.dev">documentation</a> to learn how to interact with it 🚀`)
},
securityMiddleware,
@@ -650,7 +668,7 @@ func (a *Api) Start() error {
// Favicon route.
a.srv.GET(
fmt.Sprintf("%s%s", a.rootPath, "favicon.ico"),
func(c echo.Context) error {
func(c *echo.Context) error {
return c.NoContent(http.StatusNoContent)
},
securityMiddleware,
@@ -681,7 +699,7 @@ func (a *Api) Start() error {
// ...the version route.
a.srv.GET(
fmt.Sprintf("%s%s", a.rootPath, "version"),
func(c echo.Context) error {
func(c *echo.Context) error {
return c.String(http.StatusOK, gotenberg.Version)
},
securityMiddleware,
@@ -691,7 +709,7 @@ func (a *Api) Start() error {
if a.enableDebugRoute {
a.srv.GET(
fmt.Sprintf("%s%s", a.rootPath, "debug"),
func(c echo.Context) error {
func(c *echo.Context) error {
return c.JSONPretty(http.StatusOK, gotenberg.Debug(), " ")
},
securityMiddleware,
@@ -712,18 +730,50 @@ func (a *Api) Start() error {
return fmt.Errorf("waiting for modules readiness: %w", err)
}
startConfig := echo.StartConfig{
Address: fmt.Sprintf("%s:%d", a.bindIp, a.port),
HideBanner: true,
HidePort: true,
BeforeServeFunc: func(s *http.Server) error {
s.ReadTimeout = a.timeout
s.IdleTimeout = a.timeout
// See https://github.com/gotenberg/gotenberg/issues/396.
s.WriteTimeout = a.timeout + a.timeout
if a.tlsCertFile == "" || a.tlsKeyFile == "" {
// Serve HTTP/2 Cleartext (h2c). Echo v5 dropped
// StartH2CServer and golang.org/x/net/http2/h2c is deprecated,
// so the standard library serves h2c through Server.Protocols
// instead.
protocols := new(http.Protocols)
protocols.SetHTTP1(true)
protocols.SetUnencryptedHTTP2(true)
s.Protocols = protocols
}
return nil
},
}
// Not named cancel: that would reassign the readiness timeout's cancel from
// above, whose deferred call is already bound to the old value.
serveCtx, serveCancel := context.WithCancel(context.Background())
a.shutdownCancel = serveCancel
a.serveDone = make(chan struct{})
// As the following code is blocking, run it in a goroutine.
go func() {
defer close(a.serveDone)
var err error
if a.tlsCertFile != "" && a.tlsKeyFile != "" {
// Start an HTTPS server (supports HTTP/2).
err = a.srv.StartTLS(fmt.Sprintf("%s:%d", a.bindIp, a.port), a.tlsCertFile, a.tlsKeyFile)
err = startConfig.StartTLS(serveCtx, a.srv, a.tlsCertFile, a.tlsKeyFile)
} else {
// Start an HTTP/2 Cleartext (non-HTTPS) server.
server := &http2.Server{}
err = a.srv.StartH2CServer(fmt.Sprintf("%s:%d", a.bindIp, a.port), server)
err = startConfig.Start(serveCtx, a.srv)
}
if !errors.Is(err, http.ErrServerClosed) {
if err != nil && !errors.Is(err, http.ErrServerClosed) {
a.logger.ErrorContext(context.Background(), err.Error())
}
}()
@@ -740,6 +790,26 @@ func (a *Api) StartupMessage() string {
return fmt.Sprintf("server started on %s:%d", ip, a.port)
}
// shutdown triggers the server's graceful shutdown and waits for it to
// complete, or for ctx to be done. Cancelling the serve context is what Echo v5
// exposes in place of Echo.Shutdown: [echo.StartConfig] shuts the server down
// on its own deadline, so the shutdown proceeds even when ctx is already done.
func (a *Api) shutdown(ctx context.Context) error {
if a.shutdownCancel == nil {
// Start never ran, so there is nothing to shut down.
return nil
}
a.shutdownCancel()
select {
case <-a.serveDone:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// Stop stops the HTTP server.
func (a *Api) Stop(ctx context.Context) error {
for {
@@ -749,7 +819,7 @@ func (a *Api) Stop(ctx context.Context) error {
}
select {
case <-ctx.Done():
return a.srv.Shutdown(ctx)
return a.shutdown(ctx)
default:
a.logger.DebugContext(ctx, fmt.Sprintf("%d asynchronous requests", count))
if count > 0 {
@@ -757,7 +827,7 @@ func (a *Api) Stop(ctx context.Context) error {
continue
}
a.logger.DebugContext(ctx, "no more asynchronous requests, continue with shutdown")
err := a.srv.Shutdown(ctx)
err := a.shutdown(ctx)
if err != nil {
return fmt.Errorf("shutdown: %w", err)
}

View File

@@ -18,7 +18,7 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/go-retryablehttp"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v5"
"github.com/mholt/archives"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
@@ -70,7 +70,7 @@ type Context struct {
outputFilename string
logger *slog.Logger
echoCtx echo.Context
echoCtx *echo.Context
mkdirAll gotenberg.MkdirAll
pathRename gotenberg.PathRename
context.Context
@@ -158,7 +158,7 @@ type downloadFrom struct {
}
// newContext returns a [Context] by parsing a "multipart/form-data" request.
func newContext(echoCtx echo.Context, logger *slog.Logger, fs *gotenberg.FileSystem, timeout time.Duration, bodyLimit int64, downloadFromCfg downloadFromConfig) (*Context, context.CancelFunc, error) {
func newContext(echoCtx *echo.Context, logger *slog.Logger, fs *gotenberg.FileSystem, timeout time.Duration, bodyLimit int64, downloadFromCfg downloadFromConfig) (*Context, context.CancelFunc, error) {
processCtx, processCancel := context.WithTimeout(echoCtx.Request().Context(), timeout)
// We want to make sure the multipart/form-data does not exceed a given

View File

@@ -20,7 +20,7 @@ import (
"time"
"github.com/dlclark/regexp2"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v5"
"github.com/gotenberg/gotenberg/v8/pkg/gotenberg"
)

View File

@@ -12,8 +12,8 @@ import (
"github.com/coreos/go-oidc/v3/oidc"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/labstack/echo/v5"
"github.com/labstack/echo/v5/middleware"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
@@ -37,10 +37,12 @@ var (
// ParseError parses an error and returns the corresponding HTTP status and
// HTTP message.
func ParseError(err error) (int, string) {
var echoErr *echo.HTTPError
ok := errors.As(err, &echoErr)
if ok {
return echoErr.Code, http.StatusText(echoErr.Code)
// [echo.StatusCode] also matches the router's ErrNotFound and
// ErrMethodNotAllowed sentinels, which Echo v5 no longer models as
// [echo.HTTPError]. Matching that type alone would let every unrouted
// request fall through to a 500.
if code := echo.StatusCode(err); code != 0 {
return code, http.StatusText(code)
}
if errors.Is(err, context.DeadlineExceeded) {
@@ -100,14 +102,14 @@ const statusClientClosedRequest = 499
// A server-side timeout is [context.DeadlineExceeded], mapped to 503 by
// [ParseError], and is deliberately not treated as a client abort.
// See https://github.com/gotenberg/gotenberg/issues/1627.
func requestCanceled(c echo.Context, err error) bool {
func requestCanceled(c *echo.Context, err error) bool {
return errors.Is(err, context.Canceled) && errors.Is(c.Request().Context().Err(), context.Canceled)
}
// httpErrorHandler is the centralized HTTP error handler. It parses the error,
// returns a response as "text/plain; charset=UTF-8".
func httpErrorHandler() echo.HTTPErrorHandler {
return func(err error, c echo.Context) {
return func(c *echo.Context, err error) {
logger := c.Get("logger").(*slog.Logger)
if requestCanceled(c, err) {
@@ -134,7 +136,7 @@ func httpErrorHandler() echo.HTTPErrorHandler {
// startTime := c.Get("startTime").(time.Time)
func latencyMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return func(c *echo.Context) error {
// First piece for calculating the latency.
startTime := time.Now()
c.Set("startTime", startTime)
@@ -159,7 +161,7 @@ func latencyMiddleware() echo.MiddlewareFunc {
// }
func rootPathMiddleware(rootPath string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return func(c *echo.Context) error {
c.Set("rootPath", rootPath)
// Call the next middleware in the chain.
return next(c)
@@ -173,7 +175,7 @@ func rootPathMiddleware(rootPath string) echo.MiddlewareFunc {
// outputFilename := c.Get("outputFilename").(string)
func outputFilenameMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return func(c *echo.Context) error {
filename := c.Request().Header.Get("Gotenberg-Output-Filename")
// Keep only the last path segment, so that a caller cannot name an
// output file after a path.
@@ -203,10 +205,18 @@ func telemetryMiddleware(logger *slog.Logger, serverName, correlationIdHeader st
semconvSrv := semconvutil.NewHTTPServer(meter)
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return func(c *echo.Context) error {
startTime := c.Get("startTime").(time.Time)
rootPath := c.Get("rootPath").(string)
// Echo v5 returns the bare [http.ResponseWriter] from
// Context.Response, so unwrap it to read the recorded status and
// size below.
response, errUnwrap := echo.UnwrapResponse(c.Response())
if errUnwrap != nil {
return fmt.Errorf("unwrap response: %w", errUnwrap)
}
request := c.Request()
savedCtx := request.Context()
defer func() {
@@ -239,7 +249,7 @@ func telemetryMiddleware(logger *slog.Logger, serverName, correlationIdHeader st
err := next(c)
if err != nil {
c.Error(err)
c.Echo().HTTPErrorHandler(c, err)
}
return nil
}
@@ -288,7 +298,7 @@ func telemetryMiddleware(logger *slog.Logger, serverName, correlationIdHeader st
err := next(c)
finishTime := time.Now()
status := c.Response().Status
status := response.Status
canceled := false
if err != nil {
canceled = requestCanceled(c, err)
@@ -300,13 +310,13 @@ func telemetryMiddleware(logger *slog.Logger, serverName, correlationIdHeader st
}
span.SetAttributes(attribute.String("error", err.Error()))
c.Error(err)
c.Echo().HTTPErrorHandler(c, err)
}
span.SetStatus(semconvSrv.Status(status))
span.SetAttributes(semconvSrv.ResponseTraceAttrs(semconvutil.ResponseTelemetry{
StatusCode: status,
WriteBytes: c.Response().Size,
WriteBytes: response.Size,
})...)
// Pick the level and message before building the record: err.Error
@@ -343,11 +353,11 @@ func telemetryMiddleware(logger *slog.Logger, serverName, correlationIdHeader st
slog.String("path", routePath),
slog.String("referer", c.Request().Referer()),
slog.String("user_agent", c.Request().UserAgent()),
slog.Int("status", c.Response().Status),
slog.Int("status", response.Status),
slog.Int64("latency", int64(latency)),
slog.String("latency_human", latency.String()),
slog.Int64("bytes_in", c.Request().ContentLength),
slog.Int64("bytes_out", c.Response().Size),
slog.Int64("bytes_out", response.Size),
)
additionalAttributes := []attribute.KeyValue{
@@ -356,7 +366,7 @@ func telemetryMiddleware(logger *slog.Logger, serverName, correlationIdHeader st
semconvSrv.RecordMetrics(ctx, semconvutil.ServerMetricData{
ServerName: serverName,
ResponseSize: c.Response().Size,
ResponseSize: response.Size,
Req: request,
StatusCode: status,
AdditionalAttributes: additionalAttributes,
@@ -371,7 +381,7 @@ func telemetryMiddleware(logger *slog.Logger, serverName, correlationIdHeader st
// basicAuthMiddleware manages basic authentication.
func basicAuthMiddleware(username, password string) echo.MiddlewareFunc {
return middleware.BasicAuth(func(u string, p string, e echo.Context) (bool, error) {
return middleware.BasicAuth(func(c *echo.Context, u string, p string) (bool, error) {
if subtle.ConstantTimeCompare([]byte(u), []byte(username)) == 1 &&
subtle.ConstantTimeCompare([]byte(p), []byte(password)) == 1 {
return true, nil
@@ -417,7 +427,7 @@ func (a *Api) buildOidcVerifier() (*oidc.IDTokenVerifier, error) {
// it to the client.
func oidcAuthMiddleware(verifier *oidc.IDTokenVerifier) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return func(c *echo.Context) error {
rawToken, ok := strings.CutPrefix(c.Request().Header.Get("Authorization"), "Bearer ")
if !ok || rawToken == "" {
return echo.NewHTTPError(http.StatusUnauthorized, "a Bearer token is required in the Authorization header")
@@ -446,7 +456,7 @@ func oidcAuthMiddleware(verifier *oidc.IDTokenVerifier) echo.MiddlewareFunc {
// cancel := c.Get("cancel").(context.CancelFunc)
func contextMiddleware(fs *gotenberg.FileSystem, timeout time.Duration, bodyLimit int64, downloadFromCfg downloadFromConfig) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return func(c *echo.Context) error {
logger, _ := c.Get("logger").(*slog.Logger)
if logger == nil {
return errors.New("no logger in context (possible pool reuse)")
@@ -507,7 +517,7 @@ func contextMiddleware(fs *gotenberg.FileSystem, timeout time.Duration, bodyLimi
// handler fails to timeout as expected.
func hardTimeoutMiddleware(hardTimeout time.Duration) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return func(c *echo.Context) error {
// Guard the type assertion so a pooled [echo.Context] whose
// store has been recycled under us does not crash the process.
// See the webhook async handler for the race this protects

View File

@@ -1,6 +1,7 @@
package api
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
@@ -9,13 +10,15 @@ import (
"log/slog"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/coreos/go-oidc/v3/oidc/oidctest"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v5"
)
// TestRequestCanceled pins the client-abort discriminator: only a
@@ -73,7 +76,7 @@ func TestHttpErrorHandler_ClientClosedRequest(t *testing.T) {
c := echo.New().NewContext(req, rec)
c.Set("logger", slog.New(slog.DiscardHandler))
httpErrorHandler()(tc.err, c)
httpErrorHandler()(c, tc.err)
if rec.Code != tc.wantStatus {
t.Fatalf("status = %d, want %d", rec.Code, tc.wantStatus)
@@ -105,7 +108,7 @@ func TestOutputFilenameMiddleware(t *testing.T) {
{"control characters", "fo\x01o\x7f", "foo"},
} {
t.Run(tc.name, func(t *testing.T) {
handler := outputFilenameMiddleware()(func(c echo.Context) error { return nil })
handler := outputFilenameMiddleware()(func(c *echo.Context) error { return nil })
req := httptest.NewRequest(http.MethodPost, "/", nil)
if tc.header != "" {
@@ -131,7 +134,7 @@ func TestOutputFilenameMiddleware(t *testing.T) {
func TestHardTimeoutMiddleware_MissingLoggerReturnsErrorInsteadOfPanicking(t *testing.T) {
mw := hardTimeoutMiddleware(100 * time.Millisecond)
handler := mw(func(c echo.Context) error { return nil })
handler := mw(func(c *echo.Context) error { return nil })
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
@@ -220,7 +223,7 @@ func TestOidcAuthMiddleware(t *testing.T) {
}
c := echo.New().NewContext(req, httptest.NewRecorder())
handler := oidcAuthMiddleware(verifier)(func(c echo.Context) error {
handler := oidcAuthMiddleware(verifier)(func(c *echo.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -243,3 +246,114 @@ func TestOidcAuthMiddleware(t *testing.T) {
})
}
}
// TestParseError_StatusMapping pins the statuses [ParseError] derives from the
// errors Echo and Gotenberg produce.
//
// Echo v5 models the router's ErrNotFound and ErrMethodNotAllowed as an
// unexported type rather than [echo.HTTPError], so matching that type alone
// would turn every unrouted request into a 500. It also guards the ordering:
// Gotenberg's own [SentinelHttpError] carries a client-facing message and must
// not be shadowed by the generic status lookup.
func TestParseError_StatusMapping(t *testing.T) {
for _, tc := range []struct {
scenario string
err error
wantStatus int
wantMessage string
}{
{"router not found", echo.ErrNotFound, http.StatusNotFound, http.StatusText(http.StatusNotFound)},
{"router method not allowed", echo.ErrMethodNotAllowed, http.StatusMethodNotAllowed, http.StatusText(http.StatusMethodNotAllowed)},
{"explicit HTTP error", echo.NewHTTPError(http.StatusUnauthorized, "nope"), http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized)},
{"wrapped HTTP error", fmt.Errorf("authenticate request: %w", echo.NewHTTPError(http.StatusUnauthorized, "nope")), http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized)},
{"sentinel keeps its message", NewSentinelHttpError(http.StatusBadRequest, "Invalid 'foo' form field value"), http.StatusBadRequest, "Invalid 'foo' form field value"},
{"unknown error", errors.New("boom"), http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)},
} {
t.Run(tc.scenario, func(t *testing.T) {
status, message := ParseError(tc.err)
if status != tc.wantStatus {
t.Fatalf("status = %d, want %d", status, tc.wantStatus)
}
if message != tc.wantMessage {
t.Fatalf("message = %q, want %q", message, tc.wantMessage)
}
})
}
}
// TestNewEchoServer_RealIP pins the client IP extraction that the access log's
// "remote_ip" field depends on.
//
// Echo v5.1.0 dropped the X-Forwarded-For and X-Real-IP fallbacks from
// Context.RealIP, so without an explicit extractor a Gotenberg behind a reverse
// proxy would log the proxy's address for every request. [newEchoServer]
// restores the previous behavior.
func TestNewEchoServer_RealIP(t *testing.T) {
srv := newEchoServer()
if srv.IPExtractor == nil {
t.Fatal("no IPExtractor configured: remote_ip would report the proxy address")
}
for _, tc := range []struct {
scenario string
headers map[string]string
want string
}{
{"x-forwarded-for keeps the client, not the proxy", map[string]string{"X-Forwarded-For": "203.0.113.7, 70.41.3.18"}, "203.0.113.7"},
{"single x-forwarded-for", map[string]string{"X-Forwarded-For": "203.0.113.7"}, "203.0.113.7"},
{"bracketed IPv6 is unwrapped", map[string]string{"X-Forwarded-For": "[2001:db8::1], 70.41.3.18"}, "2001:db8::1"},
{"x-real-ip when no x-forwarded-for", map[string]string{"X-Real-IP": "203.0.113.9"}, "203.0.113.9"},
{"no headers falls back to the remote address", nil, "192.0.2.1"},
} {
t.Run(tc.scenario, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "192.0.2.1:1234"
for key, value := range tc.headers {
req.Header.Set(key, value)
}
c := srv.NewContext(req, httptest.NewRecorder())
if got := c.RealIP(); got != tc.want {
t.Fatalf("RealIP = %q, want %q", got, tc.want)
}
})
}
}
// TestNewEchoServer_AttachmentServesAbsolutePath pins the filesystem that every
// conversion response is sent through.
//
// Echo v5 serves files through Echo.Filesystem, an [fs.FS] rooted at the working
// directory, and [fs.FS] rejects absolute names. Gotenberg builds every output
// file under the request's temporary directory and hands Context.Attachment an
// absolute path, so with the default filesystem every conversion route answers
// 404 while still reading the whole upload.
func TestNewEchoServer_AttachmentServesAbsolutePath(t *testing.T) {
path := filepath.Join(t.TempDir(), "output.pdf")
want := []byte("%PDF-1.7 not really a PDF")
err := os.WriteFile(path, want, 0o600)
if err != nil {
t.Fatalf("write fixture: %v", err)
}
srv := newEchoServer()
rec := httptest.NewRecorder()
c := srv.NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec)
err = c.Attachment(path, "output.pdf")
if err != nil {
t.Fatalf("Attachment(%q) = %v, want nil", path, err)
}
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
if got := rec.Body.Bytes(); !bytes.Equal(got, want) {
t.Fatalf("body = %q, want %q", got, want)
}
if got := rec.Header().Get("Content-Disposition"); !strings.Contains(got, `filename="output.pdf"`) {
t.Fatalf("Content-Disposition = %q, want it to carry filename=\"output.pdf\"", got)
}
}

View File

@@ -4,7 +4,7 @@ import (
"log/slog"
"github.com/alexliesenfeld/health"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v5"
"github.com/gotenberg/gotenberg/v8/pkg/gotenberg"
)
@@ -83,7 +83,7 @@ func (ctx *ContextMock) SetLogger(logger *slog.Logger) {
//
// ctx := &api.ContextMock{Context: &api.Context{}}
// ctx.setEchoContext(c)
func (ctx *ContextMock) SetEchoContext(c echo.Context) {
func (ctx *ContextMock) SetEchoContext(c *echo.Context) {
ctx.echoCtx = c
}