Documentation ¶
Index ¶
- Constants
- func AnyStartsWith(array []string, word string) bool
- func Base64decode(v string) (string, error)
- func Base64encode(v []byte) string
- func Bool(v bool) *bool
- func BoolValue(v *bool) bool
- func BuildPKISerial() (*big.Int, error)
- func CSRF(excludePaths []string) gin.HandlerFunc
- func Contains[T comparable](array []T, value T) bool
- func ContainsIgnoreCase(array []string, word string) bool
- func ContainsInteger(array []int, value int) bool
- func ContainsString(array []string, word string) bool
- func DELETE(group *gin.RouterGroup, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
- func Decrypt(data []byte, passphrase string) ([]byte, error)
- func Encrypt(data []byte, passphrase string) ([]byte, error)
- func EnsureDot(input string) string
- func EqualArrays[T comparable](a, b []T) bool
- func EqualStringArrays(a, b []string) bool
- func Float64(value float64) *float64
- func Float64Value(v *float64) float64
- func GET(group *gin.RouterGroup, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
- func GetResultDiff[T comparable](results []T, desiredResults []T) []T
- func Int(value int) *int
- func Int32(value int32) *int32
- func Int32Value(v *int32) int32
- func Int64(value int64) *int64
- func Int64Value(v *int64) int64
- func IsHTTPS(r *http.Request) bool
- func LoadAndListenConfig(path string, obj interface{}, onUpdate func(oldObj interface{})) error
- func MakeSentryTransaction(ctx context.Context, name string, opts ...sentry.SpanOption) (context.Context, *sentry.Span, *sentry.Hub)
- func MakeSpan(ctx context.Context, skip int) *sentry.Span
- func MapToString(input map[string]string) []string
- func MfaValidation(secret string, token string) error
- func MinUint(a, b uint) uint
- func PATCH(group *gin.RouterGroup, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
- func POST(group *gin.RouterGroup, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
- func PUT(group *gin.RouterGroup, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
- func Ptr[T any](v T) *T
- func PtrValue[T any](p *T) T
- func RandomString(n int) (string, error)
- func RandomToken() (string, error)
- func RecoverWithContext(ctx context.Context, transaction *sentry.Span)
- func Recovery() gin.HandlerFunc
- func RedisRateLimiter(rdb *redis.Client, key KeyFunc, errFunc ErrFunc) gin.HandlerFunc
- func RemoveDot(input string) string
- func SleepUntil(backoff Backoff, condition ConditionFunc) error
- func String(s string) *string
- func StringEmpty(value string) bool
- func StringToBool(value string) bool
- func StringValue(s *string) string
- func UintValue(v *uint) uint
- func Unique[T comparable](values []T) []T
- type Backoff
- type ConditionFunc
- type Datastore
- type ErrFunc
- type ErrorResponse
- type HTTPRequest
- type HTTPResponse
- type Internal
- type JWTKey
- type KeyFunc
- type Model
- type User
Examples ¶
Constants ¶
const ( // CsrfTokenKey is the cookie name which contains the CSRF token. CsrfTokenKey = "csrftoken" // Xcsrf is the header name which contains the CSRF token. Xcsrf = "X-CSRF-Token" // Authorization is the header name which contains the token. Authorization = "Authorization" )
const ServiceAccountPrefix = "@oauth2"
ServiceAccountPrefix email domain for service accounts.
Variables ¶
This section is empty.
Functions ¶
func Base64decode ¶
Base64decode decodes base64 input to string.
Example ¶
out, _ := Base64decode("U1VDQ0VTUw==") fmt.Println(out)
Output: SUCCESS
func Base64encode ¶ added in v1.1.1
Base64encode encode input to base64.
Example ¶
fmt.Println(Base64encode([]byte("SUCCESS")))
Output: U1VDQ0VTUw==
func BuildPKISerial ¶ added in v1.2.4
BuildPKISerial generates random big.Int.
func CSRF ¶
func CSRF(excludePaths []string) gin.HandlerFunc
CSRF is middleware for handling CSRF protection in gin.
Example ¶
r := gin.New() excludePaths := []string{"/oauth2/token"} r.Use(CSRF(excludePaths))
Output:
func Contains ¶
func Contains[T comparable](array []T, value T) bool
Contains returns true if value is found in array. Both input variables must be same type.
Example ¶
fmt.Println(Contains([]string{"foo", "bar"}, "bar")) fmt.Println(Contains([]int{1, 2}, 1)) fmt.Println(Contains([]string{"foo", "bar"}, "heh")) fmt.Println(Contains([]int{1, 2}, 66))
Output: true true false false
func ContainsIgnoreCase ¶
ContainsIgnoreCase returns true if word is found from array. Case of word and words in array is ignored.
func ContainsInteger ¶
ContainsInteger returns true if integer is found from array.
func ContainsString ¶
ContainsString returns true if string is found from array.
Example ¶
fmt.Println(ContainsString([]string{"foo", "bar"}, "bar")) fmt.Println(ContainsString([]string{"foo", "bar"}, "BAR")) fmt.Println(ContainsString([]string{"foo", "bar"}, "bar2"))
Output: true false false
func DELETE ¶ added in v1.2.7
func DELETE(group *gin.RouterGroup, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
DELETE wrapper to include sentrySpanTracer as last middleware.
func Decrypt ¶
Decrypt the encrypted secret with passphrase.
Example ¶
encrypted, _ := Encrypt([]byte("supersecret"), "testpassword") data, _ := Decrypt(encrypted, "testpassword") fmt.Println(string(data))
Output: supersecret
func Encrypt ¶
Encrypt the secret input with passphrase source https://www.thepolyglotdeveloper.com/2018/02/encrypt-decrypt-data-golang-application-crypto-packages/
Example ¶
encrypted, _ := Encrypt([]byte("supersecret"), "testpassword") data, _ := Decrypt(encrypted, "testpassword") fmt.Println(string(data))
Output: supersecret
func EqualArrays ¶
func EqualArrays[T comparable](a, b []T) bool
EqualArrays compares equality of two arrays. Both input variables must be same type.
Example ¶
fmt.Println(EqualArrays([]string{"1", "2"}, []string{"1", "2"})) fmt.Println(EqualArrays([]int{1, 2, 3}, []int{1, 2, 3})) fmt.Println(EqualArrays([]string{"1", "2", "3"}, []string{"1", "2"}))
Output: true true false
func EqualStringArrays ¶
EqualStringArrays compares equality of two string arrays.
func GET ¶ added in v1.2.7
func GET(group *gin.RouterGroup, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
GET wrapper to include sentrySpanTracer as last middleware.
func GetResultDiff ¶
func GetResultDiff[T comparable](results []T, desiredResults []T) []T
GetResultDiff returns array of strings that were desired but missing from results.
Example ¶
fmt.Println(GetResultDiff([]string{"foo", "bar"}, []string{"foo"})) fmt.Println(GetResultDiff([]string{"foo", "bar"}, []string{"foo", "heh"}))
Output: [] [heh]
func IsHTTPS ¶
IsHTTPS is a helper function that evaluates the http.Request and returns True if the Request uses HTTPS. It is able to detect, using the X-Forwarded-Proto, if the original request was HTTPS and routed through a reverse proxy with SSL termination.
func LoadAndListenConfig ¶ added in v1.1.10
LoadAndListenConfig loads config file to struct and listen changes in it.
func MakeSentryTransaction ¶ added in v1.2.7
func MakeSentryTransaction(ctx context.Context, name string, opts ...sentry.SpanOption) (context.Context, *sentry.Span, *sentry.Hub)
MakeSentryTransaction creates Sentry transaction.
func MapToString ¶
MapToString modifies map to string array.
func MfaValidation ¶
MfaValidation validates TOTP mfa with given secret and token.
func PATCH ¶ added in v1.2.7
func PATCH(group *gin.RouterGroup, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
PATCH wrapper to include sentrySpanTracer as last middleware.
func POST ¶ added in v1.2.7
func POST(group *gin.RouterGroup, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
POST wrapper to include sentrySpanTracer as last middleware.
func PUT ¶ added in v1.2.7
func PUT(group *gin.RouterGroup, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
PUT wrapper to include sentrySpanTracer as last middleware.
func RandomString ¶
RandomString returns a random string length of argument n.
func RecoverWithContext ¶ added in v1.2.7
RecoverWithContext recovers from panic and sends it to Sentry.
func Recovery ¶ added in v1.2.7
func Recovery() gin.HandlerFunc
Recovery middleware for Sentry crash reporting.
func RedisRateLimiter ¶ added in v1.1.4
func RedisRateLimiter(rdb *redis.Client, key KeyFunc, errFunc ErrFunc) gin.HandlerFunc
RedisRateLimiter ...
func SleepUntil ¶
func SleepUntil(backoff Backoff, condition ConditionFunc) error
SleepUntil waits for condition to succeeds.
Example ¶
// retry once in second, maximum retries 3 times backoff := Backoff{ Duration: 1 * time.Second, MaxRetries: 3, } err := SleepUntil(backoff, func() (done bool, err error) { // will continue retrying return false, nil // return true, nil, exit immediately, should be used when ConditionFunc succeed // return false, err, exit immediately, should be used when ConditionFunc returns err that we should not retry anymore }) fmt.Println(err.Error())
Output: Timed out waiting for the condition
func StringEmpty ¶
StringEmpty returns boolean value if string is empty.
func StringToBool ¶
StringToBool returns boolean value from string.
func StringValue ¶
StringValue returns string value from pointervalue.
func Unique ¶
func Unique[T comparable](values []T) []T
Unique returns unique array items.
Example ¶
fmt.Println(Unique([]string{"1", "1", "2"}))
Output: [1 2]
Types ¶
type Backoff ¶ added in v1.1.1
type Backoff struct { // The initial duration. Duration time.Duration // The remaining number of iterations in which the duration // parameter may change. If not positive, the duration is not // changed. MaxRetries int }
Backoff contains struct for retrying strategy.
type ConditionFunc ¶ added in v1.1.1
ConditionFunc returns true if the condition is satisfied, or an error if the loop should be aborted.
type Datastore ¶ added in v1.2.4
type Datastore interface { AddJWTKey(context.Context, JWTKey) (*JWTKey, error) ListJWTKeys(context.Context) ([]JWTKey, error) RotateJWTKeys(context.Context, uint) error }
Datastore will contain interface to store auth keys.
type ErrorResponse ¶
type ErrorResponse struct { Code uint `json:"code" example:"400"` Message string `json:"message" example:"Bad request"` }
ErrorResponse provides HTTP error response.
func (ErrorResponse) Error ¶
func (e ErrorResponse) Error() string
type HTTPRequest ¶
type HTTPRequest struct { Method string URL string Body []byte Cookies []*http.Cookie Headers map[string]string OKCode []int Unmarshaler func(data []byte, v any) error }
HTTPRequest ...
type HTTPResponse ¶ added in v1.1.0
HTTPResponse ...
func MakeRequest ¶
func MakeRequest( ctx context.Context, request HTTPRequest, output interface{}, client *http.Client, backoff Backoff, ) (*HTTPResponse, error)
MakeRequest ...
Example ¶
// retry once in second, maximum retries 2 times backoff := Backoff{ Duration: 1 * time.Second, MaxRetries: 2, } type Out struct { Message string `json:"message"` } out := Out{} client := &http.Client{} ctx := context.Background() body, err := MakeRequest( ctx, HTTPRequest{ URL: "https://ingress-api.csf.elisa.fi/healthz", Method: "GET", OKCode: []int{200}, }, &out, client, backoff, ) fmt.Printf("%s\n%s\n%d\n%v\n", out.Message, body.Body, body.StatusCode, err) ctx, cancel := context.WithTimeout(ctx, 1*time.Millisecond) defer cancel() _, err = MakeRequest( ctx, HTTPRequest{ URL: "https://ingress-api.csf.elisa.fi/healthz", Method: "GET", OKCode: []int{200}, }, &out, client, backoff, ) fmt.Printf("%v", err)
Output: pong {"message":"pong","error":""} 200 <nil> Get "https://ingress-api.csf.elisa.fi/healthz": context deadline exceeded
type Internal ¶ added in v1.2.5
type Internal struct { Cluster *string `json:"cluster,omitempty"` ChangeLimit *int `json:"limit,omitempty"` MFA *bool `json:"mfa"` EmployeeID string `json:"employeeid,omitempty"` }
Internal contains struct for internal non standard variables.
type JWTKey ¶ added in v1.2.4
type JWTKey struct { Model KID string `yaml:"kid" json:"kid"` PrivateKey *rsa.PrivateKey `yaml:"-" json:"-" gorm:"-"` PrivateKeyAsBytes []byte `yaml:"-" json:"-"` PublicKey *rsa.PublicKey `yaml:"-" json:"-" gorm:"-"` PublicKeyAsBytes []byte `yaml:"-" json:"-"` }
JWTKey is struct for storing auth private keys.
func GenerateNewKeyPair ¶ added in v1.2.4
GenerateNewKeyPair generates new private and public keys.
type Model ¶ added in v1.2.4
type Model struct { ID uint `json:"id" gorm:"primarykey"` CreatedAt time.Time `gorm:"index"` UpdatedAt time.Time DeletedAt gorm.DeletedAt `json:"-" gorm:"index"` }
Model is tuned gorm.model.
type User ¶ added in v1.2.5
type User struct { Groups []string `json:"groups,omitempty"` Eid string `json:"custom:employeeid,omitempty"` ImportGroups []string `json:"cognito:groups,omitempty"` Email *string `json:"email,omitempty"` EmailVerified *bool `json:"email_verified,omitempty"` Name *string `json:"name,omitempty"` Internal *Internal `json:"internal,omitempty"` }
User contains struct for single user.
func (User) IsServiceAccount ¶ added in v1.2.6
IsServiceAccount returns boolean is the account service account.