API Reference

App

The main application struct that provides routing, middleware, scheduling, and other core functionalities.

Route Handlers #

Register routes bound to specific HTTP methods. Each handler can be a function that accepts a context and returns an error.


// Route Handlers - Method Signatures    
func Get(path string, handlers ...RouteHandler) error
func Post(path string, handlers ...RouteHandler) error
func Put(path string, handlers ...RouteHandler) error
func Delete(path string, handlers ...RouteHandler) error
func Patch(path string, handlers ...RouteHandler) error
func Head(path string, handlers ...RouteHandler) error
func Options(path string, handlers ...RouteHandler) error
func Connect(path string, handlers ...RouteHandler) error
func Trace(path string, handlers ...RouteHandler) error
        

// Simple GET handler
app.Get("/api/users", func(c *Context) error {
  return c.JSON(Map{"users": []string{"John", "Jane"}})
})

// POST handler with middleware
app.Post("/api/users", 
  RequireAuth(), 
  func(c *Context) error {
    return c.JSON(Map{"status": "User created"})
  },
)

// DELETE handler with multiple middleware
app.Delete("/api/users/:id", 
  RequireAuth(), 
  RequireAdmin(),
  func(c *Context) error {
    id := c.Param("id")
    return c.JSON(Map{"status": "User " + id + " deleted"})
  },
)
        

Path Parameters #

You can define parameters in your routes using the :param syntax for named parameters or * for a wildcard.


// Named parameter
app.Get("/users/:id", func(c *Context) error {
  id := c.Param("id")
  return c.String(fmt.Sprintf("User ID: %s", id))
})

// Multiple parameters
app.Get("/users/:id/posts/:postId", func(c *Context) error {
  id := c.Param("id")
  postId := c.Param("postId")
  return c.String(fmt.Sprintf("User: %s, Post: %s", id, postId))
})

// Wildcard parameter
app.Get("/files/*", func(c *Context) error {
  path := c.Param("*")
  return c.String(fmt.Sprintf("File path: %s", path))
})
        

Use #

Adds middleware to the application. Middleware functions are executed in the order they are added.

func Use(middleware ...Middleware)

// Add global middleware to all routes
app.Use(middleware.Logger())
app.Use(middleware.Recover())

// Add multiple middleware at once
app.Use(
  middleware.RequestID(),
  middleware.Logger(),
  middleware.Recover()
)
        

Service #

Registers a service with the application that can be accessed throughout your application.

func Service(name string, service interface{})

// Register a database service
dbService := &DatabaseService{Conn: dbConn}
app.Service("db", dbService)

// Register a cache service
cacheService := &CacheService{Client: redisClient}
app.Service("cache", cacheService)
        

Serve #

Starts the HTTP server on the specified port or uses the default port from the configuration.

func Serve(port ...string) error

// Start the server with default port from config
if err := app.Serve(); err != nil {
  log.Fatal(err)
}

// Start the server with a custom port
if err := app.Serve("6530"); err != nil {
  log.Fatal(err)
}

// Start the server with a custom address
if err := app.Serve("127.0.0.1:9000"); err != nil {
  log.Fatal(err)
}
        

Cron #

Adds a cron job to be executed on the given schedule. Supports both error-returning and non-error-returning handlers.

func Cron(id string, schedule string, handler interface{}) error

// Add a cron job with an error-returning handler
app.Cron("cleanup", "0 0 * * *", func() error {
  // Run at midnight every day
  return cleanupDatabase()
})

// Add a cron job with a simple handler
app.Cron("stats", "*/15 * * * *", func() {
  // Run every 15 minutes
  collectStats()
})
        

Legacy Methods #

For backward compatibility, these methods are also available:

func Schedule(id string, schedule string, handler func() error) error func ScheduleFunc(id string, schedule string, handler func()) error func RemoveSchedule(id string)

Scheduler #

Control the cron scheduler with these methods.

func RemoveCron(id string) func StopScheduler() func StartScheduler()

// Remove a specific cron job
app.RemoveCron("cleanup")

// Stop all scheduled jobs
app.StopScheduler()

// Start the scheduler after stopping it
app.StartScheduler()
        

Components #

Set various component handlers for the application.

func SetTemplateEngine(engine *TemplateEngine) func SetWebSocketHandler(handler *WebSocketHandler) func SetFileUpload(upload *FileUpload) func SetConfig(config *Config)

// Set the template engine
templateEngine := NewTemplateEngine("./views")
app.SetTemplateEngine(templateEngine)

// Set the WebSocket handler
wsHandler := NewWebSocketHandler()
app.SetWebSocketHandler(wsHandler)

// Set the file upload handler
uploader := NewFileUpload("./uploads")
app.SetFileUpload(uploader)

// Update the application config
newConfig := &Config{ReadTimeout: 10 * time.Second}
app.SetConfig(newConfig)
        

Validation #

Validate a struct using the built-in validator.

func Validate(s interface{}) ValidationErrors

type User struct {
  Name  string `validate:"required,min=3"`
  Email string `validate:"required,email"`
  Age   int    `validate:"required,gte=18"`
}

// Validate a struct
user := User{Name: "Jo", Email: "invalid", Age: 16}
errors := app.Validate(user)

if len(errors) > 0 {
  // Handle validation errors
  fmt.Println(errors)
}