Code Examples
Learn go-wolf through practical examples. From simple Hello World to complex real-time applications, these examples will get you up and running quickly.
Perfect For Any Use Case
go-wolf is versatile enough to handle various types of applications and services.
REST APIs
Build scalable REST APIs with validation, authentication, and error handling.
Web Applications
Create full-stack web applications with template rendering and static file serving.
Microservices
Develop lightweight microservices with high performance and minimal overhead.
Secure APIs
Implement secure APIs with JWT authentication, CORS, and rate limiting.
Real-time Apps
Build real-time applications with WebSocket support and event broadcasting.
File Processing
Handle file uploads, processing, and serving with built-in middleware.
Hello World
Simple HTTP server with JSON response
Key Features:
- Simple server setup
- JSON response handling
- Route definition
package main
import (
"github.com/aliwert/go-wolf"
)
func main() {
app := wolf.New()
app.Get("/", func(c *wolf.Context) error {
return c.JSON(200, wolf.Map{
"message": "Hello, World!",
"framework": "go-wolf",
})
})
app.Listen(":3000")
}
CRUD API
Complete REST API with CRUD operations and validation
Key Features:
- Complete CRUD operations
- Request validation
- Error handling
- Route grouping
package main
import (
"strconv"
"github.com/aliwert/go-wolf"
)
type User struct {
ID int `json:"id" validate:"required"`
Name string `json:"name" validate:"required,min=2,max=50"`
Email string `json:"email" validate:"required,email"`
}
var users = []User{
{ID: 1, Name: "John Doe", Email: "john@example.com"},
{ID: 2, Name: "Jane Smith", Email: "jane@example.com"},
}
func main() {
app := wolf.New()
// Middleware
app.Use(wolf.Logger())
app.Use(wolf.Recovery())
app.Use(wolf.CORS())
// Routes
api := app.Group("/api/v1")
{
api.Get("/users", getUsers)
api.Get("/users/:id", getUser)
api.Post("/users", createUser)
api.Put("/users/:id", updateUser)
api.Delete("/users/:id", deleteUser)
}
app.Listen(":3000")
}
func getUsers(c *wolf.Context) error {
return c.JSON(200, wolf.Map{"users": users})
}
func getUser(c *wolf.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
for _, user := range users {
if user.ID == id {
return c.JSON(200, user)
}
}
return wolf.NewHTTPError(404, "User not found")
}
func createUser(c *wolf.Context) error {
var user User
if err := c.BindJSON(&user); err != nil {
return c.JSON(400, wolf.Map{"error": "Invalid JSON"})
}
if err := c.Validate(&user); err != nil {
return c.JSON(400, wolf.Map{"error": err.Error()})
}
user.ID = len(users) + 1
users = append(users, user)
return c.JSON(201, user)
}
JWT Authentication
JWT-based authentication with protected routes
Key Features:
- JWT token generation
- Protected routes
- Middleware authentication
- User session management
package main
import (
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/aliwert/go-wolf"
)
type Claims struct {
UserID int `json:"user_id"`
Email string `json:"email"`
jwt.RegisteredClaims
}
var jwtSecret = []byte("your-secret-key")
func main() {
app := wolf.New()
// Public routes
app.Post("/login", login)
app.Post("/register", register)
// Protected routes
protected := app.Group("/api")
protected.Use(AuthMiddleware())
{
protected.Get("/profile", getProfile)
protected.Put("/profile", updateProfile)
protected.Get("/dashboard", getDashboard)
}
app.Listen(":3000")
}
func AuthMiddleware() wolf.HandlerFunc {
return func(c *wolf.Context) error {
authHeader := c.Header("Authorization")
if authHeader == "" {
return c.JSON(401, wolf.Map{"error": "Authorization header required"})
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
return c.JSON(401, wolf.Map{"error": "Bearer token required"})
}
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil || !token.Valid {
return c.JSON(401, wolf.Map{"error": "Invalid token"})
}
claims := token.Claims.(*Claims)
c.Set("user_id", claims.UserID)
c.Set("user_email", claims.Email)
return c.Next()
}
}
func login(c *wolf.Context) error {
var loginReq struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=6"`
}
if err := c.BindJSON(&loginReq); err != nil {
return c.JSON(400, wolf.Map{"error": "Invalid request"})
}
if err := c.Validate(&loginReq); err != nil {
return c.JSON(400, wolf.Map{"error": err.Error()})
}
// Validate credentials (implement your own logic)
user, err := validateCredentials(loginReq.Email, loginReq.Password)
if err != nil {
return c.JSON(401, wolf.Map{"error": "Invalid credentials"})
}
// Create JWT token
claims := &Claims{
UserID: user.ID,
Email: user.Email,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtSecret)
if err != nil {
return c.JSON(500, wolf.Map{"error": "Failed to generate token"})
}
return c.JSON(200, wolf.Map{
"token": tokenString,
"user": user,
})
}
File Upload
Single and multiple file upload with validation
Key Features:
- Single & multiple file upload
- File type validation
- Static file serving
- Unique filename generation
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/aliwert/go-wolf"
)
func main() {
app := wolf.New()
app.Use(wolf.Logger())
app.Use(wolf.Recovery())
// File upload routes
app.Post("/upload", uploadFile)
app.Post("/upload/multiple", uploadMultipleFiles)
app.Get("/files/:filename", serveFile)
// Static file serving
app.Static("/static", "./uploads")
app.Listen(":3000")
}
func uploadFile(c *wolf.Context) error {
// Parse multipart form (32MB max)
if err := c.Request().ParseMultipartForm(32 << 20); err != nil {
return c.JSON(400, wolf.Map{"error": "Failed to parse form"})
}
file, header, err := c.Request().FormFile("file")
if err != nil {
return c.JSON(400, wolf.Map{"error": "No file provided"})
}
defer file.Close()
// Validate file type
if !isAllowedFileType(header.Filename) {
return c.JSON(400, wolf.Map{"error": "File type not allowed"})
}
// Create uploads directory if it doesn't exist
if err := os.MkdirAll("./uploads", 0755); err != nil {
return c.JSON(500, wolf.Map{"error": "Failed to create upload directory"})
}
// Create destination file
filename := generateUniqueFilename(header.Filename)
dst, err := os.Create(filepath.Join("./uploads", filename))
if err != nil {
return c.JSON(500, wolf.Map{"error": "Failed to create file"})
}
defer dst.Close()
// Copy file content
if _, err := io.Copy(dst, file); err != nil {
return c.JSON(500, wolf.Map{"error": "Failed to save file"})
}
return c.JSON(200, wolf.Map{
"message": "File uploaded successfully",
"filename": filename,
"size": header.Size,
"url": fmt.Sprintf("/static/%s", filename),
})
}
func uploadMultipleFiles(c *wolf.Context) error {
if err := c.Request().ParseMultipartForm(32 << 20); err != nil {
return c.JSON(400, wolf.Map{"error": "Failed to parse form"})
}
files := c.Request().MultipartForm.File["files"]
if len(files) == 0 {
return c.JSON(400, wolf.Map{"error": "No files provided"})
}
var uploadedFiles []wolf.Map
for _, fileHeader := range files {
file, err := fileHeader.Open()
if err != nil {
continue
}
if !isAllowedFileType(fileHeader.Filename) {
file.Close()
continue
}
filename := generateUniqueFilename(fileHeader.Filename)
dst, err := os.Create(filepath.Join("./uploads", filename))
if err != nil {
file.Close()
continue
}
io.Copy(dst, file)
file.Close()
dst.Close()
uploadedFiles = append(uploadedFiles, wolf.Map{
"filename": filename,
"size": fileHeader.Size,
"url": fmt.Sprintf("/static/%s", filename),
})
}
return c.JSON(200, wolf.Map{
"message": "Files uploaded successfully",
"files": uploadedFiles,
"count": len(uploadedFiles),
})
}
WebSocket Chat
Real-time WebSocket server with broadcasting
Key Features:
- WebSocket connections
- Message broadcasting
- Client management
- REST API integration
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
"github.com/aliwert/go-wolf"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // Allow connections from any origin
},
}
type Hub struct {
clients map[*Client]bool
broadcast chan []byte
register chan *Client
unregister chan *Client
}
type Client struct {
hub *Hub
conn *websocket.Conn
send chan []byte
}
func main() {
app := wolf.New()
app.Use(wolf.Logger())
app.Use(wolf.Recovery())
app.Use(wolf.CORS())
// Create WebSocket hub
hub := &Hub{
clients: make(map[*Client]bool),
broadcast: make(chan []byte),
register: make(chan *Client),
unregister: make(chan *Client),
}
go hub.run()
// WebSocket endpoint
app.Get("/ws", func(c *wolf.Context) error {
return handleWebSocket(hub, c)
})
// REST API for sending messages
app.Post("/api/broadcast", func(c *wolf.Context) error {
var msg struct {
Message string `json:"message"`
}
if err := c.BindJSON(&msg); err != nil {
return c.JSON(400, wolf.Map{"error": "Invalid JSON"})
}
hub.broadcast <- []byte(msg.Message)
return c.JSON(200, wolf.Map{"message": "Message broadcasted"})
})
// Serve static files for WebSocket client
app.Static("/", "./public")
app.Listen(":3000")
}
func (h *Hub) run() {
for {
select {
case client := <-h.register:
h.clients[client] = true
log.Println("Client connected")
case client := <-h.unregister:
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.send)
log.Println("Client disconnected")
}
case message := <-h.broadcast:
for client := range h.clients {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
}
}
}
func handleWebSocket(hub *Hub, c *wolf.Context) error {
conn, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
if err != nil {
return err
}
client := &Client{
hub: hub,
conn: conn,
send: make(chan []byte, 256),
}
client.hub.register <- client
go client.writePump()
go client.readPump()
return nil
}