API Reference
Overview
Complete API reference for Weber framework. This page documents all available APIs, methods, and interfaces for both backend and frontend development.
App Module
app.App
The main application structure.
Methods
// Create new app instance
func New() *App
// Create with configuration
func NewWithConfig(cfg *Config) *App
// HTTP method handlers
func (a *App) GET(path string, handler HandlerFunc)
func (a *App) POST(path string, handler HandlerFunc)
func (a *App) PUT(path string, handler HandlerFunc)
func (a *App) DELETE(path string, handler HandlerFunc)
func (a *App) PATCH(path string, handler HandlerFunc)
func (a *App) OPTIONS(path string, handler HandlerFunc)
func (a *App) Handle(path string, handler HandlerFunc, methods ...string)
// Route groups
func (a *App) Group(prefix string, middleware ...MiddlewareFunc) *RouterGroup
// Middleware
func (a *App) Use(middleware ...MiddlewareFunc)
// Static files
func (a *App) Static(urlPath string, dirPath string)
func (a *App) StaticFile(urlPath string, filePath string)
// Error handlers
func (a *App) NoRoute(handler HandlerFunc)
func (a *App) OnError(handler ErrorHandlerFunc)
// Configuration
func (a *App) SetDebugMode(debug bool)
func (a *App) LoadTemplates(path string)
// Server
func (a *App) Run(addr string) error
func (a *App) RunTLS(addr, certFile, keyFile string) error
Context API
app.Context
Request context passed to handlers.
Request Methods
// Request info
func (c *Context) Method() string
func (c *Context) Path() string
func (c *Context) Host() string
func (c *Context) ClientIP() string
func (c *Context) UserAgent() string
// URL parameters
func (c *Context) Param(name string) string
func (c *Context) ParamInt(name string) (int, error)
func (c *Context) ParamInt64(name string) (int64, error)
// Query parameters
func (c *Context) Query(name string) string
func (c *Context) QueryDefault(name, defaultValue string) string
func (c *Context) QueryInt(name string) (int, error)
func (c *Context) QueryBool(name string) bool
func (c *Context) QueryArray(name string) []string
// Form data
func (c *Context) PostForm(name string) string
func (c *Context) PostFormDefault(name, defaultValue string) string
func (c *Context) PostFormAll() map[string]string
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
// Request body
func (c *Context) Body() ([]byte, error)
func (c *Context) BindJSON(obj interface{}) error
func (c *Context) BindXML(obj interface{}) error
Response Methods
// Status and headers
func (c *Context) SetStatus(code int)
func (c *Context) SetHeader(key, value string)
func (c *Context) GetHeader(key string) string
func (c *Context) SetContentType(contentType string)
// Response writers
func (c *Context) Text(code int, text string)
func (c *Context) JSON(code int, obj interface{})
func (c *Context) XML(code int, obj interface{})
func (c *Context) HTML(code int, html string)
func (c *Context) Render(template string, data interface{})
func (c *Context) File(filepath string)
func (c *Context) FileAttachment(filepath, filename string)
func (c *Context) Redirect(code int, location string)
func (c *Context) Write(data []byte) (int, error)
// Error responses
func (c *Context) Error(code int, message string)
func (c *Context) NotFound()
func (c *Context) BadRequest(message string)
func (c *Context) InternalServerError(message string)
func (c *Context) Unauthorized()
func (c *Context) Forbidden()
Cookie Methods
func (c *Context) Cookie(name string) string
func (c *Context) SetCookie(name, value string, maxAge int)
func (c *Context) SetCookieAdvanced(cookie *http.Cookie)
func (c *Context) DeleteCookie(name string)
Context Storage
func (c *Context) Set(key string, value interface{})
func (c *Context) Get(key string) (interface{}, bool)
func (c *Context) MustGet(key string) interface{}
func (c *Context) GetString(key string) string
func (c *Context) GetInt(key string) int
func (c *Context) GetBool(key string) bool
Router API
RouterGroup
// Create sub-group
func (g *RouterGroup) Group(prefix string, middleware ...MiddlewareFunc) *RouterGroup
// HTTP methods
func (g *RouterGroup) GET(path string, handler HandlerFunc)
func (g *RouterGroup) POST(path string, handler HandlerFunc)
func (g *RouterGroup) PUT(path string, handler HandlerFunc)
func (g *RouterGroup) DELETE(path string, handler HandlerFunc)
func (g *RouterGroup) PATCH(path string, handler HandlerFunc)
// Middleware
func (g *RouterGroup) Use(middleware ...MiddlewareFunc)
HTTP Client API
http Package
// Basic requests
func Get(url string) (*Response, error)
func Post(url string, data interface{}) (*Response, error)
func Put(url string, data interface{}) (*Response, error)
func Delete(url string) (*Response, error)
// With options
func Request(method, url string, options *RequestOptions) (*Response, error)
// With caching
func GetWithCache(url string, ttl time.Duration) (*Response, error)
// Request options
type RequestOptions struct {
Headers map[string]string
Query map[string]string
Body interface{}
Timeout time.Duration
Retry int
RetryDelay time.Duration
}
// Response
type Response struct {
Status int
Headers http.Header
Body []byte
// Helper methods
func (r *Response) JSON(v interface{}) error
func (r *Response) String() string
}
Logger API
logger Package
// Create logger
func New(name string) *Logger
// Log levels
func (l *Logger) Debug(msg string, args ...interface{})
func (l *Logger) Info(msg string, args ...interface{})
func (l *Logger) Warn(msg string, args ...interface{})
func (l *Logger) Error(msg string, args ...interface{})
func (l *Logger) Fatal(msg string, args ...interface{})
// Structured logging
func (l *Logger) WithFields(fields Fields) *Entry
type Fields map[string]interface{}
// Logger entry
type Entry struct {
func (e *Entry) Debug(msg string)
func (e *Entry) Info(msg string)
func (e *Entry) Warn(msg string)
func (e *Entry) Error(msg string)
func (e *Entry) WithField(key string, value interface{}) *Entry
}
// Configuration
func SetLevel(level Level)
func SetOutput(output io.Writer)
func SetFormatter(formatter Formatter)
Configuration API
config Package
// Load configuration
func Load() (*Config, error)
func LoadFrom(path string) (*Config, error)
// Validate
func Validate(cfg *Config) error
// Configuration structure
type Config struct {
Server ServerConfig
Database DatabaseConfig
Cache CacheConfig
Logging LoggingConfig
Templates TemplatesConfig
Static StaticConfig
API APIConfig
CORS CORSConfig
Session SessionConfig
OAuth OAuthConfig
}
// Server configuration
type ServerConfig struct {
Port int
Host string
Debug bool
ReadTimeout int
WriteTimeout int
}
// Database configuration
type DatabaseConfig struct {
Driver string
Host string
Port int
Name string
User string
Password string
SSLMode string
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime int
}
Cache API
cache Package
// Create cache
func New(driver string) Cache
// Cache interface
type Cache interface {
Get(key string) (interface{}, bool)
Set(key string, value interface{}, ttl time.Duration) error
Delete(key string) error
Clear() error
Has(key string) bool
}
// Memory cache
func NewMemoryCache() *MemoryCache
// Redis cache
func NewRedisCache(addr string, password string, db int) *RedisCache
Template Functions
Available Template Functions
// String functions
{{upper .text}} // Convert to uppercase
{{lower .text}} // Convert to lowercase
{{title .text}} // Title case
{{truncate .text 100}} // Truncate to 100 chars
{{trim .text}} // Trim whitespace
// Date functions
{{formatDate .date "2006-01-02"}} // Format date
{{now}} // Current time
{{dateAdd .date "24h"}} // Add duration to date
// Array functions
{{len .array}} // Array length
{{join .array ", "}} // Join array elements
{{contains .array "item"}} // Check if contains
{{first .array}} // First element
{{last .array}} // Last element
// Math functions
{{add 1 2}} // Addition
{{sub 5 3}} // Subtraction
{{mul 2 3}} // Multiplication
{{div 10 2}} // Division
{{mod 10 3}} // Modulo
// Comparison
{{eq .a .b}} // Equal
{{ne .a .b}} // Not equal
{{lt .a .b}} // Less than
{{le .a .b}} // Less than or equal
{{gt .a .b}} // Greater than
{{ge .a .b}} // Greater than or equal
// URL functions
{{urlEncode .query}} // URL encode
{{urlDecode .query}} // URL decode
// JSON
{{toJSON .data}} // Convert to JSON
{{fromJSON .json}} // Parse JSON
// Utilities
{{default "default" .value}} // Default value if empty
{{safe .html}} // Mark as safe HTML
{{dict "key1" "val1" "key2" "val2"}} // Create dictionary
Model API
News Model
type News struct {
ID int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
Excerpt string `json:"excerpt"`
Category string `json:"category"`
Author string `json:"author"`
ImageURL string `json:"image_url"`
PublishedAt time.Time `json:"published_at"`
Tags []string `json:"tags"`
}
// Fetch news
func FetchNews(category string, page int) ([]News, error)
func FetchNewsById(id string) (*News, error)
func FetchNewsByCategory(category string) ([]News, error)
Football Model
type Football struct {
ID int `json:"id"`
Title string `json:"title"`
Slug string `json:"slug"`
League string `json:"league"`
HomeTeam string `json:"home_team"`
AwayTeam string `json:"away_team"`
Score string `json:"score"`
Date time.Time `json:"date"`
}
func FetchFootballData() ([]Football, error)
func FetchFootballBySlug(slug string) (*Football, error)
Category Model
type Category struct {
ID int `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Description string `json:"description"`
Count int `json:"count"`
}
func GetCategories() ([]Category, error)
func GetCategoryBySlug(slug string) (*Category, error)
Middleware API
Built-in Middleware
// Logger middleware
func LoggerMiddleware() MiddlewareFunc
// Recovery middleware (panic recovery)
func RecoveryMiddleware() MiddlewareFunc
// CORS middleware
func CORSMiddleware(config CORSConfig) MiddlewareFunc
// Rate limiting
func RateLimitMiddleware(rate int, window time.Duration) MiddlewareFunc
// Authentication
func AuthMiddleware(secret string) MiddlewareFunc
// Compression
func GzipMiddleware() MiddlewareFunc
// Custom middleware type
type MiddlewareFunc func(HandlerFunc) HandlerFunc
// Example custom middleware
func CustomMiddleware(next HandlerFunc) HandlerFunc {
return func(ctx *Context) {
// Before request
next(ctx)
// After request
}
}
Utility Functions
util Package
// String utilities
func GenerateID() string
func RandomString(length int) string
func Slugify(text string) string
func TruncateText(text string, length int) string
// Hash utilities
func MD5Hash(text string) string
func SHA256Hash(text string) string
// Validation
func IsEmail(email string) bool
func IsURL(url string) bool
func IsNumeric(s string) bool
// Conversion
func ToString(value interface{}) string
func ToInt(value interface{}) (int, error)
func ToBool(value interface{}) bool
// JSON utilities
func ToJSON(v interface{}) (string, error)
func FromJSON(data string, v interface{}) error
func PrettyJSON(v interface{}) (string, error)
Frontend API (Preact)
Component Structure
import { h } from 'preact';
import { useState, useEffect } from 'preact/hooks';
export default function Component(props) {
const [state, setState] = useState(initialValue);
useEffect(() => {
// Side effects
return () => {
// Cleanup
};
}, [dependencies]);
return (
<div>
{/* JSX content */}
</div>
);
}
Hooks
// State hook
const [value, setValue] = useState(initialValue);
// Effect hook
useEffect(() => { /* effect */ }, [deps]);
// Ref hook
const ref = useRef(initialValue);
// Context hook
const value = useContext(Context);
// Reducer hook
const [state, dispatch] = useReducer(reducer, initialState);
// Memo hook
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
// Callback hook
const memoizedCallback = useCallback(() => { /* callback */ }, [deps]);
API Service
// service/api.ts
export class APIService {
async get(url: string): Promise<any>
async post(url: string, data: any): Promise<any>
async put(url: string, data: any): Promise<any>
async delete(url: string): Promise<any>
}
// Usage
import { api } from './service/api';
const data = await api.get('/api/news');
const result = await api.post('/api/submit', formData);
Build System API
Build Configuration
// frontend/build/const.js
module.exports = {
// Source directory
srcDir: 'src',
// Output directory
outDir: '../webroot/static',
// Entry points
entries: {
'main': 'src/main.tsx',
'news': 'src/pages/news.tsx',
},
// Build options
minify: true,
sourcemap: false,
target: 'es2015',
};
Build Commands
// package.json scripts
{
"dev": "node build/dev.js",
"build": "node build/build.js",
"watch": "node build/dev.js --watch",
"clean": "node build/clean.js"
}
Error Types
HTTP Errors
type HTTPError struct {
Code int
Message string
Details map[string]interface{}
}
// Common errors
var (
ErrNotFound = &HTTPError{404, "Not Found", nil}
ErrBadRequest = &HTTPError{400, "Bad Request", nil}
ErrUnauthorized = &HTTPError{401, "Unauthorized", nil}
ErrForbidden = &HTTPError{403, "Forbidden", nil}
ErrInternalServer = &HTTPError{500, "Internal Server Error", nil}
)
Constants
HTTP Methods
const (
MethodGet = "GET"
MethodPost = "POST"
MethodPut = "PUT"
MethodDelete = "DELETE"
MethodPatch = "PATCH"
MethodOptions = "OPTIONS"
)
Content Types
const (
MIMEApplicationJSON = "application/json"
MIMEApplicationXML = "application/xml"
MIMETextHTML = "text/html"
MIMETextPlain = "text/plain"
MIMEMultipartForm = "multipart/form-data"
MIMEApplicationForm = "application/x-www-form-urlencoded"
)