vcago

package module
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2022 License: MIT Imports: 27 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

View Source
const StatusCREATED = "created"
View Source
const StatusDONE = "done"
View Source
const StatusFAILED = "failed"
View Source
const StatusINTERNAL = "internal_error"
View Source
const StatusOPEN = "open"
View Source
const StatusPROCESS = "process"

Variables

View Source
var CORS = new(CORSConfig)
View Source
var Config = LoadConfig()
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 HTTPBaseCookie http.Cookie

HTTPBaseCookie defines the base cookie setup for vcago

View Source
var JSONValidator = NewValidator()
View Source
var Nats = new(NatsDAO)
View Source
var NatsHost string

NatsHost is the ip of the nats service.

View Source
var NatsPort string

NatsPort is the port ot the nats service.

Functions

func BindAndValidate added in v1.0.2

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

func HTTPErrorHandler added in v1.0.2

func HTTPErrorHandler(err error, c echo.Context)

HTTPErrorHandler handles echo.HTTPError and return the correct response.

func MongoNoDocuments added in v1.1.2

func MongoNoDocuments(err error) bool

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

Types

type Avatar

type Avatar struct {
	URL  string `bson:"url" json:"url"`
	Type string `bson:"type" json:"type"`
}

Avatar contains the link and picturetype of the user avatar

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 ErrorResponse added in v1.0.2

type ErrorResponse struct {
	Status  int         `json:"-"`
	Message string      `json:"message"`
	Body    interface{} `json:"body,omitempty"`
	Coll    string      `json:"collection,omitempty"`
	Model   string      `json:"model,omitempty"`
}

Response represents an response json in case of an error.

func BadRequest added in v1.0.2

func BadRequest(message string, body ...interface{}) (int, *ErrorResponse)

BadRequest creates an echo.HTTPError with the status http.StatusBadRequest

func Conflict added in v1.0.2

func Conflict(message string, body ...interface{}) (int, *ErrorResponse)

Conflict creates an echo.HTTPError with the status http.StatusConflict

func InternalServerError added in v1.0.2

func InternalServerError() (int, ErrorResponse)

InternalServerError creates an echo.HTTPError with the status http.StatusInternalServerError

func NotFound added in v1.0.2

func NotFound(message string, body ...interface{}) (int, *ErrorResponse)

NotFound creates an echo.HTTPError with the status http.StatusNotFound

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 `bson:"_id" json:"token_id"`
	Code    string `bson:"code" json:"code"`
	Tcase   string `json:"t_case"`
	Scope   string `json:"scope"`
	Expired int64  `json:"expired"`
	Created int64  `json:"created"`
	ModelID string `json:"model_id" bson:"model_id"`
}

LinkToken is used for handling link with token

func NewLinkToken added in v1.0.2

func NewLinkToken(tCase string, expired time.Duration, modelID 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

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"`
	Service      string      `json:"service" bson:"service"`
	Time         string      `json:"time" bson:"time"`
	RemoteIP     string      `json:"remote_ip" bson:"remote_io"`
	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"`
	ByteIn       string      `json:"byte_in" bson:"byte_in"`
	ByteOut      string      `json:"byte_out" bson:"byte_out"`
	Modified     Modified    `json:"modified" bson:"modified"`
}

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 (*LoggingHandler) Init added in v1.1.2

func (i *LoggingHandler) Init() 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) 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 Modified

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

func NewModified added in v1.1.2

func NewModified() Modified

NewModified initial Modified model, cTime is the current time Unix format.

func (*Modified) Update added in v1.1.2

func (i *Modified) Update()

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) 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) 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) UpdateOne added in v1.0.5

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

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

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() (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 {
	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

func (*MongoError) Response added in v1.0.2

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

Response return the ErrorResponse for handling in httpErrorHandler

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() (r *NatsDAO)

func (*NatsDAO) LoadEnv added in v1.0.2

func (i *NatsDAO) LoadEnv() *NatsDAO

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 Profile

type Profile struct {
	FirstName   string `bson:"first_name" json:"first_name" validate:"required"`
	LastName    string `bson:"last_name" json:"last_name" validate:"required"`
	FullName    string `bson:"full_name" json:"full_name"`
	DisplayName string `bson:"display_name" json:"display_name"`
	Gender      string `bson:"gender" json:"gender"`
	Country     string `bson:"country" json:"country"`
	Avatar      Avatar `bson:"avatar" json:"avatar"`
}

Profile contains the profile information of an user model

type Response added in v1.0.3

type Response struct {
	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 Message shows action information Model shows the collection that would be attached Payload contains the response model

func NewResponse added in v1.0.3

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

NewResponse can be used for create Response struct

func (*Response) BadRequest added in v1.1.2

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

func (*Response) Conflict added in v1.1.2

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

func (*Response) Created added in v1.0.3

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

func (*Response) Deleted added in v1.0.3

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

func (*Response) Executed added in v1.0.3

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

func (*Response) InternalServerError added in v1.1.2

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

func (*Response) NotFound added in v1.1.2

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

func (*Response) Selected added in v1.0.3

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

func (*Response) Updated added in v1.0.3

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

type Status added in v1.0.3

type Status struct {
	StatusType    string `bson:"status_type" json:"status_type"`
	StatusMessage string `bson:"status_message" json:"status_message"`
}

func NewStatus added in v1.0.3

func NewStatus() *Status

func NewStatusInternal added in v1.0.3

func NewStatusInternal(message error) *Status

func (*Status) Created added in v1.0.3

func (i *Status) Created(message string)

func (*Status) Done added in v1.0.3

func (i *Status) Done(message string)

func (*Status) Error added in v1.0.3

func (i *Status) Error() string

func (*Status) Failed added in v1.0.3

func (i *Status) Failed(message string)

func (*Status) Internal added in v1.0.3

func (i *Status) Internal(message string)

func (*Status) Open added in v1.0.3

func (i *Status) Open(message string)

func (*Status) Process added in v1.0.3

func (i *Status) Process(message string)

func (*Status) Response added in v1.0.3

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

func (*Status) Set added in v1.0.3

func (i *Status) Set(t string, message string) *Status

func (*Status) ValidateDone added in v1.0.3

func (i *Status) ValidateDone() error

type User

type User struct {
	ID      string  `json:"id,omitempty" bson:"_id"`
	Email   string  `json:"email" bson:"email" validate:"required,email"`
	Profile Profile `json:"profile" bson:"profile"`
	Roles   string  `json:"roles" bson:"roles"`
}

User represents the user model

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) Response added in v1.0.3

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

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