Documentation ¶
Overview ¶
Package sgul defines common structures and functionalities for applications. amqp.go defines commons for amqp integration.
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. event.go defines commons for application events: normally to push some event into an amqp event bus.
Package sgul defines common structures and functionalities for applications. jwt.go defines commons for jwt Authorization.
Package sgul defines common structures and functionalities for applications. loadbalance.go defines commons for endpoints load balancing.
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. pagin.go defines commons for paging params in api requests.
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. servicereg.go defines helpers for service registration using the kit/registry.Client.
Package sgul defines common structures and functionalities for applications. sham.go defines the ShamClient struct to be used as a service-to-service http load-balanced client.
Package sgul defines common structures and functionalities for applications. stringify.go converts a struct to its string representation.
Index ¶
- Constants
- Variables
- func ContainsString(s []string, elem string) bool
- func Get(key string) interface{}
- func GetComponentConfig(cname string) interface{}
- func IsSet(key string) bool
- func JWTAuthorizer(enforcer RolesEnforcer) func(next http.Handler) http.Handler
- func JWTRouteAuthorizer(enforcer RolesEnforcer) func(next http.HandlerFunc) http.HandlerFunc
- func LoadConfiguration(configStruct interface{})
- func MaskedStringify(strct interface{}, mask []string) string
- func MergeStringSlices(s1, s2 []string) []string
- func NewHTTPError(err error, status int, detail interface{}, requestID string) error
- func Pager() func(next http.Handler) http.Handler
- func RegisterService(r registry.ServiceRegistrationRequest) (registry.ServiceRegistrationResponse, error)
- func RenderError(w http.ResponseWriter, err error)
- func RoutePager(next http.HandlerFunc) http.HandlerFunc
- func Stringify(strct interface{}) string
- type AMQP
- type AMQPConnection
- type AMQPPublisher
- type AMQPSubscriber
- type API
- type Balancer
- type BalancingStrategy
- type CasbinEnforcer
- type ChiController
- type Client
- type ClientError
- type Configuration
- type Controller
- type DB
- type Event
- type Exchange
- type GormRepository
- type GormRepositoryInterface
- type HTTPError
- type InTransaction
- type Ldap
- type Log
- type Logger
- type Management
- type MatchAllEnforcer
- type MatchRoleEnforcer
- type Page
- type Principal
- type Publisher
- type Queue
- type REGAgent
- type RestController
- type RolesEnforcer
- type Service
- type ServiceRegistry
- type ShamClient
- type Subscriber
Constants ¶
const RandomStrategy = "random"
RandomStrategy is the random balancing strategy name.
const RoundRobinStrategy = "round-robin"
RoundRobinStrategy is the round robin balancing strategy name.
Variables ¶
var ErrFailedDiscoveryRequest = errors.New("Error making service discovery HTTP request")
ErrFailedDiscoveryRequest is returned when a discovery request fails.
var ErrFailedDiscoveryResponseBody = errors.New("Error reading service discovery HTTP response body")
ErrFailedDiscoveryResponseBody is returned if the discovery client is unable to read http response body.
var ErrPagerNotInContext = errors.New("Pager info not in Context")
ErrPagerNotInContext is returned if there is no Pager in the request context.
var ErrPrincipalNotInContext = errors.New("No Principal in request context")
ErrPrincipalNotInContext is returned if there is no Principal in the request context.
Functions ¶
func ContainsString ¶
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 GetComponentConfig ¶
func GetComponentConfig(cname string) interface{}
GetComponentConfig returns default config structure for a default component name.
func IsSet ¶
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(enforcer RolesEnforcer) func(next http.Handler) http.Handler
JWTAuthorizer is the JWT authentication middleware to use on mux (a. e. Chi router or Groups). func JWTAuthorizer(roles []string) func(next http.Handler) http.Handler {
func JWTRouteAuthorizer ¶
func JWTRouteAuthorizer(enforcer RolesEnforcer) func(next http.HandlerFunc) http.HandlerFunc
JWTRouteAuthorizer is the JWT authentication middleware to use on single route (a.e. Chi router get, post, ...). func JWTRouteAuthorizer(roles []string) func(next http.HandlerFunc) http.HandlerFunc {
func LoadConfiguration ¶
func LoadConfiguration(configStruct interface{})
LoadConfiguration reads the configuration file according to the ENV var and return unmarshalled struct.
func MaskedStringify ¶
MaskedStringify converts a struct to its string representation obfuscating values for keys in the mask slice.
func MergeStringSlices ¶
MergeStringSlices merges string slices avoiding duplicates. source code from Jacy Gao (http://jgao.io/?p=119)... thank you man!
func NewHTTPError ¶
NewHTTPError returns a new HTTPError instance
func RegisterService ¶
func RegisterService(r registry.ServiceRegistrationRequest) (registry.ServiceRegistrationResponse, error)
RegisterService is an helper to register a service with the SgulREG service.
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.
Types ¶
type AMQP ¶
type AMQP struct { User string Password string Host string Port int VHost string Exchanges []Exchange Queues []Queue Publishers []Publisher Subscribers []Subscriber }
AMQP configuration
type AMQPConnection ¶
type AMQPConnection struct { URI string Connection *amqp.Connection Channel *amqp.Channel // publishers to be send messages to the relative exchanges Publishers map[string]*AMQPPublisher // subscribers to start and listen for messages from relative queues Subscribers map[string]*AMQPSubscriber // contains filtered or unexported fields }
AMQPConnection is the main struct to manage a connection to an AMQP server. It keeps exchanges and queues up and register AMQP publishers and subscribers.
func NewAMQPConnection ¶
func NewAMQPConnection() *AMQPConnection
NewAMQPConnection return a new disconnected AMQP Connection structure.
func (*AMQPConnection) Close ¶
func (conn *AMQPConnection) Close() error
Close closes AMQP channel and connection.
func (*AMQPConnection) Connect ¶
func (conn *AMQPConnection) Connect() error
Connect open an AMQP connection and setup the channel.
func (*AMQPConnection) NewPublisher ¶
func (conn *AMQPConnection) NewPublisher(name string) (*AMQPPublisher, error)
NewPublisher return a new AMQP Publisher object initialized with "name"-publisher configuration.
func (*AMQPConnection) Subscriber ¶
func (conn *AMQPConnection) Subscriber(queue string, consumer string, durable, autoDelete, autoAck, exclusive, noLocal, noWait bool) (*AMQPSubscriber, error)
Subscriber reutrns a new AMQP Subscriber on this connection.
type AMQPPublisher ¶
type AMQPPublisher struct { Connection *AMQPConnection Exchange string ExchangeType string RoutingKey string ContentType string DeliveryMode uint8 }
AMQPPublisher define the AMQP Publisher structure. Normally can be used as a sort of repository by a business service.
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. TODO: try and parametrize even "mandatory" and "immdiate" flags.
type AMQPSubscriber ¶
type AMQPSubscriber struct { Connection *AMQPConnection Queue string Consumer string AutoAck bool Exclusive bool NoLocal bool NoWait bool Replies <-chan amqp.Delivery }
AMQPSubscriber define the AMQP Subscriber structure. TODO: complete the definition!!!
func NewAMQPSubscriber ¶
func NewAMQPSubscriber(connection *AMQPConnection, queue string, consumer string, durable, autoDelete, autoAck, exclusive, noLocal, noWait bool) (*AMQPSubscriber, error)
NewAMQPSubscriber returns a new AMQP Subscriber object.
type API ¶
type API struct { Endpoint struct { Port int BaseRoutingPath string } // Cors defines the cors allowed resources struct. Cors struct { Origin []string Methods []string Headers []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 Balancer ¶
Balancer defines the load balancing interface for a concrete balancer.
func BalancerFor ¶
BalancerFor returns the load balancer instance for the requested strategy.
func RandomBalander ¶
func RandomBalander() Balancer
RandomBalander returns the random balancer instance.
func RoundRobinBalancer ¶
func RoundRobinBalancer() Balancer
RoundRobinBalancer returns the round-robin balancer instance.
type BalancingStrategy ¶
type BalancingStrategy struct {
Strategy string
}
BalancingStrategy defines the load balancing strategy.
type CasbinEnforcer ¶
type CasbinEnforcer struct {
// contains filtered or unexported fields
}
CasbinEnforcer .
type ChiController ¶
ChiController defines the interface for an API Controller with Chi Router
type Client ¶
type Client struct { // Timeout specifies a time limit for requests made by this // Client. The timeout includes connection time, any // redirects, and reading the response body. The timer remains // running after Get, Head, Post, or Do return and will // interrupt reading of the Response.Body. // A Timeout of zero means no timeout. Timeout time.Duration // Timeout is the maximum amount of time a dial will wait for // a connect to complete. If Deadline is also set, it may fail // earlier. // The default is no timeout. DialerTimeout time.Duration // TLSHandshakeTimeout specifies the maximum amount of time waiting to // wait for a TLS handshake. Zero means no timeout. TLSHandshakeTimeout time.Duration // ExpectContinueTimeout, if non-zero, specifies the amount of // time to wait for a server's first response headers after fully // writing the request headers if the request has an // "Expect: 100-continue" header. Zero means no timeout and // causes the body to be sent immediately, without // waiting for the server to approve. // This time does not include the time to send the request header. ExpectContinueTimeout time.Duration // ResponseHeaderTimeout, if non-zero, specifies the amount of // time to wait for a server's response headers after fully // writing the request (including its body, if any). This // time does not include the time to read the response body. ResponseHeaderTimeout time.Duration // ServiceRegistry is the service registry for this client. ServiceRegistry ServiceRegistry // Balancing is the load balancing strategy for this client. // Actually it can be one from "round-robin" or "random". Balancing BalancingStrategy }
Client defines configuration structure for Http (API) clients.
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 Client Client 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.
type Exchange ¶
type Exchange struct { Name string Type string AutoDelete bool Durable bool Internal bool NoWait bool }
Exchange is the config struct for an AMQP Exchange.
type GormRepository ¶
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.
func (*GormRepository) SetDB ¶
func (r *GormRepository) SetDB(db *gorm.DB)
SetDB sets gorm db instance into the repository.
type GormRepositoryInterface ¶
GormRepositoryInterface is the contract for a Gorm Repository.
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) ResponseBody ¶
ResponseBody returns JSON response body.
type InTransaction ¶
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 Logger ¶
type Logger = zap.SugaredLogger
Logger is a type alias for Zap sugared logger We love Zap, we use Zap and we will continue using it forever!
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 MatchAllEnforcer ¶
type MatchAllEnforcer struct{}
MatchAllEnforcer is the match all rules;routes enforcer. It will always authorize a user.
type MatchRoleEnforcer ¶
type MatchRoleEnforcer struct {
// contains filtered or unexported fields
}
MatchRoleEnforcer authorize user only if it's role is in roles.
func NewMatchRoleEnforcer ¶
func NewMatchRoleEnforcer(roles []string) *MatchRoleEnforcer
NewMatchRoleEnforcer returns a new MathRoleEnforcer instance.
func (*MatchRoleEnforcer) Enforce ¶
func (mre *MatchRoleEnforcer) Enforce(ctx context.Context, role string, route string, method string) bool
Enforce always authorize a user role agains roles[]. It skips route/method checks. The use is authorized only if it role is in roles[]. If roles[] size is 0 user will not be authorized.
type Principal ¶
Principal defines the struct registered into the Context representing the authenticated user information from the JWT Token.
type Publisher ¶
type Publisher struct { Name string Exchange string RoutingKey string ContentType string // 2: "persistent" or 1: "non-persistent" DeliveryMode uint8 }
Publisher is the config struct for an AMQP Publisher.
type Queue ¶
type Queue struct { Name string AutoDelete bool Durable bool Internal bool Exclusive bool NoWait bool }
Queue is the config struct for an AMQP Queue.
type REGAgent ¶
type REGAgent struct {
// contains filtered or unexported fields
}
REGAgent is the Agent used by a service to register its instance with the SgulREG Service Registry. It is an helper agent to use the sgulreg client.
func NewREGAgent ¶
NewREGAgent returns a new REGAgent instance
func (*REGAgent) Register ¶
func (ra *REGAgent) Register(r registry.ServiceRegistrationRequest) (registry.ServiceRegistrationResponse, error)
Register try and register register a service with the SgulREG service. If the registration fails, it starts a watcher to continue trying registration.
type RestController ¶
RestController is the Rest API Controller interface.
type RolesEnforcer ¶
type RolesEnforcer interface {
Enforce(ctx context.Context, role string, route string, method string) bool
}
RolesEnforcer is the user roles enforcer for gain user access to resources.
type ServiceRegistry ¶
type ServiceRegistry struct { // Type specify the service registry type. Actually only "sgulreg" is managed. Type string // URL is the http url for the service registry. // For a SuglREG registry it is in the form of http://<host>:<port>. // This URL must be without trailing slash. URL string // Fallback is the fallback service registry used in case of the service registry // does not respond at the client startup or respond with and empty list, so we have an // empty local registry. // So, if the client local registry is empty and the service registry is not reachable // at the client startup, the client will use this fallback endpoints list to balance // client requests. Fallback []string // WatchInterval specifies the duration of a single interval between // two service discovery invocations from a service registry watcher. WatchInterval time.Duration }
ServiceRegistry is the endpoint configuration for the service registry used for service discovery by an http client. Actually only Type="sgulreg" is managed.
type ShamClient ¶
type ShamClient struct {
// contains filtered or unexported fields
}
ShamClient defines the struct for a sham client to an http endpoint. The sham client is bound to an http service by its unique system discoverable name.
func NewShamClient ¶
func NewShamClient(serviceName string, apiPath string) *ShamClient
NewShamClient returns a new Sham client instance bounded to a service.