Skip to content

Bakemono-san/gofsen

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Gofsen - HTTP Framework for Go

Go Version GitHub release Go Report Card License GoDoc

Gofsen is a lightweight, Express.js-inspired HTTP framework for Go. Simple, fast, and powerful.


πŸ“¦ Installation

go get github.com/Bakemono-san/gofsen

CLI (gofsen-cli) Installation

You can install the CLI in multiple ways:

  • Using go install (latest from main):
go install github.com/Bakemono-san/gofsen/cmd/gofsen-cli@latest
  • Using Homebrew (macOS/Linux):
brew tap Bakemono-san/homebrew-tap
brew install gofsen-cli
  • Linux via APT (Cloudsmith hosted repo):
# Add the APT repository (Ubuntu/Debian)
curl -1sLf 'https://dl.cloudsmith.io/public/bakemono-san/gofsen/setup.deb.sh' | sudo -E bash

# Install
sudo apt update
sudo apt install gofsen-cli
  • RHEL/CentOS/Alma/Rocky via YUM/DNF (Cloudsmith hosted repo):
# Add the YUM/DNF repository
curl -1sLf 'https://dl.cloudsmith.io/public/bakemono-san/gofsen/setup.rpm.sh' | sudo -E bash

# Install
sudo dnf install gofsen-cli
# or: sudo yum install gofsen-cli
  • Download prebuilt binaries (Windows/macOS/Linux) from the Releases page.

Verify installation:

gofsen-cli --version

CLI quickstart:

# Create a new project (interactive)
gofsen-cli new

# Generate CRUD routes for a resource
gofsen-cli gen route users

# Generate a middleware
gofsen-cli gen middleware auth

# Generate a simple handler
gofsen-cli gen handler status

Tip:

  • Homebrew upgrade later: brew update && brew upgrade gofsen-cli
  • If APT says it can't find the package, ensure you added the repo (lowercase URL) and ran sudo apt update.

πŸš€ Quick Start

package main

import "github.com/Bakemono-san/gofsen"

func main() {
    app := gofsen.New()
    
    app.GET("/", func(c *gofsen.Context) {
        c.JSON(map[string]string{
            "message": "Hello Gofsen!",
            "version": gofsen.Version,
        })
    })
    
    app.Listen("8080")
}

✨ Features

βœ… HTTP Routing

  • HTTP Methods: GET, POST, PUT, DELETE, PATCH
  • Route Parameters: /users/:id
  • Route Groups: /api/v1
  • Query Parameters: ?name=value

βœ… Middleware System

  • Logger: Automatic request logging
  • Recovery: Panic recovery
  • CORS: Complete CORS support with configuration
  • Custom Middleware: Create your own middlewares

βœ… Request/Response Helpers

  • JSON: Automatic parsing and sending
  • Query Params: Easy access to parameters
  • Route Params: Dynamic parameter support
  • Error Handling: Built-in error management

πŸ’‘ Examples

Basic Server

package main

import "github.com/Bakemono-san/gofsen"

func main() {
    app := gofsen.New()
    
    // Middlewares
    app.Use(gofsen.Logger())
    app.Use(gofsen.Recovery())
    app.Use(gofsen.CORS())
    
    // Routes
    app.GET("/health", func(c *gofsen.Context) {
        c.JSON(map[string]string{"status": "OK"})
    })
    
    app.Listen("8080")
}

REST API

package main

import "github.com/Bakemono-san/gofsen"

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

func main() {
    app := gofsen.New()
    app.Use(gofsen.Logger())
    
    api := app.Group("/api/v1")
    
    // GET /api/v1/users
    api.GET("/users", getUsers)
    
    // GET /api/v1/users/:id
    api.GET("/users/:id", getUser)
    
    // POST /api/v1/users
    api.POST("/users", createUser)
    
    app.Listen("3000")
}

func getUsers(c *gofsen.Context) {
    users := []User{{ID: 1, Name: "Alice"}}
    c.JSON(users)
}

func getUser(c *gofsen.Context) {
    id := c.Param("id")
    c.JSON(map[string]string{"id": id})
}

func createUser(c *gofsen.Context) {
    var user User
    if err := c.BindJSON(&user); err != nil {
        c.Error(400, "Invalid JSON")
        return
    }
    c.Status(201).JSON(user)
}

Custom Middleware

package main

import (
    "log"
    "github.com/Bakemono-san/gofsen"
)

func main() {
    app := gofsen.New()
    
    // Authentication middleware
    authMiddleware := func(c *gofsen.Context) {
        token := c.Request.Header.Get("Authorization")
        if token == "" {
            c.Error(401, "Missing token")
            return
        }
        log.Printf("User authenticated with token: %s", token)
        c.Next() // Important: continue to next handler
    }
    
    // Protected routes
    protected := app.Group("/protected")
    protected.Use(authMiddleware)
    
    protected.GET("/profile", func(c *gofsen.Context) {
        c.JSON(map[string]string{"message": "Protected route"})
    })
    
    app.Listen("3000")
}

πŸ› οΈ API Reference

Router Methods

app := gofsen.New()                    // Create instance
app.Use(middleware)                    // Add global middleware
app.GET(path, handler)                 // GET route
app.POST(path, handler)                // POST route  
app.PUT(path, handler)                 // PUT route
app.DELETE(path, handler)              // DELETE route
app.PATCH(path, handler)               // PATCH route
app.Group(prefix)                      // Create route group
app.Listen(port)                       // Start server
app.PrintRoutes()                      // Print routes

Context Methods

// Request
c.Param("id")                          // Route parameter
c.QueryParam("name")                   // Query parameter
c.BindJSON(&struct{})                  // Parse JSON

// Response
c.JSON(data)                           // JSON response
c.Text("Hello")                        // Text response
c.HTML("<h1>Hello</h1>")              // HTML response
c.Status(200)                          // Status code
c.Error(404, "Not found")             // Error with code

// Middleware
c.Next()                               // Next middleware

Built-in Middlewares

gofsen.Logger()                        // Request logger
gofsen.Recovery()                      // Panic recovery
gofsen.CORS()                          // CORS with defaults
gofsen.CORSFromEnv()                   // CORS from environment variables
gofsen.CORSWithConfig(config)          // CORS with custom config

πŸ”§ CORS Configuration

Manual Configuration

corsConfig := gofsen.CORSConfig{
    AllowOrigins: []string{"http://localhost:3000", "https://myapp.com"},
    AllowMethods: []string{"GET", "POST", "PUT", "DELETE"},
    AllowHeaders: []string{"Content-Type", "Authorization"},
}

app.Use(gofsen.CORSWithConfig(corsConfig))

Environment Variables Configuration

Gofsen supports configuring CORS through environment variables for easier deployment and configuration management:

// Use CORS configured from environment variables
app.Use(gofsen.CORSFromEnv())

Supported Environment Variables:

Variable Description Default Example
CORS_ALLOWED_ORIGINS Allowed origins (comma-separated) * http://localhost:3000,https://myapp.com
ALLOWED_ORIGINS Fallback for allowed origins * https://example.com
CORS_ALLOWED_METHODS Allowed HTTP methods GET,POST,PUT,DELETE,PATCH,OPTIONS GET,POST,PUT
CORS_ALLOWED_HEADERS Allowed headers Content-Type,Authorization Content-Type,X-API-Key

Example .env file:

# CORS Configuration
CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173,https://myapp.com
CORS_ALLOWED_METHODS=GET,POST,PUT,DELETE,PATCH,OPTIONS
CORS_ALLOWED_HEADERS=Content-Type,Authorization,X-Requested-With

Usage in code:

package main

import "github.com/Bakemono-san/gofsen"

func main() {
    app := gofsen.New()
    
    // CORS will automatically read from environment variables
    app.Use(gofsen.CORSFromEnv())
    
    app.GET("/", func(c *gofsen.Context) {
        c.JSON(map[string]string{"message": "CORS configured from env!"})
    })
    
    app.Listen("8080")
}

πŸ“Š Framework Comparison

Framework Import Philosophy
Gofsen github.com/Bakemono-san/gofsen Simple, Express.js-like
Gin github.com/gin-gonic/gin Performance, minimalist
Fiber github.com/gofiber/fiber/v2 Express.js for Go
Echo github.com/labstack/echo/v4 High performance

Migration from Gin

// Gin
r := gin.Default()
r.GET("/users/:id", func(c *gin.Context) {
    id := c.Param("id")
    c.JSON(200, gin.H{"id": id})
})

// Gofsen
app := gofsen.New()
app.GET("/users/:id", func(c *gofsen.Context) {
    id := c.Param("id")
    c.JSON(map[string]string{"id": id})
})

πŸ§ͺ Testing

go test ./...

πŸ“ˆ Performance

Gofsen is optimized for excellent performance with a simple API:

  • Fast routing with optimized regex
  • Efficient middleware chain
  • Zero allocation in common cases

🀝 Contributing

Contributions are welcome!

  1. Fork the project
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License. See the LICENSE file for details.

🌟 Why Choose Gofsen?

  • Simple: Intuitive API inspired by Express.js
  • Lightweight: No external dependencies
  • Fast: Optimized performance
  • Flexible: Extensible middleware system
  • Production-ready: Robust error handling

Made with ❀️ by Bakemono

πŸ“š Links

About

A fast, idiomatic API framework for Go, built in Senegal.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages