gohttp

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2025 License: ISC Imports: 10 Imported by: 0

README

gohttp

gohttp is a Go package that provides a collection of utilities and middleware for building HTTP servers using the Fiber 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/mekramy/gohttp

Usage

Error Handling
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/mekramy/gohttp"
    "github.com/mekramy/gologger"
)

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

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

import (
    "github.com/gofiber/fiber/v2"
    "github.com/mekramy/gocache"
    "github.com/mekramy/gohttp/session"
)

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

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

import (
    "github.com/gofiber/fiber/v2"
    "github.com/mekramy/gocache"
    "github.com/mekramy/gohttp/session"
    "github.com/mekramy/gohttp/csrf"
)

func main() {
    app := fiber.New()
    cache := gocache.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/mekramy/gohttp/limiter"
    "github.com/mekramy/gocache"
)

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

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

import (
    "github.com/gofiber/fiber/v2"
    "github.com/mekramy/gohttp/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/mekramy/gohttp/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 a new HttpError with the provided error message and optional status code. If no status code is provided, it defaults to 500. It also captures the file and line number where the error occurred.

func NewFiberErrorHandler

func NewFiberErrorHandler(l gologger.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 a new HttpError with the provided error message, request context, and optional status code. It captures the file and line number where the error occurred and 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.
	Status  int            // HTTP status code.
	Message string         // Error message.
}

HttpError represents an HTTP error with additional context information.

func (HttpError) Error

func (he HttpError) Error() string

Error returns the error message.

Directories

Path Synopsis
Package uploader provides functionality for handling file uploads.
Package uploader provides functionality for handling file uploads.

Jump to

Keyboard shortcuts

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