Context (Ctx)¶
Request context with helpers for clean handler code.
Properties¶
Response Methods¶
JSON Response¶
Text Response¶
HTML Response¶
Binary Response¶
Stream Response¶
No Content¶
Error Responses¶
c.BadRequest(message string) error // 400
c.Unauthorized(message string) error // 401
c.Forbidden(message string) error // 403
c.NotFound(message string) error // 404
c.ServerError(message string) error // 500
Status & Headers¶
c.Status(code int) *Ctx
c.StatusCode() int
c.Header(key, value string) *Ctx
c.GetHeader(key string) string
c.Written() bool
c.Redirect(code int, url string) error
Request Data¶
Path Parameters¶
Query Parameters¶
c.Query(name string) string
c.QueryInt(name string) int
c.QueryInt64(name string) int64
c.QueryBool(name string) bool
c.QueryDefault(name, def string) string
c.QueryValues(name string) []string
c.QueryParams() url.Values
Body Binding¶
Bind() supports multiple content types:
application/json- JSON bodyapplication/x-www-form-urlencoded- Form datamultipart/form-data- Multipart form data
Form & Files¶
Cookies¶
Request Helpers¶
c.Method() string
c.Path() string
c.ClientIP() string
c.Bearer() string
c.RequestID() string
c.IsJSON() bool
c.IsAJAX() bool
c.Context() context.Context
Request-Scoped Storage¶
c.Set(key string, value any)
c.Get(key string) any
c.GetString(key string) string
c.GetInt(key string) int
c.GetBool(key string) bool
Examples¶
JSON API Handler¶
func getUser(c *marten.Ctx) error {
id := c.ParamInt("id")
user, err := db.FindUser(id)
if err != nil {
return c.NotFound("user not found")
}
return c.OK(user)
}
Streaming Response¶
func downloadFile(c *marten.Ctx) error {
file, err := os.Open("large-file.zip")
if err != nil {
return c.NotFound("file not found")
}
defer file.Close()
c.Header("Content-Disposition", "attachment; filename=file.zip")
return c.Stream(200, "application/octet-stream", file)
}
HTML Response¶
func homePage(c *marten.Ctx) error {
html := "<html><body><h1>Welcome</h1></body></html>"
return c.HTML(200, html)
}
Form Handling¶
func createPost(c *marten.Ctx) error {
title := c.FormValue("title")
file, err := c.File("image")
if err != nil {
return c.BadRequest("image required")
}
// Process...
return c.Created(marten.M{"id": newID})
}
Request Validation¶
func createUser(c *marten.Ctx) error {
var input struct {
Name string `json:"name"`
Email string `json:"email"`
}
if err := c.BindValid(&input, func() error {
if input.Name == "" {
return &marten.BindError{Message: "name required"}
}
return nil
}); err != nil {
return c.BadRequest(err.Error())
}
return c.Created(input)
}