Context
The Context is the most important part of Rue. It carries request data, response methods, and allows passing values between middleware.
Request Data
go
r.GET("/example", func(c *rue.Context) {
// Path parameters
id := c.Param("id")
// Query parameters
q := c.Query("q")
page := c.DefaultQuery("page", "1")
tags := c.QueryArray("tags")
// Headers
auth := c.GetHeader("Authorization")
contentType := c.GetHeader("Content-Type")
// Client info
ip := c.ClientIP()
method := c.Request.Method
path := c.Request.URL.Path
})
Response Methods
go
// JSON response
c.JSON(http.StatusOK, rue.H{"message": "success"})
// XML response
c.XML(http.StatusOK, user)
// Plain text (printf-style formatting)
c.String(http.StatusOK, "Hello %s", name)
// Plain text (no formatting)
c.Text(http.StatusOK, "Hello World")
// Raw data with content type
c.Data(http.StatusOK, "text/html", []byte("Hi
"))
// File download
c.File("path/to/file.pdf")
// Stream response
c.Stream(http.StatusOK, "application/octet-stream", reader)
// Redirect
c.Redirect(http.StatusFound, "/new-location")
Setting Headers
go
c.SetHeader("X-Custom-Header", "value")
c.SetHeader("Cache-Control", "no-cache")
c.SetHeader("Content-Disposition", "attachment; filename=file.pdf")
Context Values
Pass data between middleware and handlers:
go
// In middleware
func AuthMiddleware() rue.HandlerFunc {
return func(c *rue.Context) {
user := validateToken(c.GetHeader("Authorization"))
c.Set("user", user)
c.Set("authenticated", true)
c.Next()
}
}
// In handler
r.GET("/profile", func(c *rue.Context) {
// Get with existence check
user, exists := c.Get("user")
if !exists {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// Get without check (panics if not found)
user := c.MustGet("user")
c.JSON(http.StatusOK, user)
})
Flow Control
go
// Continue to next handler
c.Next()
// Stop handler chain
c.Abort()
// Stop and return status
c.AbortWithStatus(http.StatusForbidden)
// Stop and return error
c.AbortWithError(http.StatusBadRequest, err)
// Check if aborted
if c.IsAborted() {
return
}
Cookies
go
// Set cookie
c.SetCookie("session", "abc123", 3600, "/", "example.com", true, true)
// Get cookie
session, err := c.Cookie("session")