swan_lib

package module
v1.2.7 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2024 License: GPL-3.0 Imports: 14 Imported by: 1

README

Why I Built This

Swan_lib was created to help Go developers handle JWT authentication, CORS, and common API tasks easily when working with net/http. I built this because, while working on my own microservice for a portfolio project, I found myself repeating the same code too often. Instead of getting frustrated, I wrote this library to save time, reduce complexity, and focus on the actual business logic.

I haved tested the JWT middleware and I believe also the CORS will work

Available Methods in swan_lib

Here’s a quick rundown of what swan_lib offers to simplify your API development with net/http:


JWT Methods

  • NewJWTManager(secretKey string, duration time.Duration)
    Create a manager for generating and verifying JWTs with a secret key and expiration duration.

  • GenerateToken(userID string, customClaims map[string]any)
    Generate a JWT with a user ID and optional custom claims.

  • NewJWTMiddleware(secretKey string)
    Set up middleware to validate JWTs on protected routes.

  • Authorize(next http.Handler)
    Middleware that checks if a valid JWT is present in the request.


CORS Methods

  • NewCORSMiddleware()
    Create a CORS middleware to handle cross-origin requests.

  • AllowOrigins(origins []string)
    Specify allowed origins for CORS.

  • AllowMethods(methods []string)
    Define allowed HTTP methods (GET, POST, etc.) for CORS.

  • AllowHeaders(headers []string)
    Set which headers are allowed in CORS requests.

  • AllowCredentials(allowed bool)
    Allow or disallow credentials in cross-origin requests.

  • Handler(next http.Handler)
    Apply CORS settings to the provided handler.


General Utilities

  • JSONResponse(w http.ResponseWriter, status int, data any)
    Send a JSON response with the given status and data.

  • ErrorResponse(w http.ResponseWriter, status int, message string, err error)
    Send a standard error response.

  • ParseBody(r http.Request, target any)
    Parse the request body into the provided struct.


Installation

To get started with swan_lib, run the following command:

go get github.com/SwanHtetAungPhyo/swan_lib

Documentation

Index

Constants

View Source
const (
	ORIGIN_CONTROL      = "Access-Control-Allow-Origin"
	METHOD_CONTROL      = "Access-Control-Allow-Methods"
	HEADER_CONTROL      = "Access-Control-Allow-Headers"
	CREDENTIALS_CONTROL = "Access-Control-Allow-Credentials"
)

Variables

This section is empty.

Functions

func ErrorResponse

func ErrorResponse(w http.ResponseWriter, status int, message string, err error)

func JSONResponse

func JSONResponse(w http.ResponseWriter, status int, message string, data any)

func ParseBody

func ParseBody(r *http.Request, target any) error

Types

type CORSMiddleware

type CORSMiddleware struct {
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	AllowCredentials bool
}

func NewCORSMiddleware

func NewCORSMiddleware() *CORSMiddleware

func (*CORSMiddleware) AllowHeaders

func (c *CORSMiddleware) AllowHeaders(headers []string) *CORSMiddleware

func (*CORSMiddleware) AllowMethods

func (c *CORSMiddleware) AllowMethods(methods []string) *CORSMiddleware

func (*CORSMiddleware) AllowOrigins

func (c *CORSMiddleware) AllowOrigins(origins []string) *CORSMiddleware

func (*CORSMiddleware) Handler

func (c *CORSMiddleware) Handler(next http.Handler) http.Handler

type ErrorResponseStruct

type ErrorResponseStruct struct {
	Error   error  `json:"error"`
	Message string `json:"message"`
	Status  int    `json:"status"`
}

type GlobalJWTMiddleware

type GlobalJWTMiddleware struct {
	Secret string
}

func NewJWTMiddleware

func NewJWTMiddleware(secretKey string) *GlobalJWTMiddleware

func (*GlobalJWTMiddleware) Authorize

func (j *GlobalJWTMiddleware) Authorize(next http.Handler) http.Handler

func (*GlobalJWTMiddleware) FastAuthorize added in v1.2.2

func (*GlobalJWTMiddleware) FiberAuthorize added in v1.2.5

func (j *GlobalJWTMiddleware) FiberAuthorize() fiber.Handler

type GlobalResponse

type GlobalResponse struct {
	Message string `json:"message"`
	Body    any    `json:"body"`
}

type GraceFulShutDown

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

func New

func New() *GraceFulShutDown

func (*GraceFulShutDown) AddTask

func (g *GraceFulShutDown) AddTask(task func(ctx context.Context) error)

func (*GraceFulShutDown) Run

func (g *GraceFulShutDown) Run(timeout time.Duration)

type JWTManager

type JWTManager struct {
	SecretKey     string
	TokenDuration time.Duration
}

func NewJWTManager

func NewJWTManager(secretKey string, duration time.Duration) *JWTManager

func (*JWTManager) GenerateToken

func (j *JWTManager) GenerateToken(userID string, customClaims map[string]any) (string, error)

Jump to

Keyboard shortcuts

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