Skip to content

App

The core application type.

Creating an App

app := marten.New()

Methods

Run

Start the server.

func (a *App) Run(addr string) error
app.Run(":8080")

RunGraceful

Start with graceful shutdown support.

func (a *App) RunGraceful(addr string, timeout time.Duration) error
app.RunGraceful(":8080", 10*time.Second)

Handles SIGINT and SIGTERM signals, allowing in-flight requests to complete.

Use

Add global middleware.

func (a *App) Use(mw ...Middleware)
app.Use(middleware.Logger, middleware.Recover)

OnError

Set custom error handler.

func (a *App) OnError(fn func(*Ctx, error))
app.OnError(func(c *marten.Ctx, err error) {
    log.Printf("Error: %v", err)
    c.ServerError("something went wrong")
})

NotFound

Set custom 404 handler.

func (a *App) NotFound(h Handler)
app.NotFound(func(c *marten.Ctx) error {
    return c.JSON(404, marten.M{"error": "not found"})
})

OnStart

Register a callback to run when the server starts.

func (a *App) OnStart(fn func())
app.OnStart(func() {
    log.Println("Server starting...")
    // Initialize connections, warm caches, etc.
})

OnShutdown

Register a callback to run when the server shuts down gracefully.

func (a *App) OnShutdown(fn func())
app.OnShutdown(func() {
    log.Println("Server shutting down...")
    // Close database connections, flush buffers, etc.
    db.Close()
})

Group

Create a route group.

func (a *App) Group(prefix string) *Group
api := app.Group("/api/v1")
api.GET("/users", listUsers)

Route Methods

app.GET(path string, h Handler, mw ...Middleware)
app.POST(path string, h Handler, mw ...Middleware)
app.PUT(path string, h Handler, mw ...Middleware)
app.DELETE(path string, h Handler, mw ...Middleware)
app.PATCH(path string, h Handler, mw ...Middleware)
app.Handle(method, path string, h Handler, mw ...Middleware)

ServeHTTP

App implements http.Handler:

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

Use with custom server:

server := &http.Server{
    Addr:         ":8080",
    Handler:      app,
    ReadTimeout:  5 * time.Second,
    WriteTimeout: 10 * time.Second,
}
server.ListenAndServe()