fiber

package
v0.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2025 License: MIT Imports: 28 Imported by: 1

README

SimpleHTTP

SimpleHTTP is a flexible HTTP handler interface for Go that provides a unified abstraction layer for multiple web frameworks. It allows you to write web applications that can seamlessly switch between different web framework implementations (Fiber, Echo, Gin, etc.) without changing your application code.

Features

  • Framework Agnostic: Write your code once and switch between different web frameworks
  • Consistent Interface: Unified API for handling HTTP requests and responses
  • Middleware Support: Rich collection of built-in middleware for common web application needs
  • Extensible: Easy to add support for additional web frameworks
  • Configurable: Simple configuration through environment variables
  • WebSocket Support: Standardized API for WebSocket connections

Installation

go get github.com/medatechnology/simplehttp

Quick Start

package main

import (
	"log"
	"net/http"

	"github.com/medatechnology/simplehttp"
	"github.com/medatechnology/simplehttp/framework/fiber" // Import implementation of your choice
)

func main() {
	// Load configuration from environment variables
	config := simplehttp.LoadConfig()
	
	// Create server with Fiber implementation
	server := fiber.NewServer(config)
	
	// Add middleware
	server.Use(
		simplehttp.MiddlewareRequestID(),
		simplehttp.MiddlewareLogger(simplehttp.NewDefaultLogger()),
	)
	
	// Define routes
	server.GET("/hello", func(c simplehttp.Context) error {
		return c.JSON(http.StatusOK, map[string]string{
			"message": "Hello, World!",
		})
	})
	
	// Start server
	if err := server.Start(""); err != nil {
		log.Fatal(err)
	}
}

Configuration

SimpleHTTP can be configured through environment variables:

Variable Description Default
SIMPLEHTTP_FRAMEWORK The web framework to use (e.g., "fiber", "echo") "echo"
SIMPLEHTTP_PORT The port to listen on "8080"
SIMPLEHTTP_APP_NAME Application name "MedaHTTP"
SIMPLEHTTP_HOST_NAME Hostname to bind to "localhost"
SIMPLEHTTP_READ_TIMEOUT Read timeout in seconds 30s
SIMPLEHTTP_WRITE_TIMEOUT Write timeout in seconds 30s
SIMPLEHTTP_IDLE_TIMEOUT Idle timeout in seconds 60s
SIMPLEHTTP_DEBUG Enable debug mode false
SIMPLEHTTP_FRAMEWORK_STARTUP_MESSAGE Show startup message true

Core Components

MedaContext

MedaContext provides a unified interface for handling HTTP requests and responses:

// Get request information
path := c.GetPath()
method := c.GetMethod()
header := c.GetHeader("Content-Type")
headers := c.GetHeaders() // Get all parsed headers
queryParam := c.GetQueryParam("filter")
body := c.GetBody()

// Set headers
c.SetHeader("X-Custom-Header", "value")
c.SetRequestHeader("Authorization", "Bearer token")
c.SetResponseHeader("Cache-Control", "no-cache")

// Response methods
c.JSON(http.StatusOK, data)
c.String(http.StatusOK, "Hello World")
c.Stream(http.StatusOK, "text/plain", reader)

// File handling
file, err := c.GetFile("upload")
c.SaveFile(file, "/path/to/save")
c.SendFile("/path/to/file", true) // Download as attachment

// Context values
c.Set("user", user)
user := c.Get("user")

// Data binding
var user User
c.BindJSON(&user)
c.BindForm(&user)
MedaRouter

MedaRouter provides routing capabilities:

// HTTP methods
server.GET("/users", listUsers)
server.POST("/users", createUser)
server.PUT("/users/:id", updateUser)
server.DELETE("/users/:id", deleteUser)

// Route groups
api := server.Group("/api")
{
    api.GET("/status", getStatus)
    
    // Nested groups
    users := api.Group("/users")
    {
        users.GET("", listUsers)
        users.POST("", createUser)
    }
}

// Static file serving
server.Static("/assets", "./public")
server.StaticFile("/favicon.ico", "./public/favicon.ico")

// Websockets
server.WebSocket("/ws", handleWebSocket)
Middleware

MedaHTTP includes a variety of built-in middleware:

// Basic middleware
server.Use(
    simplehttp.MiddlewareRequestID(),
    simplehttp.MiddlewareLogger(logger),
    simplehttp.MiddlewareHeaderParser(),
)

// Rate limiting
server.Use(simplehttp.MiddlewareRateLimiter(simplehttp.RateLimitConfig{
    RequestsPerSecond: 10,
    BurstSize: 20,
    KeyFunc: func(c simplehttp.Context) string {
        headers := c.GetHeaders()
        return headers.RealIP // Rate limit by IP
    },
}))

// Security middleware
server.Use(simplehttp.MiddlewareSecurity(simplehttp.SecurityConfig{
    FrameDeny: true,
    ContentTypeNosniff: true,
    BrowserXssFilter: true,
}))

// CORS middleware
server.Use(simplehttp.MiddlewareCORS(&simplehttp.CORSConfig{
    AllowOrigins: []string{"*"},
    AllowMethods: []string{"GET", "POST", "PUT", "DELETE"},
    AllowHeaders: []string{"Origin", "Content-Type"},
}))

// Timeout middleware
server.Use(simplehttp.MiddlewareTimeout(simplehttp.TimeOutConfig{
    ReadTimeout: 30 * time.Second,
    WriteTimeout: 30 * time.Second,
    IdleTimeout: 60 * time.Second,
}))

// Basic Auth middleware
server.Use(simplehttp.MiddlewareBasicAuth("username", "password"))

// Cache middleware
server.Use(simplehttp.MiddlewareCache(simplehttp.CacheConfig{
    TTL: 5 * time.Minute,
    Store: simplehttp.NewMemoryCache(),
    KeyFunc: func(c simplehttp.Context) string {
        return c.GetPath() + c.GetHeader("Authorization")
    },
}))

Advanced Usage

File Handling
// Create a file handler
fileHandler := simplehttp.NewFileHandler("./uploads")
fileHandler.MaxFileSize = 50 << 20 // 50MB
fileHandler.AllowedTypes = []string{
    "image/jpeg",
    "image/png",
    "application/pdf",
}

// Register file routes
server.POST("/upload", fileHandler.HandleUpload())
server.GET("/files/:filename", fileHandler.HandleDownload("./uploads/{{filename}}"))
WebSockets
type Message struct {
    Type string `json:"type"`
    Data string `json:"data"`
}

server.WebSocket("/ws/chat", func(ws simplehttp.WebSocket) error {
    for {
        msg := &Message{}
        if err := ws.ReadJSON(msg); err != nil {
            return err
        }
        
        // Echo the message back
        response := &Message{
            Type: "response",
            Data: msg.Data,
        }
        
        if err := ws.WriteJSON(response); err != nil {
            return err
        }
    }
})
Graceful Shutdown
// Start server in a goroutine
go func() {
    if err := server.Start(""); err != nil {
        log.Printf("server error: %v", err)
    }
}()

// Wait for interrupt signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit

// Gracefully shutdown
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

if err := server.Shutdown(ctx); err != nil {
    log.Fatal(err)
}

Framework Implementations

SimpleHTTP currently includes the following framework implementations:

  • Fiber (github.com/medatechnology/simplehttp/framework/fiber)

License

MIT License

Documentation

Overview

framework/fiber/adapter.go

framework/fiber/context.go

framework/fiber/middleware.go

framework/fiber/server.go

Index

Constants

View Source
const (
	HEADER_PARSED_KEY = "simplehttp.header"
)

Variables

This section is empty.

Functions

func Adapter

func Adapter(handler simplehttp.HandlerFunc) fiber.Handler

Adapter converts SimpleHttpHandlerFunc to fiber.Handler

func MiddlewareAdapter

func MiddlewareAdapter(middleware simplehttp.MiddlewareFunc) fiber.Handler

MiddlewareAdapter converts SimpleHttpMiddleware to fiber middleware

func MiddlewareBasicAuth

func MiddlewareBasicAuth(username, password string) simplehttp.Middleware

MiddlewareBasicAuth returns Fiber's basic auth middleware

func MiddlewareCORS

func MiddlewareCORS(config *simplehttp.CORSConfig) simplehttp.Middleware

Example of another middleware following the same pattern

func MiddlewareCSRF

func MiddlewareCSRF() simplehttp.Middleware

MiddlewareCSRF returns Fiber's CSRF middleware

func MiddlewareCache

func MiddlewareCache(config simplehttp.CacheConfig) simplehttp.Middleware

MiddlewareCache returns Fiber's cache middleware

func MiddlewareCompress

func MiddlewareCompress(config simplehttp.CompressionConfig) simplehttp.Middleware

MiddlewareCompress returns Fiber's compression middleware

func MiddlewareETag

func MiddlewareETag() simplehttp.Middleware

MiddlewareETag returns Fiber's ETag middleware

func MiddlewareLogger

func MiddlewareLogger(log simplehttp.Logger) simplehttp.Middleware

MiddlewareLogger returns Fiber's logger middleware

func MiddlewareMonitor

func MiddlewareMonitor() simplehttp.Middleware

MiddlewareMonitor returns Fiber's monitor middleware

func MiddlewareRateLimiter

func MiddlewareRateLimiter(config simplehttp.RateLimitConfig) simplehttp.Middleware

MiddlewareRateLimiter returns Fiber's rate limiter middleware

func MiddlewareRecover

func MiddlewareRecover() simplehttp.Middleware

MiddlewareRecover returns Fiber's recover middleware

func MiddlewareRequestID

func MiddlewareRequestID() simplehttp.Middleware

RequestID middleware as an example., TODO: Check and test this, last time it wasn't working!

func MiddlewareSecurity

func MiddlewareSecurity(config simplehttp.SecurityConfig) simplehttp.Middleware

MiddlewareSecurity returns Fiber's security middleware (Helmet)

Types

type FiberContext

type FiberContext struct {
	// contains filtered or unexported fields
}

func NewContext

func NewContext(c *fiber.Ctx) *FiberContext

func (*FiberContext) Bind

func (c *FiberContext) Bind(v interface{}) error

func (*FiberContext) BindForm

func (c *FiberContext) BindForm(v interface{}) error

func (*FiberContext) BindJSON

func (c *FiberContext) BindJSON(v interface{}) error

func (*FiberContext) Context

func (c *FiberContext) Context() context.Context

Context handling

func (*FiberContext) Get

func (c *FiberContext) Get(key string) interface{}

func (*FiberContext) GetBody

func (c *FiberContext) GetBody() []byte

func (*FiberContext) GetFile

func (c *FiberContext) GetFile(fieldName string) (*multipart.FileHeader, error)

File handling

func (*FiberContext) GetHeader

func (c *FiberContext) GetHeader(key string) string

func (*FiberContext) GetHeaders

func (c *FiberContext) GetHeaders() *simplehttp.RequestHeader

func (*FiberContext) GetMethod

func (c *FiberContext) GetMethod() string

func (*FiberContext) GetPath

func (c *FiberContext) GetPath() string

Path and method accessors

func (*FiberContext) GetQueryParam

func (c *FiberContext) GetQueryParam(key string) string

Query parameter handling

func (*FiberContext) GetQueryParams

func (c *FiberContext) GetQueryParams() map[string][]string

func (*FiberContext) JSON

func (c *FiberContext) JSON(code int, data interface{}) error

Response methods

func (*FiberContext) Request

func (c *FiberContext) Request() *http.Request

Standard http.Request and http.ResponseWriter implementation

func (*FiberContext) Response

func (c *FiberContext) Response() http.ResponseWriter

func (*FiberContext) SSE added in v0.0.8

func (c *FiberContext) SSE(handler simplehttp.SSEHandler) error

SSE starts a Server-Sent Events stream

func (*FiberContext) SaveFile

func (c *FiberContext) SaveFile(file *multipart.FileHeader, dst string) error

func (*FiberContext) SendFile

func (c *FiberContext) SendFile(filepath string, attachment bool) error

func (*FiberContext) Set

func (c *FiberContext) Set(key string, value interface{})

func (*FiberContext) SetContext

func (c *FiberContext) SetContext(ctx context.Context)

func (*FiberContext) SetHeader

func (c *FiberContext) SetHeader(key, value string)

func (*FiberContext) SetRequestHeader

func (c *FiberContext) SetRequestHeader(key, value string)

Header manipulation methods

func (*FiberContext) SetResponseHeader

func (c *FiberContext) SetResponseHeader(key, value string)

func (*FiberContext) Stream

func (c *FiberContext) Stream(code int, contentType string, reader io.Reader) error

func (*FiberContext) String

func (c *FiberContext) String(code int, data string) error

func (*FiberContext) Upgrade

func (c *FiberContext) Upgrade() (simplehttp.Websocket, error)

WebSocket handling

type FiberWebSocket

type FiberWebSocket struct {
	// contains filtered or unexported fields
}

WebSocket implementation

func NewFiberWebSocket

func NewFiberWebSocket(c *websocket.Conn) *FiberWebSocket

func (*FiberWebSocket) Close

func (ws *FiberWebSocket) Close() error

func (*FiberWebSocket) ReadJSON

func (ws *FiberWebSocket) ReadJSON(v interface{}) error

func (*FiberWebSocket) ReadMessage

func (ws *FiberWebSocket) ReadMessage() (messageType int, p []byte, err error)

func (*FiberWebSocket) WriteJSON

func (ws *FiberWebSocket) WriteJSON(v interface{}) error

func (*FiberWebSocket) WriteMessage

func (ws *FiberWebSocket) WriteMessage(messageType int, data []byte) error

type RouterGroup

type RouterGroup struct {
	// contains filtered or unexported fields
}

RouterGroup implements group routing

func (*RouterGroup) DELETE

func (g *RouterGroup) DELETE(path string, handler simplehttp.HandlerFunc)

func (*RouterGroup) GET

func (g *RouterGroup) GET(path string, handler simplehttp.HandlerFunc)

func (*RouterGroup) Group

func (g *RouterGroup) Group(prefix string) simplehttp.Router

func (*RouterGroup) HEAD

func (g *RouterGroup) HEAD(path string, handler simplehttp.HandlerFunc)

func (*RouterGroup) OPTIONS

func (g *RouterGroup) OPTIONS(path string, handler simplehttp.HandlerFunc)

func (*RouterGroup) PATCH

func (g *RouterGroup) PATCH(path string, handler simplehttp.HandlerFunc)

func (*RouterGroup) POST

func (g *RouterGroup) POST(path string, handler simplehttp.HandlerFunc)

func (*RouterGroup) PUT

func (g *RouterGroup) PUT(path string, handler simplehttp.HandlerFunc)

func (*RouterGroup) Static

func (g *RouterGroup) Static(prefix, root string)

func (*RouterGroup) StaticFile

func (g *RouterGroup) StaticFile(path, filepath string)

func (*RouterGroup) Use

func (g *RouterGroup) Use(middleware ...simplehttp.Middleware)

func (*RouterGroup) WebSocket

func (g *RouterGroup) WebSocket(path string, handler func(simplehttp.Websocket) error)

type Server

type Server struct {
	// contains filtered or unexported fields
}

func NewServer

func NewServer(config *simplehttp.Config) *Server

func (*Server) DELETE

func (s *Server) DELETE(path string, handler simplehttp.HandlerFunc)

func (*Server) GET

func (s *Server) GET(path string, handler simplehttp.HandlerFunc)

func (*Server) Group

func (s *Server) Group(prefix string) simplehttp.Router

func (*Server) HEAD

func (s *Server) HEAD(path string, handler simplehttp.HandlerFunc)

func (*Server) OPTIONS

func (s *Server) OPTIONS(path string, handler simplehttp.HandlerFunc)

func (*Server) PATCH

func (s *Server) PATCH(path string, handler simplehttp.HandlerFunc)

func (*Server) POST

func (s *Server) POST(path string, handler simplehttp.HandlerFunc)

func (*Server) PUT

func (s *Server) PUT(path string, handler simplehttp.HandlerFunc)

func (*Server) PrintMiddleware

func (s *Server) PrintMiddleware(verbose bool)

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

func (*Server) Start

func (s *Server) Start(address string) error

Usually this is framework.Listen() function TODO: use config.Debug to print out or if not silence / minimal

func (*Server) Static

func (s *Server) Static(prefix, root string)

func (*Server) StaticFile

func (s *Server) StaticFile(path, filepath string)

func (*Server) Use

func (s *Server) Use(middleware ...simplehttp.Middleware)

func (*Server) WebSocket

func (s *Server) WebSocket(path string, handler func(simplehttp.Websocket) error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL