vcago

package module
v1.5.4 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 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 = Settings.String("API_KEY", "w", "secret")

APIKey represents the api Bearer token

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

Logger is the global LoggingHandler

View Source
var Nats = new(NatsDAO)

Nats used for Nats connection

View Source
var Settings = SettingHandlerLoad()

Settings represents the global SettingType variable and can be used for load config parameters.

Functions

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

func HTTPErrorHandler(err error, c echo.Context)

func KeyAuthMiddleware added in v1.1.14

func KeyAuthMiddleware() echo.MiddlewareFunc

KeyAuthMiddleware middleware function for handling authentication via key.

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 RefreshCookieMiddleware added in v1.3.0

func RefreshCookieMiddleware() 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 SignedString added in v1.4.5

func SignedString(token jwt.Claims) (string, error)

func SliceContains added in v1.1.6

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

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         vmod.RoleListCookie `json:"system_roles"`
	Country       string              `json:"country"`
	PrivacyPolicy bool                `json:"privacy_policy"`
	Confirmed     bool                `json:"confirmed"`
	LastUpdate    string              `json:"last_update"`
	jwt.StandardClaims
}

AccessToken represents the default access_token contains the basic user informations.

func NewAccessToken added in v1.1.6

func NewAccessToken(user *vmod.User) *AccessToken

NewAccessToken creates an new access_token from vmod.User model.

func (*AccessToken) SignedString added in v1.1.6

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

SignedString is used for Sign an accesstoken based on the secret param.

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

NewAdminRequest initial the AdminRequest model.

func (*AdminRequest) Get added in v1.2.10

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

Get provides an GET Request over the admin route. The Response model can contain an http.Error.

func (*AdminRequest) Post added in v1.3.2

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

Post posts the data via POST Request to the path using the admin route.

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(accessToken jwt.Claims, refreshToken jwt.Claims) (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 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 extends an echo.Context type. Inititial an Context for an echo.Group via echo.Group.Use(Handler.Context()). The Context model is set by the Model param of the Handler model.

Example:

func (i *ExampleHandler) Routes(group echo.Group) {
	group.Use(i.Context)
}

Echo need and function that provide an echo.Context as parameter. So you need to convert the echo.Context to an Context in a function block.

Example:

func (i *ExampleHandler) Create(cc echo.Context) (err error) {
	c := cc.(vcago.Context)
	...
}

func (*Context) AccessToken added in v1.3.0

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

AccessToken binds the accessToken form an cookie into the token interface. The token needs to extends jwt.StandardClaims.

func (*Context) BadRequest added in v1.4.11

func (i *Context) BadRequest(message string, payload interface{}) (err error)

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) BindFormDataAndValidate added in v1.4.45

func (i *Context) BindFormDataAndValidate(key string, body interface{}) error

BindFormDataAndValidate

func (*Context) BindFormDataFile added in v1.4.45

func (i *Context) BindFormDataFile(key string) (file *vmod.File, err error)

func (*Context) Created added in v1.3.0

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

Created returns an Created response.

Status: 201 Created

JSON: model == "example"

{
	"type": "success",
	"message": "successfully_created",
	"model": "example",
	"payload": payload
}

func (*Context) Ctx added in v1.3.0

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

Ctx return echo.Context.Context().

func (*Context) Deleted added in v1.3.0

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

Deleted returns an Deleted response.

Status: 200 OK

JSON: model == "example"

{
	"type": "success",
	"message": "successfully_deleted",
	"model": "example",
	"payload": payload
}

func (*Context) ErrorResponse added in v1.4.0

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

ErrorResonse match the error and returns the correct error response.

Error: mongo.IsDuplicateKeyError

Status: 409 Conflict

JSON:

{
	"type": "error",
	"message": "duplicate_key_error",
	"model": model,
	"payload": key from error
}

Error: mongo.ErrNoDocument

Status: 404 Not Found

JSON:

{
	"type": "error",
	"message": "not_found",
	"model": model
}

Error: default

Status: 500 Internal Server Error

JSON:

{
	"type": "error",
	"message": "internal_server_error",
	"model": model
}

func (*Context) Listed added in v1.3.0

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

Listed return an List response.

Status: 200 OK

JSON: model == "example"

{
	"type": "success",
	"message": "successfully_selected",
	"model": "example_list",
	"payload": payload,
    "list_size": listSize
}

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) RefreshTokenID added in v1.4.5

func (i *Context) RefreshTokenID() (string, error)

RefreshToken returns the user id of an refresh token.

func (*Context) Selected added in v1.3.0

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

Selected returns an Selected response.

Status: 200 OK

JSON: model == "example"

{
	"type": "success",
	"message": "successfully_selected",
	"model": "example",
	"payload": payload
}

func (*Context) SuccessResponse added in v1.4.0

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

SuccessResponse returns an new success 200 OK response with an custom message string.

Status: 200 OK

JSON: model == "example"

{
	"type": "success",
	"message": message,
	"model": "example",
	"payload": payload
}

func (*Context) Updated added in v1.3.0

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

Updated returns an Updated response

Status: 200 OK

JSON: model == "example"

{
	"type": "success",
	"message": "successfully_updated",
	"model": "example",
	"payload": payload
}

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 NewError added in v1.4.4

func NewError(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 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 *vmod.User, 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

func (*IDjangoError) Log added in v1.4.4

func (i *IDjangoError) Log() string

type IDjangoHandler added in v1.4.4

type IDjangoHandler struct {
	URL    string
	Key    string
	Delay  int
	Export bool
}

Mongo represents the initial struct for an Mongo connection.

func NewIDjangoHandler added in v1.4.4

func NewIDjangoHandler() *IDjangoHandler

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

func (*IDjangoHandler) Post added in v1.4.4

func (i *IDjangoHandler) Post(data interface{}, path string, sleep ...bool) (err error)

func (*IDjangoHandler) Put added in v1.4.43

func (i *IDjangoHandler) Put(data interface{}, path string, sleep ...bool) (err error)

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  vmod.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 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
}

LoggingHandler represents a struct for handling response logging.

func (*LoggingHandler) Init added in v1.1.2

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

Init initial the config for echo middleware Logger.

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"`
	Name        string       `json:"name" bson:"name"`
	Scope       string       `json:"scope" bson:"scope"`
	Lang        string       `json:"lang" bson:"lang"`
	User        vmod.User    `json:"user" bson:"user"`
	Content     vmod.Content `json:"content" bson:"content"`
	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, name 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) AddContent added in v1.4.35

func (i *MailData) AddContent(content *vmod.Content)

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 *vmod.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 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) Request added in v1.4.39

func (i *NatsDAO) Request(message string, request interface{}, response interface{}) (err error)

func (*NatsDAO) Subscribe added in v1.0.2

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

type NotificationData added in v1.4.37

type NotificationData 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"`
	Name         string       `json:"name" bson:"name"`
	Content      vmod.Content `json:"content" bson:"content"`
	User         vmod.User    `json:"user" bson:"user"`
	OriginUserID string       `json:"origin_user_id" bson:"origin_user_id"`
}

func NewMNotificationData added in v1.4.37

func NewMNotificationData(to string, service string, name string, scope string, lang string, user_id string) *NotificationData

func (*NotificationData) AddContent added in v1.4.37

func (i *NotificationData) AddContent(content *vmod.Content)

func (*NotificationData) AddUser added in v1.4.37

func (i *NotificationData) AddUser(user *vmod.User)

func (*NotificationData) Response added in v1.4.37

func (i *NotificationData) Response() *NotificationResponse

type NotificationResponse added in v1.4.37

type NotificationResponse 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"`
	Name         string       `json:"name" bson:"name"`
	Content      vmod.Content `json:"content" bson:"content"`
	User         vmod.User    `json:"user" bson:"user"`
	OriginUserID string       `json:"origin_user_id" bson:"origin_user_id"`
	From         string       `json:"from" bson:"from"`
	Subject      string       `json:"subject" bson:"subject"`
	Body         string       `json:"body" bson:"body"`
}

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

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"`
	ListSize int64       `json:"list_size,omitempty" bson:"list_size,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

NewBadRequest returns an Response model intended for an bad request response.

Status: 400 Bad Request

JSON with payload:

{
	"type": "error",
	"message": message,
	"model": model,
	"payload": payload
}

JSON without payload:

{
	"type": "error",
	"message": message,
	"model": model,
}

func NewConflict added in v1.2.8

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

NewConflict returns an Response model intended for an conflict error response.

Status: 409 Conflict

JSON with payload:

{
	"type": "error",
	"message": "conflict",
	"model": model,
	"payload": payload
}

JSON without payload:

{
	"type": "error",
	"message": "conflict",
	"model": model
}

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.

Status: 201 Created

JSON:

{
	"type": "success",
	"message": "successfully_created",
	"model": model,
	"payload": payload
}

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.

Status: 200 OK

JSON:

{
	"type": "success",
	"message": "successfully_deleted",
	"model": model,
	"payload": payload
}

func NewExecuted added in v1.2.10

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

NewExecuted returns an Response model intended for a request that execute an process.

Status: 200 OK

JSON:

{
	"type": "success",
	"message": "successfully_executed",
	"model": model,
	"payload": payload
}

func NewInternalServerError added in v1.2.10

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

NewInternalServerError returns an Response model intended for an internal server error response. The payload param is optional.

Status: 500 Internal Server Error

JSON with payload:

{
	"type": "error",
	"message": "internal_server_error",
	"model": model,
	"payload": payload
}

JSON without payload:

{
	"type": "error",
	"message": "internal_server_error",
	"model": model
}

func NewListed added in v1.4.26

func NewListed(model string, payload interface{}, listSize int64) *Response

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

Status: 200 OK

JSON:

	{
		"type": "success",
		"message": "successfully_selected",
		"model": model,
		"payload": payload,
     "list_size": listSize
	}

func NewNotFound added in v1.2.8

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

NewNotFound returns an Response model intended for an not found error response.

Status: 404 Not Found

JSON with payload:

{
	"type": "error",
	"message": "not_found",
	"model": model,
	"payload": payload
}

JSON without payload:

{
	"type": "error",
	"message": "not_found",
	"model": model
}

func NewPermissionDenied added in v1.2.10

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

NewPermissionDenied returns an Response model intended for an permission denied error response.

Status: 400 Bad Request

JSON with payload:

{
	"type": "error",
	"message": "permission_denied",
	"model": model,
	"payload": payload
}

JSON without payload:

{
	"type": "error",
	"message": "permission_denied",
	"model": model
}

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.

Status: 200 OK

JSON:

{
	"type": "success",
	"message": "successfully_selected",
	"model": model,
	"payload": payload
}

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.

Status: 200 OK

JSON:

{
	"type": "success",
	"message": "successfully_updated",
	"model": model,
	"payload": payload
}

func (*Response) Error added in v1.2.10

func (i *Response) Error() string

Error implements an error interface for handling Responses as Error. The function returns an json.Marshal of the error as string.

func (*Response) Response added in v1.2.10

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

Response returns an tuple that can be used with echo.Context.JSON.

type Server added in v1.4.6

type Server struct {
	echo.Echo
}

Server represents an echo.Echo interface.

func NewServer added in v1.4.6

func NewServer() *Server

NewServer

func (*Server) Run added in v1.4.6

func (i *Server) Run()

Run starts the echo.Echo server on default port 1323. Use the APP_PORT param for set an custom port.

type SettingHandler added in v1.4.6

type SettingHandler struct {
	Error  []bool
	Config map[string]interface{}
}

SettingHandler represents and handler for load Settings via flag or environment variable.

func SettingHandlerLoad added in v1.4.6

func SettingHandlerLoad() *SettingHandler

SettingHandlerLoad loads all variables form an .env file and return an SettingHandler.

func (*SettingHandler) Bool added in v1.4.6

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

func (*SettingHandler) Int added in v1.4.6

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

func (*SettingHandler) Load added in v1.4.6

func (i *SettingHandler) Load()

func (*SettingHandler) String added in v1.4.6

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

String loads an string config variable. The function will first looking for an flag, than the environment variables and as default dVal.

func (*SettingHandler) StringList added in v1.4.6

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

type Test added in v1.4.6

type Test struct {
	Server Server
}

func NewTest added in v1.4.6

func NewTest(server *Server) *Test

func (*Test) DELETEContext added in v1.4.6

func (i *Test) DELETEContext(data string, rec *httptest.ResponseRecorder, token *jwt.Token) Context

func (*Test) GETByIDContext added in v1.4.6

func (i *Test) GETByIDContext(data string, rec *httptest.ResponseRecorder, token *jwt.Token) Context

func (*Test) GETContext added in v1.4.6

func (i *Test) GETContext(data string, rec *httptest.ResponseRecorder, token *jwt.Token) Context

func (*Test) POSTContext added in v1.4.6

func (i *Test) POSTContext(data string, rec *httptest.ResponseRecorder, token *jwt.Token) Context

func (*Test) PUTContext added in v1.4.6

func (i *Test) PUTContext(data string, rec *httptest.ResponseRecorder, token *jwt.Token) Context

type UserClaims added in v1.1.4

type UserClaims struct {
	User vmod.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
Package vmdb
Package vmdb

Jump to

Keyboard shortcuts

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