http

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2025 License: ISC Imports: 10 Imported by: 0

README

http

GitHub Tag Go Reference License Go Report Card Contributors Issues

http is a Go package that provides a collection of utilities and middleware for GoFiber framework. It includes functionalities for content type validation, CSRF protection, error handling, rate limiting, session management, and file uploading.

Features

  • Content Type Middleware: Validate request content types such as JSON, XML, multipart form data, etc.
  • CSRF Protection: Middleware for protecting against Cross-Site Request Forgery attacks.
  • Error Handling: Custom error handling with logging and detailed error responses.
  • Rate Limiting: Middleware for limiting the number of requests a client can make within a specified time period.
  • Session Management: Middleware for managing user sessions with support for cookies and headers.
  • File Uploading: Utilities for handling file uploads, including size and MIME type validation.

Installation

To install the package, run:

go get github.com/go-universal/http

Usage

Error Handling
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/go-universal/http"
)

func main() {
    app := fiber.New(fiber.Config{
        ErrorHandler: http.NewFiberErrorHandler(
            nil,
            func(ctx *fiber.Ctx, err http.HttpError) error {
                return ctx.Status(500).SendString(err.Message)
            },
        ),
    })

    app.Listen(":3000")
}
Session Management
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/go-universal/cache"
    "github.com/go-universal/http/session"
)

func main() {
    app := fiber.New()
    cache := cache.NewMemoryCache()
    app.Use(session.NewMiddleware(cache))

    app.Listen(":3000")
}
CSRF Protection
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/go-universal/cache"
    "github.com/go-universal/http/csrf"
    "github.com/go-universal/http/session"
)

func main() {
    app := fiber.New()
    cache := cache.NewMemoryCache()
    app.Use(session.NewMiddleware(cache))
    app.Use(csrf.NewMiddleware())

    app.Get("/csrf_token", func(c *fiber.Ctx) error{
        return c.JSON(csrf.GetToken(c))
    })

    app.Post("/refresh_csrf", func(c *fiber.Ctx) error{
        newToken, err := csrf.RefreshToken(c)
        if err != nil{
            return err
        }
        return c.JSON(newToken)
    })

    app.Listen(":3000")
}
Rate Limiting
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/go-universal/cache"
    "github.com/go-universal/http/limiter"
)

func main() {
    app := fiber.New()
    cache := cache.NewMemoryCache()
    app.Use(limiter.NewMiddleware(cache))

    app.Listen(":3000")
}
Content Type Middleware
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/go-universal/http/content"
)

func main() {
    app := fiber.New()
    app.Use(content.JsonOnly())

    app.Listen(":3000")
}
File Uploading
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/go-universal/http/uploader"
)

func main() {
    app := fiber.New()

    app.Post("/upload", func(c *fiber.Ctx) error {
        file, err := uploader.NewFiberUploader("./uploads", c, "file")
        if err != nil {
            return err
        }

        if err := file.Save(); err != nil {
            return err
        }

        return c.JSON(fiber.Map{
            "url": file.URL(),
        })
    })

    app.Listen(":3000")
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewError

func NewError(e string, status ...int) error

NewError creates an HttpError with a message and optional status code. Defaults to status 500 if none is provided.

func NewFiberErrorHandler

func NewFiberErrorHandler(l logger.Logger, cb ErrorCallback, codes ...int) fiber.ErrorHandler

NewFiberErrorHandler creates a new Fiber error handler with logging and custom error response capabilities. It takes a logger, an optional error callback, and a list of status codes to log. If the error matches one of the provided status codes, it will be logged using the provided logger. If an error callback is provided, it will be used to handle the error response; otherwise, a default plain text response will be sent. For relative file name in log use os.Setenv("APP_ROOT", "your/project/root") to define your project root.

func NewFormError

func NewFormError(e string, ctx *fiber.Ctx, status ...int) error

NewFormError creates an HttpError with a message, request context, and optional status code. Includes request body data if available.

Types

type ErrorCallback

type ErrorCallback func(ctx *fiber.Ctx, err HttpError) error

ErrorCallback is a function type that handles custom error responses.

type HttpError

type HttpError struct {
	Line    int            // Line number where the error occurred.
	File    string         // File name where the error occurred.
	Body    map[string]any // Request body data (if available).
	Status  int            // HTTP status code.
	Message string         // Error message.
}

HttpError represents an HTTP error with additional context.

func (HttpError) Error

func (he HttpError) Error() string

Error returns the error message as a string.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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