vcago

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2022 License: MIT Imports: 30 Imported by: 1

README

vcago

The package contains standard functions that are used in the Viva-con-Agua API services and is on the echo web framework

PACKAGE

Basic Webserver
Setup in server.go
func main() {
    e := echo.New()
    e.HTTPErrorHandler = vcago.HTTPErrorHandler    
    e.Validator = vcago.JSONValidator
    e.Use(vcago.CORS.Init())
    e.Use(vcago.Logger.Init()) 
    ...

    ...
	appPort := vcago.Config.GetEnvString("APP_PORT", "n", "1323")
	e.Logger.Fatal(e.Start(":" + appPort))

}
edit the .env file
SERVICE_NAME=default  //service name, default default
APP_PORT=1323           // default port 1323
LOGGING_OUTPUT=strout  // pretty, nats default strout
ALLOW_ORIGINS="https://example.com,https://api.example.com"
...
output logger pretty
{
    "id": "",  //not implemented
    "service": "example",
    "time": "2022-02-07T19:50:08.971851362+01:00",
    "remote_ip": "127.0.0.1",
    "host": "localhost:1323",
    "method": "POST",
    "uri": "/example",
    "user_agent": "Mozilla/5.0 (X11; Linux x86_64; rv:96.0) Gecko/20100101 Firefox/96.0",
    "status": 500,
    "error": {
        "status_message": "example error",
        "status_type": "internal_error"
    },
    "latency": 2002915,
    "latency_human": "2.002915ms",
    "byte_in": "",
    "byte_out": "",
    "modified": {
        "updated": 1644259808,
        "created": 1644259808
    }
}
Use in handler

BindAndValidate follows this documentation. In the event of an error, an ValidationError will always be returned, which can be processed by the HTTPErrorHandler.

func Example(c echo.Context) (err error) {
	...
	//Validate JSON
	body := new(dao.Example)
	if vcago.BindAndValidate(c, body); err != nil {
		return
	}
    ...
func main() {
	e := echo.New()
	e.Debug = false
	// Middleware
	e.Use(vcago.Logger.Init())
	e.Use(vcago.CORS.Init())

	//error
	e.HTTPErrorHandler = vcago.HTTPErrorHandler
	e.Validator = vcago.JSONValidator
	handlers.CreateClient()
	login := e.Group("/v1/auth")
	login.POST("/callback", handlers.CallbackHandler)

	//server
	appPort := vcago.Config.GetEnvString("APP_PORT", "n", "1323")
	e.Logger.Fatal(e.Start(":" + appPort))
CONSTANTS

const (
	colorRed    = "\033[31m"
	colorGreen  = "\033[32m"
	colorYellow = "\033[33m"
	colorBlue   = "\033[34m"
	colorPurple = "\033[35m"
	colorCyan   = "\033[36m"
	colorWhite  = "\033[37m"
)

VARIABLES

var CORSConfig = middleware.CORSWithConfig(middleware.CORSConfig{
	AllowOrigins:     strings.Split(os.Getenv("ALLOW_ORIGINS"), ","),
	AllowHeaders:     []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
	AllowCredentials: true,
})
    CORSConfig for api services. Can be configured via .env.


FUNCTIONS

func DeleteSession(c echo.Context)
    DeleteSession remove sessin for context c from Redis.

func GetSessionUser(c echo.Context) (u *vmod.User, contains bool)
    GetSessionUser return user for c or false if c has no user in Redis

func InitSession(c echo.Context, user *vmod.User)
    InitSession initial a session for a vmod.User via Redis

func JSONErrorHandler(c echo.Context, i interface{}) (rErr *verr.ResponseError)
    JSONErrorHandler formats JsonError to ResponseError

func LogAPIError(e *verr.ApiError, c echo.Context, i interface{})
    LogApiError via log.Print

func RedisSession() echo.MiddlewareFunc
    RedisSession middleware initial redis store for session handling

func ResponseErrorHandler(c echo.Context, apiErr *verr.ApiError, i interface{}) (rErr *verr.ResponseError)
    ResponseErrorHandler handles ApiError

func SessionAuth(next echo.HandlerFunc) echo.HandlerFunc
    SessionAuth go to next if the request has a session else return 401.

func formatRequestPrint(r *http.Request) string

TYPES

type Validator struct {
	Validator *validator.Validate
}
    Validator represents a Json validator

func (cv *Validator) Validate(i interface{}) error
    Validate interface i

Documentation

Overview

Package handles error logs via nats message broker

Index

Constants

This section is empty.

Variables

View Source
var APIKey = Config.GetEnvString("API_KEY", "w", "secret")

APIKey represents the api Bearer token

View Source
var CORS = new(CORSConfig)
View Source
var Config = LoadConfig()

Config represents the global configuration variables.

View Source
var ErrMongoDelete = errors.New("no delete document")

ErrMongoDelete represents an delete error in mongo case

View Source
var ErrMongoUpdate = errors.New("no updated document")

ErrMongoUpdate represents an update error in mongo case

View Source
var JSONValidator = NewValidator()
View Source
var LogLevel = Settings.String("LOG_LEVEL", "w", "DEBUG")
View Source
var Nats = new(NatsDAO)

Nats used for Nats connection

View Source
var Settings = SettingTypeLoad()

Functions

func AccessCookieConfig added in v0.1.6

func AccessCookieConfig() echo.MiddlewareFunc

AccessCookieConfig can with echo for middleware.JWTWithConfig(vmod.AccessConfig) to handling access controll The token is reachable with c.Get("token")

func AccessCookieMiddleware added in v1.3.0

func AccessCookieMiddleware(i jwt.Claims) echo.MiddlewareFunc

AccessCookieConfig can with echo for middleware.JWTWithConfig(vmod.AccessConfig) to handling access controll The token is reachable with c.Get("token")

func BindAndValidate added in v1.0.2

func BindAndValidate(c echo.Context, i interface{}) error

func CreateUpdateManyFilter added in v1.2.9

func CreateUpdateManyFilter(key string, values []string) (r *bson.A)

func HTTPErrorHandler added in v1.0.2

func HTTPErrorHandler(err error, c echo.Context)

HTTPErrorHandler handles echo.HTTPError and return the correct response.

func KeyAuthMiddleware added in v1.1.14

func KeyAuthMiddleware() echo.MiddlewareFunc

KeyAuthMiddleware middleware function for handling authentication via key.

func MongoConfict added in v1.3.3

func MongoConfict(err error) bool

func MongoNoDeleted added in v1.1.16

func MongoNoDeleted(err error) bool

func MongoNoDocuments added in v1.1.2

func MongoNoDocuments(err error) bool

func MongoNoUpdated added in v1.1.16

func MongoNoUpdated(err error) bool

func NewEchoServer added in v1.4.0

func NewEchoServer(service string) (r *echo.Echo)

func RandomBase64 added in v1.0.2

func RandomBase64(n int) (string, error)

RandomBase64 generate random Base64 string

func RandomBytes added in v1.0.2

func RandomBytes(n int) ([]byte, error)

RandomBytes return random bytes

func RefreshCookieConfig added in v0.1.6

func RefreshCookieConfig() echo.MiddlewareFunc

RefreshCookieConfig can with echo for middleware.JWTWithConfig(vmod.AccessConfig) to handling access controll The token is reachable with c.Get("token")

func RefreshCookieMiddleware added in v1.3.0

func RefreshCookieMiddleware(i jwt.Claims) echo.MiddlewareFunc

RefreshCookieConfig can with echo for middleware.JWTWithConfig(vmod.AccessConfig) to handling access controll The token is reachable with c.Get("token")

func RefreshCookieUserID added in v1.1.6

func RefreshCookieUserID(c echo.Context) (string, error)

func ResetAccessCookie added in v1.1.6

func ResetAccessCookie() *http.Cookie

ResetAccessCookie returns an cookie for reset the access_token.

func ResetRefreshCookie added in v1.1.6

func ResetRefreshCookie() *http.Cookie

ResetRefreshCookie returns an cookie for reset the refresh_token.

func SliceContains added in v1.1.6

func SliceContains(list []string, element string) bool

func ValidationErrorResponseHandler added in v1.2.11

func ValidationErrorResponseHandler(i *ValidationError) (int, interface{})

ValidationErrorResponseHandler handles the response for the ValidationError type.

Types

type AccessToken added in v1.1.6

type AccessToken struct {
	ID            string         `json:"id,omitempty" bson:"_id"`
	Email         string         `json:"email" bson:"email" validate:"required,email"`
	FirstName     string         `json:"first_name" validate:"required"`
	LastName      string         `json:"last_name" validate:"required"`
	FullName      string         `json:"full_name"`
	DisplayName   string         `json:"display_name"`
	Roles         RoleListCookie `json:"system_roles"`
	Country       string         `json:"country"`
	PrivacyPolicy bool           `json:"privacy_policy"`
	Confirmed     bool           `json:"confirmed"`
	LastUpdate    string         `json:"last_update"`
	jwt.StandardClaims
}

func AccessCookieUser added in v1.1.6

func AccessCookieUser(c echo.Context) (r *AccessToken, err error)

func NewAccessToken added in v1.1.6

func NewAccessToken(user *User) *AccessToken

func (*AccessToken) SignedString added in v1.1.6

func (i *AccessToken) SignedString(secret string) (string, error)

type AdminRequest added in v1.2.10

type AdminRequest struct {
	URL string
}

AdminRequest represents model for admin requests.

func NewAdminRequest added in v1.2.10

func NewAdminRequest() *AdminRequest

func (*AdminRequest) Get added in v1.2.10

func (i *AdminRequest) Get(path string) (r *Response, err error)

func (*AdminRequest) Post added in v1.3.2

func (i *AdminRequest) Post(path string, data interface{}) (r *Response, err error)

type AuthToken added in v1.1.6

type AuthToken struct {
	AccessToken  string `json:"access_token" bson:"access_token"`
	RefreshToken string `json:"refresh_token" bson:"refresh_token"`
	ExpiresAt    int64  `json:"expires_at" bson:"expires_at"`
}

AuthToken represents the authentication tokens for handling access via jwt.

func NewAuthToken added in v1.1.6

func NewAuthToken(user *User) (r *AuthToken, err error)

NewAuthToken creates an new access and refresh token for the given user.

func (*AuthToken) AccessCookie added in v1.1.6

func (i *AuthToken) AccessCookie() (r *http.Cookie)

AccessCookie return an cookie conains the access_token.

func (*AuthToken) RefreshCookie added in v1.1.6

func (i *AuthToken) RefreshCookie() *http.Cookie

RefreshCookie returns an cookie conains the refresh_token.

type CORSConfig added in v0.0.7

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

func (*CORSConfig) Init added in v1.1.2

func (i *CORSConfig) Init() echo.MiddlewareFunc

NewCORSConfig create a echo middleware for cors handling.

type Callback added in v1.1.4

type Callback struct {
	Code string `json:"code"`
}

type Context added in v1.3.0

type Context struct {
	Model string
	echo.Context
}

Context represents an extended echo.Context models used for basic functions in a Handler.

func (*Context) AccessToken added in v1.3.0

func (i *Context) AccessToken(token interface{}) (err error)

AccessToken binds the accessToken form an cookie into an struct.

func (*Context) BindAndValidate added in v1.3.0

func (i *Context) BindAndValidate(body interface{}) error

BindAndValidate binds the request data in an the body interface. Define param:"" for bind the params in a struct. Define json:"" for bind the request body as json in a struct. Define query:"" for bind the query parameters in a struct.

func (*Context) Created added in v1.3.0

func (i *Context) Created(payload interface{}) (err error)

Created returns an Created response.

func (*Context) Ctx added in v1.3.0

func (i *Context) Ctx() context.Context

Ctx return the context.Context model of the request.

func (*Context) Deleted added in v1.3.0

func (i *Context) Deleted(payload interface{}) (err error)

Deleted returns an Deleted response.

func (*Context) ErrorResponse added in v1.4.0

func (i *Context) ErrorResponse(err error) error

ErrorResonse return an http error for an given error.

func (*Context) Listed added in v1.3.0

func (i *Context) Listed(payload interface{}) (err error)

Listed return an List response.

func (*Context) Log added in v1.4.0

func (i *Context) Log(err error)

Log return a function call for handling Debug and Error logs. Usage: c.Log(err)(err)

func (*Context) Selected added in v1.3.0

func (i *Context) Selected(payload interface{}) (err error)

Selected returns an Selected response.

func (*Context) SuccessResponse added in v1.4.0

func (i *Context) SuccessResponse(status int, message string, model string, payload interface{}) (err error)

func (*Context) Updated added in v1.3.0

func (i *Context) Updated(payload interface{}) (err error)

Updated returns an Updated response

type CookieConfig added in v1.2.0

type CookieConfig struct {
	SameSite http.SameSite
	Secure   bool
	HttpOnly bool
}

CookieConfig represents the cookie parameters

func NewCookieConfig added in v1.2.0

func NewCookieConfig() *CookieConfig

NewCookieConfig loads the cookie parameters from the .env file and return a new CookieConfig.

func (*CookieConfig) Cookie added in v1.2.0

func (i *CookieConfig) Cookie(name string, value string) *http.Cookie

Cookie returns an http.Cookie using the CookieConfig parameters. @param name cookie name @param value cookie value

type CycularMail added in v1.2.4

type CycularMail struct {
	Email   string   `json:"email"`
	Emails  []string `json:"emails"`
	Subject string   `json:"subject"`
	Message string   `json:"message"`
}

func NewCycularMail added in v1.2.4

func NewCycularMail(email string, emails []string, subject string, message string) *CycularMail

type Error added in v1.4.1

type Error struct {
	ID      string `json:"id"`
	Time    string `json:"time"`
	Level   string `json:"level"`
	File    string `json:"file"`
	Line    int    `json:"line"`
	Message string `json:"message"`
	Err     error  `json:"-"`
	Model   string `json:"model,omitempty"`
	Type    string `json:"type"`
}

func NewErrorLog added in v1.4.1

func NewErrorLog(err error, lvl string, t string) *Error

func (*Error) AddModel added in v1.4.1

func (i *Error) AddModel(model string) *Error

func (*Error) BindResponse added in v1.4.1

func (i *Error) BindResponse() (int, interface{})

func (*Error) Error added in v1.4.1

func (i *Error) Error() string

func (*Error) Log added in v1.4.1

func (i *Error) Log() string

func (*Error) MongoResponse added in v1.4.1

func (i *Error) MongoResponse() (int, interface{})

func (*Error) Print added in v1.4.1

func (i *Error) Print(id string)

func (*Error) Response added in v1.4.1

func (i *Error) Response() (int, interface{})

MongoErrorResponseHandler handles the response for the MongoError type.

func (*Error) ValidationResponse added in v1.4.1

func (i *Error) ValidationResponse() (int, interface{})

type Filter added in v1.3.0

type Filter struct {
	Filter bson.M
}

func NewFilter added in v1.3.0

func NewFilter() *Filter

func (*Filter) Bson added in v1.3.0

func (i *Filter) Bson() bson.M

func (*Filter) Equal added in v1.3.0

func (i *Filter) Equal(key string, value string) *Filter

func (*Filter) In added in v1.3.0

func (i *Filter) In(key string, list []string) *Filter

type Handler added in v1.3.0

type Handler struct {
	Model string
}

Handler represents an network handler for echo framework

func NewHandler added in v1.3.0

func NewHandler(model string) *Handler

NewHandler creates an new `Handler`.

func (*Handler) Context added in v1.3.0

func (i *Handler) Context(next echo.HandlerFunc) echo.HandlerFunc

Conext return an function for convertion an echo.Context models to an Context model. Based on the echo.HandlerFunc.

type HydraClient added in v1.1.4

type HydraClient struct {
	Oauth2Config oauth2.Config
	Verifier     *oidc.IDTokenVerifier
}

func NewHydraClient added in v1.1.4

func NewHydraClient() (r *HydraClient)

func (*HydraClient) Callback added in v1.1.4

func (i *HydraClient) Callback(ctx context.Context, callback *Callback) (r *User, err error)

type IDjango added in v1.0.2

type IDjango struct {
	URL    string
	Key    string
	Export bool
}

Mongo represents the initial struct for an Mongo connection.

func (*IDjango) LoadEnv added in v1.0.2

func (i *IDjango) LoadEnv()

LoadEnv loads the Host and Port From .env file. Host can be set via NATS_HOST Port can be set via NATS_PORT

func (*IDjango) Post added in v1.0.2

func (i *IDjango) Post(data interface{}, path string) (err error)

type IDjangoError added in v1.0.2

type IDjangoError struct {
	Err     error       `json:"error" bson:"error"`
	Message string      `json:"message" bson:"message"`
	Code    int         `json:"code" bson:"code"`
	Body    interface{} `json:"body" bson:"body"`
	Line    int         `json:"line" bson:"line"`
	File    string      `json:"file" bson:"file"`
}

func NewIDjangoError added in v1.0.2

func NewIDjangoError(err error, code int, body interface{}) *IDjangoError

func (*IDjangoError) Error added in v1.0.2

func (i *IDjangoError) Error() string

type LinkToken added in v1.0.2

type LinkToken struct {
	ID        string   `json:"id" bson:"_id"`
	Code      string   `json:"code" bson:"code"`
	ExpiresAt int64    `json:"expires_at" bson:"expires_at"`
	Scope     string   `json:"scope" bson:"scope"`
	UserID    string   `json:"user_id" bson:"user_id"`
	Modified  Modified `json:"modified" bson:"modified"`
}

LinkToken is used for handling link with token

func NewLinkToken added in v1.0.2

func NewLinkToken(expired time.Duration, userID string, scope string) (*LinkToken, error)

NewLinkToken initial a Token with a 32bit random string Base64 encoded for Web handling. Set expired time max 1 month.

func (*LinkToken) NewCode added in v1.0.2

func (l *LinkToken) NewCode(expired time.Duration) (*LinkToken, error)

NewCode generate a new code for LinkTokens

type LoadEnv added in v0.1.1

type LoadEnv []bool

LoadEnv used for loading environment variables.

func LoadConfig added in v1.0.2

func LoadConfig() *LoadEnv

LoadConfig loads the .env file and return an LoadEnv type

func (LoadEnv) GetEnvBool added in v0.1.1

func (l LoadEnv) GetEnvBool(key string, lvl string, dVal bool) bool

GetEnvBool load a key from environment variables as bool.

func (LoadEnv) GetEnvInt added in v0.1.1

func (l LoadEnv) GetEnvInt(key string, lvl string, dVal int) int

GetEnvInt loads a key from enviroment variables as int. The lvl param defines the log level. For warnings set "w" and for error set "e". If the variable is not used or can be ignored use n for do nothing. The default value can be set by the dVal param.

func (LoadEnv) GetEnvString added in v0.1.1

func (l LoadEnv) GetEnvString(key string, lvl string, dVal string) string

GetEnvString loads a key from enviroment variables as string. The lvl param defines the log level. For warnings set "w" and for error set "e". If the variable is not used or can be ignored use n for do nothing. The default value can be set by the dVal param.

func (LoadEnv) GetEnvStringList added in v0.1.1

func (l LoadEnv) GetEnvStringList(key string, lvl string, dVal []string) []string

GetEnvStringList as

func (LoadEnv) Validate added in v0.1.1

func (l LoadEnv) Validate()

Validate check if LoadEnv is valid and log.Fatal if on entry is false.

type LogError added in v1.0.2

type LogError struct {
	ID           string      `json:"id" bson:"_id"`
	Time         string      `json:"time" bson:"time"`
	RemoteIP     string      `json:"remote_ip" bson:"remote_ip"`
	Host         string      `json:"host" bson:"host"`
	Method       string      `json:"method" bson:"method"`
	Uri          string      `json:"uri" bson:"uri"`
	UserAgent    string      `json:"user_agent" bson:"user_agent"`
	Status       int         `json:"status" bson:"status"`
	Error        interface{} `json:"error" bson:"error"`
	Latency      int64       `json:"latency" bson:"latency"`
	LatencyHuman string      `json:"latency_human" bson:"latency_human"`
}

LogError represents the an LogError for handling via nats and store into mongo databases. The struct matches the Config Format string as json.

type LoggingHandler added in v1.0.2

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

Logger struct for handling the nats connection.

func NewLoggingHandler added in v1.2.9

func NewLoggingHandler(service string) *LoggingHandler

func (*LoggingHandler) Init added in v1.1.2

func (i *LoggingHandler) Init(service string) echo.MiddlewareFunc

Config for echo middleware Logger. Use logger for handle Nats connection.

func (*LoggingHandler) Log added in v1.0.2

func (i *LoggingHandler) Log(logError *LogError)

Log publish the LogError to nats route "logger.log".

func (*LoggingHandler) New added in v1.2.9

func (i *LoggingHandler) New(method string, uri string, err error) *LogError

func (*LoggingHandler) Write added in v1.0.2

func (i *LoggingHandler) Write(data []byte) (n int, err error)

Write is an IOWriter for handling the middleware Logger output.

type MailData added in v1.1.6

type MailData struct {
	TO          string    `json:"to" bson:"to"`
	Service     string    `json:"service" bson:"service"`
	Scope       string    `json:"scope" bson:"scope"`
	Lang        string    `json:"lang" bson:"lang"`
	User        User      `json:"user" bson:"user"`
	LinkToken   LinkToken `json:"link_token" bson:"link_token"`
	CurrentUser MailUser  `json:"current_user" bson:"current_user"`
	ContactUser MailUser  `json:"contact_user" bson:"contact_user"`
}

func NewMailData added in v1.1.6

func NewMailData(to string, service string, scope string, lang string) *MailData

func (*MailData) AddContactUser added in v1.2.3

func (i *MailData) AddContactUser(id string, email string, firstName string, lastName string)

func (*MailData) AddCurrentUser added in v1.2.3

func (i *MailData) AddCurrentUser(id string, email string, firstName string, lastName string)

func (*MailData) AddLinkToken added in v1.1.6

func (i *MailData) AddLinkToken(token *LinkToken)

func (*MailData) AddUser added in v1.1.6

func (i *MailData) AddUser(user *User)

func (*MailData) Send added in v1.1.6

func (i *MailData) Send() (err error)

type MailSend added in v1.1.14

type MailSend struct {
	URL  string
	Key  string
	Mode string
}

func NewMailSend added in v1.1.14

func NewMailSend() *MailSend

func (*MailSend) Nats added in v1.1.14

func (i *MailSend) Nats(mail *MailData)

func (*MailSend) Post added in v1.1.14

func (i *MailSend) Post(mailData *MailData)

func (*MailSend) PostCycularMail added in v1.2.4

func (i *MailSend) PostCycularMail(data *CycularMail)

func (*MailSend) Print added in v1.1.14

func (i *MailSend) Print(mail *MailData)

func (*MailSend) Send added in v1.1.14

func (i *MailSend) Send(mail *MailData)

func (*MailSend) Subscribe added in v1.1.14

func (i *MailSend) Subscribe()

type MailUser added in v1.2.3

type MailUser struct {
	ID        string `json:"id"`
	Email     string `json:"email"`
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
}

type Modified

type Modified struct {
	Updated int64 `json:"updated" bson:"updated"`
	Created int64 `json:"created" bson:"created"`
}

Modified contains update and create time for an model

func NewModified added in v1.1.2

func NewModified() Modified

NewModified initial Modified model.

func (*Modified) Update added in v1.1.2

func (i *Modified) Update()

Update updates the Updated key to the current time.

type Money added in v1.0.3

type Money struct {
	Amount   int64  `bson:"amount" json:"amount" validate:"required"`
	Currency string `bson:"currency" json:"currency" validate:"required"`
}

func (*Money) ValidateAmount added in v1.0.3

func (i *Money) ValidateAmount(minAmount int64) (err error)

func (*Money) ValidateCurrency added in v1.0.3

func (i *Money) ValidateCurrency(currency string) (err error)

type MongoColl added in v1.0.5

type MongoColl struct {
	Name         string
	DatabaseName string
	Collection   *mongo.Collection
}

MongoColl represents an mongo db database collection

func (*MongoColl) Aggregate added in v1.0.5

func (i *MongoColl) Aggregate(ctx context.Context, filter []bson.D, value interface{}) (err error)

Aggregate provide using aggregations.

func (*MongoColl) CreateIndex added in v1.0.5

func (i *MongoColl) CreateIndex(field string, unique bool) *MongoColl

CreateIndex creates an index for a given collection.

func (*MongoColl) CreateMultiIndex added in v1.1.10

func (i *MongoColl) CreateMultiIndex(filter bson.D, unique bool) *MongoColl

func (*MongoColl) DeleteMany added in v1.1.16

func (i *MongoColl) DeleteMany(ctx context.Context, filter bson.M) (err error)

func (*MongoColl) DeleteOne added in v1.0.5

func (i *MongoColl) DeleteOne(ctx context.Context, filter bson.M) (err error)

DeleteOne deletes an element from given collection by the bson.M filter.

func (*MongoColl) Find added in v1.0.5

func (i *MongoColl) Find(ctx context.Context, filter bson.M, value interface{}) (err error)

Find return a list of objects by given filter

func (*MongoColl) FindOne added in v1.0.5

func (i *MongoColl) FindOne(ctx context.Context, filter bson.M, value interface{}) (err error)

FindOne select an element form database by using a given filter. The element will bind to the value interface{}. In error case it return an MongoError as error.

func (*MongoColl) InsertMany added in v1.2.9

func (i *MongoColl) InsertMany(ctx context.Context, value []interface{}) (err error)

InsertMany inserts a list of value and return an MongoError as error.

func (*MongoColl) InsertOne added in v1.0.5

func (i *MongoColl) InsertOne(ctx context.Context, value interface{}) (err error)

InsertOne inserts a value and return an MongoError as error.

func (*MongoColl) InsertOrUpdate added in v1.1.2

func (i *MongoColl) InsertOrUpdate(ctx context.Context, filter bson.M, value interface{}) (err error)

InsertOrUpdate updates a value via "$set" and the given bson.M filter. Return an MongoError in case that no element has updated.

func (*MongoColl) Permission added in v1.1.13

func (i *MongoColl) Permission(ctx context.Context, filter bson.M, value interface{}) (err error)

func (*MongoColl) Update added in v1.2.9

func (i *MongoColl) Update(ctx context.Context, filter bson.M, value bson.M) (err error)

Update updates a value via "$set" and the given bson.M filter. Return an MongoError in case that no element has updated.

func (*MongoColl) UpdateMany added in v1.2.9

func (i *MongoColl) UpdateMany(ctx context.Context, filter bson.A, value bson.M) (err error)

func (*MongoColl) UpdateOne added in v1.0.5

func (i *MongoColl) UpdateOne(ctx context.Context, filter bson.M, value bson.M) (err error)

UpdateOne updates a value via bson.M and the given bson.M filter. Return an MongoError in case that no element has updated.

func (*MongoColl) UpdateOneSet added in v1.3.1

func (i *MongoColl) UpdateOneSet(ctx context.Context, filter bson.M, value interface{}) (err error)

UpdateOneSet updates a value via "$set" and the given bson.M filter. Return an MongoError in case that no element has updated.

type MongoConfictError added in v1.2.10

type MongoConfictError struct {
	Key string `json:"key" bson:"value"`
}

type MongoDB added in v1.0.5

type MongoDB struct {
	Host     string
	Port     string
	Name     string
	Database *mongo.Database
}

Mongo represents the initial struct for an Mongo connection.

func NewMongoDB added in v1.0.5

func NewMongoDB(name string) (r *MongoDB)

NewMongoDB creates a new MongoDB connects to mongoDB and return an Mongo struct.

func (*MongoDB) Collection added in v1.0.5

func (i *MongoDB) Collection(name string) *MongoColl

type MongoError added in v1.0.2

type MongoError struct {
	ErrorType  string      `json:"error_type" bson:"error_type"`
	Err        error       `json:"-" bson:"-"`
	Message    string      `json:"message" bson:"message"`
	Filter     interface{} `json:"filter" bson:"filter"`
	Value      interface{} `json:"value" bson:"value"`
	Database   string      `json:"database" bson:"database"`
	Collection string      `json:"collection" bson:"collection"`
	Line       int         `json:"line" bson:"line"`
	File       string      `json:"file" bson:"file"`
}

MongoError represents the struct of an mongo Error type.

func NewMongoError added in v1.0.2

func NewMongoError(err error, value interface{}, filter bson.M, database string, collection string) *MongoError

NewMongoError creates an mongo Error for an given parameter set

func (*MongoError) Error added in v1.0.2

func (i *MongoError) Error() string

Error return string of the error

type MongoFilter added in v1.2.11

type MongoFilter struct {
	Filter bson.M
}

func NewMongoFilter added in v1.2.11

func NewMongoFilter() *MongoFilter

func (*MongoFilter) Equal added in v1.2.11

func (i *MongoFilter) Equal(key string, value string) *MongoFilter

func (*MongoFilter) EqualIn64 added in v1.2.11

func (i *MongoFilter) EqualIn64(key string, value string)

func (*MongoFilter) EqualInt added in v1.2.11

func (i *MongoFilter) EqualInt(key string, value string)

func (*MongoFilter) GteInt added in v1.2.11

func (i *MongoFilter) GteInt(key string, value string)

func (*MongoFilter) GteInt64 added in v1.2.11

func (i *MongoFilter) GteInt64(key string, value string)

func (*MongoFilter) Like added in v1.2.11

func (i *MongoFilter) Like(key string, value string)

func (*MongoFilter) LteInt added in v1.2.11

func (i *MongoFilter) LteInt(key string, value string)

func (*MongoFilter) LteInt64 added in v1.2.11

func (i *MongoFilter) LteInt64(key string, value string)

type MongoMatch added in v1.2.4

type MongoMatch bson.D

func NewMongoMatch added in v1.2.6

func NewMongoMatch() *MongoMatch

NewMongoMatch creates an new MongoMatch struct.

func (*MongoMatch) ElemMatch added in v1.2.11

func (i *MongoMatch) ElemMatch(list string, key string, value string)

ElemMatch TODO

func (*MongoMatch) ElemMatchList added in v1.2.11

func (i *MongoMatch) ElemMatchList(list string, key string, value []string)

ElemMatchList TODO

func (*MongoMatch) EqualBool added in v1.2.11

func (i *MongoMatch) EqualBool(key string, value string)

EqualBool the value is a string representation of an bool. match if value is equal to the value of the key in a database entry.

func (*MongoMatch) EqualInt added in v1.2.11

func (i *MongoMatch) EqualInt(key string, value string)

EqualInt the value is an string representation of an int. match if the value is equal to the value of the given key in an database entry.

func (*MongoMatch) EqualInt64 added in v1.2.11

func (i *MongoMatch) EqualInt64(key string, value string)

EqualInt the value is an string representation of an int64. match if value is equal to the value of the key in a database entry.

func (*MongoMatch) EqualString added in v1.2.11

func (i *MongoMatch) EqualString(key string, value string)

EqualString match if value is equal to the value of the key in a database entry.

func (*MongoMatch) ExpIn added in v1.2.11

func (i *MongoMatch) ExpIn(key string, value string)

ExpIn TODO

func (*MongoMatch) GteInt added in v1.2.11

func (i *MongoMatch) GteInt(key string, value string)

func (*MongoMatch) GteInt64 added in v1.2.11

func (i *MongoMatch) GteInt64(key string, value string)

func (*MongoMatch) LikeString added in v1.2.11

func (i *MongoMatch) LikeString(key string, value string)

func (*MongoMatch) LteInt added in v1.2.11

func (i *MongoMatch) LteInt(key string, value string)

func (*MongoMatch) LteInt64 added in v1.2.11

func (i *MongoMatch) LteInt64(key string, value string)

func (*MongoMatch) StringList added in v1.2.11

func (i *MongoMatch) StringList(key string, value []string)

type MongoPipe added in v1.1.5

type MongoPipe struct {
	Pipe []bson.D
}

func NewMongoPipe added in v1.1.5

func NewMongoPipe() *MongoPipe

func (*MongoPipe) Lookup added in v1.2.11

func (i *MongoPipe) Lookup(from string, root string, child string, as string)

func (*MongoPipe) LookupUnwind added in v1.2.11

func (i *MongoPipe) LookupUnwind(from string, root string, child string, as string)

func (*MongoPipe) Match added in v1.2.11

func (i *MongoPipe) Match(m *MongoMatch)

type MongoUpdate added in v1.3.1

type MongoUpdate struct {
	Update bson.M
}

type NatsDAO added in v1.0.2

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

Nats represents the config struct for Nats service.

func (*NatsDAO) Connect added in v1.0.2

func (i *NatsDAO) Connect()

func (*NatsDAO) Publish added in v1.0.2

func (i *NatsDAO) Publish(message string, body interface{})

func (*NatsDAO) Subscribe added in v1.0.2

func (i *NatsDAO) Subscribe(message string, catch interface{})

type Position added in v1.4.0

type Position struct {
	Lat float64 `json:"lat" bson:"lat"`
	Lng float64 `json:"lng" bson:"lng"`
}

type RefreshToken added in v1.1.6

type RefreshToken struct {
	UserID string `json:"user_id"`
	jwt.StandardClaims
}

func NewRefreshToken added in v1.1.6

func NewRefreshToken(userID string) *RefreshToken

func (*RefreshToken) SignedString added in v1.1.6

func (i *RefreshToken) SignedString(secret string) (string, error)

type Response added in v1.0.3

type Response struct {
	Status  int         `json:"-"`
	Type    string      `json:"type" bson:"type"`
	Message string      `json:"message" bson:"message"`
	Model   string      `json:"model,omitempty" bson:"model,omitempty"`
	Payload interface{} `json:"payload,omitempty" bson:"payload,omitempty"`
}

Response represents the default api response struct Status defines the response status code Type defines the response type. Can be success or error Message shows action information Model shows the collection that would be attached Payload contains the response model

func NewBadRequest added in v1.2.8

func NewBadRequest(model string, message string, payload ...interface{}) *Response

func NewConflict added in v1.2.8

func NewConflict(model string, payload ...interface{}) *Response

func NewCreated added in v1.2.10

func NewCreated(model string, payload interface{}) *Response

NewCreated returns a Response model intended for a POST request that creates a model.

func NewDeleted added in v1.2.10

func NewDeleted(model string, payload interface{}) *Response

NewDeleted returns a Response model intended for a DELETE request that deletes a model.

func NewExecuted added in v1.2.10

func NewExecuted(model string, payload interface{}) *Response

func NewInternalServerError added in v1.2.10

func NewInternalServerError(model string, payload ...interface{}) *Response

func NewNotFound added in v1.2.8

func NewNotFound(model string, payload ...interface{}) *Response

func NewPermissionDenied added in v1.2.10

func NewPermissionDenied(model string, payload ...interface{}) *Response

func NewResp added in v1.2.10

func NewResp(status int, typ string, message string, model string, payload interface{}) *Response

NewResp creates new Response model.

func NewSelected added in v1.2.10

func NewSelected(model string, payload interface{}) *Response

NewSelected returns a Response model intended for a GET request that selects a model or list.

func NewUpdated added in v1.2.10

func NewUpdated(model string, payload interface{}) *Response

NewUpdated returns a Response model intended for a PUT request that updates a model.

func (*Response) Error added in v1.2.10

func (i *Response) Error() string

func (*Response) Response added in v1.2.10

func (i *Response) Response() (int, *Response)

Response returns an tuple for handling in echo.Context.JSON

type Role added in v1.1.8

type Role struct {
	ID     string `json:"id" bson:"_id"`
	Name   string `json:"name" bson:"name"`
	Label  string `json:"label" bson:"label"`
	Root   string `json:"root" bson:"root"`
	UserID string `json:"user_id" bson:"user_id"`
}

func RoleAdmin added in v1.1.8

func RoleAdmin(userID string) *Role

func RoleEmployee added in v1.1.8

func RoleEmployee(userID string) *Role

func RoleMember added in v1.1.8

func RoleMember(userID string) *Role

type RoleList added in v1.1.8

type RoleList []Role

func (*RoleList) Append added in v1.1.8

func (i *RoleList) Append(role *Role)
func (i *RoleList) Validate(roles string) bool {
	for n, _ := range *i {
		if strings.Contains(roles, (*i)[n].Name) {
			return true
		}
	}
	return false
}
func (i *RoleList) CheckRoot(role *Role) bool {
	for n, _ := range *i {
		if strings.Contains(role.Root, (*i)[n].Name) {
			return true
		}
	}
	return false
}

func (*RoleList) Cookie added in v1.2.2

func (i *RoleList) Cookie() (r *RoleListCookie)

func (*RoleList) In added in v1.1.8

func (i *RoleList) In(roles string) bool

type RoleListCookie added in v1.2.2

type RoleListCookie []string

func (*RoleListCookie) CheckRoot added in v1.2.2

func (i *RoleListCookie) CheckRoot(role *Role) bool

func (*RoleListCookie) Validate added in v1.2.2

func (i *RoleListCookie) Validate(roles string) bool

type SettingType added in v1.4.0

type SettingType struct {
	Error []bool
}

func SettingTypeLoad added in v1.4.0

func SettingTypeLoad() *SettingType

func (*SettingType) Bool added in v1.4.0

func (i *SettingType) Bool(key string, lvl string, dVal bool) bool

func (*SettingType) BoolEnv added in v1.4.0

func (i *SettingType) BoolEnv(key string, lvl string, dVal bool) bool

GetEnvBool load a key from environment variables as bool.

func (*SettingType) Int added in v1.4.0

func (i *SettingType) Int(key string, lvl string, dVal int) int

func (*SettingType) IntEnv added in v1.4.0

func (i *SettingType) IntEnv(key string, lvl string, dVal int) int

func (*SettingType) String added in v1.4.0

func (i *SettingType) String(key string, lvl string, dVal string) string

func (*SettingType) StringEnv added in v1.4.0

func (i *SettingType) StringEnv(key string, lvl string, dVal string) string

func (*SettingType) StringList added in v1.4.0

func (i *SettingType) StringList(key string, lvl string, dVal []string) []string

func (*SettingType) StringListEnv added in v1.4.0

func (i *SettingType) StringListEnv(key string, lvl string, dVal []string) []string

GetEnvStringList as

type User

type User struct {
	ID            string   `json:"id,omitempty" bson:"_id"`
	Email         string   `json:"email" bson:"email"`
	FirstName     string   `bson:"first_name" json:"first_name"`
	LastName      string   `bson:"last_name" json:"last_name"`
	FullName      string   `bson:"full_name" json:"full_name"`
	DisplayName   string   `bson:"display_name" json:"display_name"`
	Roles         RoleList `json:"system_roles" bson:"system_roles"`
	Country       string   `bson:"country" json:"country"`
	PrivacyPolicy bool     `bson:"privacy_policy" json:"privacy_policy"`
	Confirmd      bool     `bson:"confirmed" json:"confirmed"`
	LastUpdate    string   `bson:"last_update" json:"last_update"`
}

User represents the user model

func (*User) CheckUpdate added in v1.1.11

func (i *User) CheckUpdate(lastUpdate string) bool

func (*User) Load added in v1.1.2

func (i *User) Load(user interface{}) (err error)

Load loads an interface in an vcago.User model

type UserClaims added in v1.1.4

type UserClaims struct {
	User User `json:"user"`
}

type ValidationError added in v1.0.2

type ValidationError struct {
	Errors []string `json:"errors"`
}

func NewValidationError added in v1.1.2

func NewValidationError(err string) *ValidationError

func (*ValidationError) Bind added in v1.0.2

func (i *ValidationError) Bind(err error)

func (*ValidationError) Error added in v1.0.2

func (i *ValidationError) Error() string

func (*ValidationError) Valid added in v1.0.2

func (i *ValidationError) Valid(err error)

type Validator added in v1.0.2

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

func NewValidator added in v1.1.2

func NewValidator() (r *Validator)

func (*Validator) Validate added in v1.0.2

func (i *Validator) Validate(valid interface{}) error

Directories

Path Synopsis
api module

Jump to

Keyboard shortcuts

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