rotator

package module
v0.0.0-...-7050c00 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2023 License: MIT Imports: 3 Imported by: 0

README

Rotator

Go Reference Go Report Card License

Overview

Rotator is a Go package that provides an implementation of a rotating container, well-suited for use cases where cyclic traversal of element lists or rapid access by their respective keys is necessary, all while ensuring Go routine safety.

Installation

To install the package, simply run:

go get github.com/dimasadyaksa/rotator

Usage

Here is an example of using Rotator as a key rotator for JWT signing.

First, make sure to install the "github.com/golang-jwt/jwt" package if you haven't already:

go get github.com/golang-jwt/jwt
package main

import (
	"fmt"
	"github.com/dimasadyaksa/rotator"
	"github.com/golang-jwt/jwt"
)

// JWTKey Custom struct to represent JWT signing keys.
type JWTKey struct {
	ID  string
	Key string
}

func main() {
	// Create a Rotator for JWT signing keys.
	keyRotator := rotator.New(func(key JWTKey) string {
		return key.ID
	})

	keys := []JWTKey{
		{
			ID:  "key1",
			Key: "key1_secret",
		},
		{
			ID:  "key2",
			Key: "key2_secret",
		},
	}

	// Add JWT signing keys to the rotator.
	keyRotator.Add(keys...)

	// Get the current key from the rotator.
	currentKey, err := keyRotator.Rotate()
	if err != nil {
		fmt.Println("Error getting current key:", err)
		return
	}

	// Create a new JWT token.
	token := jwt.New(jwt.SigningMethodHS256)

	// Set the "kid" (Key ID) in the JWT header.
	token.Header["kid"] = currentKey.ID

	// Sign the token with the current key.
	tokenString, err := token.SignedString([]byte(currentKey.Key))
	if err != nil {
		fmt.Println("Error signing token:", err)
		return
	}

	// Print the JWT token.
	fmt.Println("JWT Token:")
	fmt.Println(tokenString)
}

License

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Rotator

type Rotator[T any, C comparable] struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func New

func New[T any, C comparable](keyFunc func(T) C) *Rotator[T, C]

func (*Rotator[T, C]) Add

func (k *Rotator[T, C]) Add(v ...T) error

func (*Rotator[T, C]) Delete

func (k *Rotator[T, C]) Delete(key C) error

func (*Rotator[T, C]) Get

func (k *Rotator[T, C]) Get(key C) (T, bool)

func (*Rotator[T, C]) Len

func (k *Rotator[T, C]) Len() int

func (*Rotator[T, C]) Rotate

func (k *Rotator[T, C]) Rotate() (T, error)

Jump to

Keyboard shortcuts

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