sgul

package module
v0.0.0-...-419076b Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2019 License: MIT Imports: 22 Imported by: 0

README

SGUL - Simple Golang Utils & Libs

Documentation

Overview

Package sgul defines common structures and functionalities for applications. config.go defines commons for application configuration.

Package sgul defines common structures and functionalities for applications. controller.go defines commons for a base api controller.

Package sgul defines common structures and functionalities for applications. log.go defines commons for application logging.

Package sgul defines common structures and functionalities for applications. repository.go defines commons for a Gorm based Repository structure.

Package sgul defines common structures and functionalities for applications. stringify.go converts a struct to its string representation.

Index

Constants

This section is empty.

Variables

View Source
var ErrPagerNotInContext = errors.New("Pager info not in Context")

ErrPagerNotInContext is returned if there is no Pager in the request context.

View Source
var ErrPrincipalNotInContext = errors.New("No Principal in request context")

ErrPrincipalNotInContext is returned if there is no Principal in the request context.

Functions

func ContainsString

func ContainsString(s []string, elem string) bool

ContainsString checks if a slice of strings contains a string.

func Get

func Get(key string) interface{}

Get returns a configuration map by key. Used for custom or gear configurations.

func GetLogger

func GetLogger() *zap.Logger

GetLogger .

func GetLoggerByConf

func GetLoggerByConf(conf Log) *zap.Logger

GetLoggerByConf .

func IsSet

func IsSet(key string) bool

IsSet checks to see if the key has been set in any of the data locations. IsSet is case-insensitive for a key.

func JWTAuthorizer

func JWTAuthorizer(roles []string) func(next http.Handler) http.Handler

JWTAuthorizer is the JWT authentication middleware to use on mux (a. e. Chi router or Groups).

func JWTRouteAuthorizer

func JWTRouteAuthorizer(roles []string) func(next http.HandlerFunc) http.HandlerFunc

JWTRouteAuthorizer is the JWT authentication middleware to use on single route (a.e. Chi router get, post, ...).

func LoadConfiguration

func LoadConfiguration(configStruct interface{})

LoadConfiguration reads the configuration file according to the ENV var and return unmarshalled struct.

func MaskedStringify

func MaskedStringify(strct interface{}, mask []string) string

MaskedStringify converts a struct to its string representation obfuscating values for the key passed in mask slice.

func NewHTTPError

func NewHTTPError(err error, status int, detail interface{}, requestID string) error

NewHTTPError returns a new HTTPError instance

func Pager

func Pager() func(next http.Handler) http.Handler

Pager is the query paging middleware.

func RenderError

func RenderError(w http.ResponseWriter, err error)

RenderError exported to be used in this lib (a.e. in middlewares) returns error to the client.

func RoutePager

func RoutePager(next http.HandlerFunc) http.HandlerFunc

RoutePager is the query paging middleware to be used on routes.

func Stringify

func Stringify(strct interface{}) string

Stringify converts a struct to its string representation.

Types

type AMQP

type AMQP struct {
	User     string
	Password string
	Host     string
	Port     int
	VHost    string
	Exchange string
	Queue    string
}

AMQP configuration

type AMQPConnection

type AMQPConnection struct {
	URI        string
	Connection *amqp.Connection
	Channel    *amqp.Channel
}

AMQPConnection .

func NewAMQPConnection

func NewAMQPConnection() *AMQPConnection

NewAMQPConnection return a new disconnected AMQP Connection structure.

func (*AMQPConnection) Close

func (conn *AMQPConnection) Close()

Close closes AMQP channel and connection.

func (*AMQPConnection) Connect

func (conn *AMQPConnection) Connect() error

Connect open an AMQP connection and setup the channel.

type AMQPPublisher

type AMQPPublisher struct {
	Connection   *AMQPConnection
	Exchange     string
	ExchangeType string
	RoutingKey   string
}

AMQPPublisher define the AMQP Publisher structure.

func NewAMQPPublisher

func NewAMQPPublisher(connection *AMQPConnection, exchange string, exchangeType string, routingKey string) (*AMQPPublisher, error)

NewAMQPPublisher return a new AMQP Publisher object.

func (*AMQPPublisher) Publish

func (pub *AMQPPublisher) Publish(event Event) error

Publish send a message to the AMQP Exchange.

type AMQPSubscriber

type AMQPSubscriber struct {
}

AMQPSubscriber define the AMQP Subscriber structure.

type API

type API struct {
	Endpoint struct {
		Port            int
		BaseRoutingPath string
	}
	Security struct {
		Enabled bool
		Jwt     struct {
			Secret     string
			Expiration struct {
				Enabled bool
				Minutes int32
			}
		}
	}
}

API is the structure for the Http API server and app configuration.

type ChiController

type ChiController interface {
	Router() chi.Router
}

ChiController defines the interface for an API Controller with Chi Router

type ClientError

type ClientError interface {
	Error() string
	// ResponseBody returns response body.
	ResponseBody() ([]byte, error)
	// ResponseHeaders returns http status code and headers.
	ResponseHeaders() (int, map[string]string)
}

ClientError is an error whose details to be shared with client.

type Configuration

type Configuration struct {
	Service    Service
	API        API
	DB         DB
	Management Management
	Log        Log
	Ldap       Ldap
	AMQP       AMQP
}

Configuration describe the type for the configuration file

func GetConfiguration

func GetConfiguration() *Configuration

GetConfiguration returns the Configuration structure singleton instance.

type Controller

type Controller struct {
	// Path is the base routing path for each route of the controller
	Path string
}

Controller defines the base API Controller structure

func NewController

func NewController(path string) Controller

NewController return a new instance of Controller (useful in composition for api controllers).

func (*Controller) RenderError

func (c *Controller) RenderError(w http.ResponseWriter, err error)

RenderError returns error to the client.

type DB

type DB struct {
	Type       string
	Host       string
	Port       int
	User       string
	Password   string
	Database   string
	Log        bool
	Migrations struct {
		Enabled            bool
		Drop               bool
		SingularTableNames bool
	}
}

DB is the structure for the main database configuration.

type Event

type Event struct {
	// Name is the global identifier for event. It MUST be
	// composed as "<action>_<resource>", a.e. "new_user", "upd_user", "del_user", ...
	Name string

	// Source is the global identifier for the client which push
	// the evt message. A.E. "uaa-servce", "acct-service", ...
	Source string

	// Payload is the struct containing all the event message information.
	// The AMQP Publisher will marshal it to json and the AMQP Subscriber
	// will unmarshal it into a specific request (something like a dto).
	Payload interface{}
}

Event is the struct used to push event messages into AMQP queues.

func NewEvent

func NewEvent(name string, source string, payload interface{}) Event

NewEvent return a new Event instance.

type GormRepository

type GormRepository struct {
	DB *gorm.DB
}

GormRepository defines the base repository structure form gorm based db access

func NewRepository

func NewRepository(db *gorm.DB) GormRepository

NewRepository returns a new Repository instance

func (GormRepository) DoInTransaction

func (r GormRepository) DoInTransaction(fn InTransaction) error

DoInTransaction executes the fn() callback in a gorm transaction.

type HTTPError

type HTTPError struct {
	Code      int         `json:"code"`
	Err       string      `json:"error"`
	Detail    interface{} `json:"detail"`
	RequestID string      `json:"requestId"`
	Timestamp time.Time   `json:"timestamp"`
}

HTTPError implements ClientError interface.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error return a formatted description of the error.

func (*HTTPError) ResponseBody

func (e *HTTPError) ResponseBody() ([]byte, error)

ResponseBody returns JSON response body.

func (*HTTPError) ResponseHeaders

func (e *HTTPError) ResponseHeaders() (int, map[string]string)

ResponseHeaders returns http status code and headers.

type InTransaction

type InTransaction func(tx *gorm.DB) error

InTransaction defines the func type to be executed in a gorm transaction.

type Ldap

type Ldap struct {
	Base   string
	Host   string
	Port   int
	UseSSL bool
	Bind   struct {
		DN       string
		Password string
	}
	UserFilter  string
	GroupFilter string
	Attributes  []string
}

Ldap configuration

type Log

type Log struct {
	Path       string
	Filename   string
	Console    bool
	Level      string
	JSON       bool
	MaxSize    int
	MaxBackups int
	MaxAge     int
	Compress   bool
	Caller     bool
}

Log is the structure for the logger configuration. If not present, the Machinery will use a default logger provided by the "gm-log" package.

type Management

type Management struct {
	Endpoint struct {
		Port            int
		BaseRoutingPath string
	}
	Health struct {
		Path string
		Full bool
	}
}

Management is the structure for the management http endpoint configuration.

type Page

type Page struct {
	Page int
	Size int
}

Page defines the struct with paging info to send into the request context.

func GetPage

func GetPage(ctx context.Context) (Page, error)

GetPage return the pager struct from request Context.

type Principal

type Principal struct {
	Username string
	Role     string
}

Principal defines the struct registered into the Context representing the authenticated user information from the JWT Token.

func GetPrincipal

func GetPrincipal(ctx context.Context) (Principal, error)

GetPrincipal return the user authenticated Princiapl information from the request context.

type Service

type Service struct {
	Group   string
	Name    string
	Version string
}

Service is the structure for the service information configuration.

Jump to

Keyboard shortcuts

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