hexa

package module
v0.0.0-...-ccd401e Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2020 License: MIT Imports: 9 Imported by: 0

README

Hexa contain services kit.

Note : Hexa is in progress and does not have any stable release.

Requirements:

go : minimum version 1.13

Install

go get github.com/Kamva/hexa

Available Services:

  • Config: config service.
  • Logger: logger service
  • Translator: translator service.

How to use:

example:

// Assume we want to use viper as config service.
v := viper.New()

// tune your viper.
config := hexaconfig.NewViperDriver(v)

// Use config service in app.

Proposal

  • Replace http status code with gRPC status code in our errors (also maybe in replies).

  • We should implement Distributed tracing by using zipkin and open tracing and also use it in gRPC,... . but I think this should be in the service mesh not in the business logic.

  • Implement a service (e.g Ping) which should implement by all of the Hexa services to check health of that service [Accepted].

Todo

  • Where we are checking log level on logger initialization step?
  • Change all of kamva packages from uppercase to lowercase.
  • Write Tests
  • Add badges to readme.
  • CI

Client conventions:

  • on occure error and want to say to user that "some error occured", give the requestID to the user, then user can give it back to the support team, and support team can see logs relative to that request id.

Documentation

Index

Constants

View Source
const (
	// ErrorKeyInternalError is the internal error key in Error
	// messages over all of packages. use this to have just one
	// internal_error translation key in your translation system.
	ErrKeyInternalError = "err_internal_error"
)
View Source
const LogConfigLevel = "log.level"

LogConfigLevel is the config key to say that level of log should use. you can using it to detect the generic log level of the package.

View Source
const TranslateKeyEmptyMessage = "__empty_message__"

TranslateKeyEmptyMessage is special key that translators return empty string for that.

View Source
const (
	Version = "1.1.0"
)

Version is Hexa current version.

Variables

View Source
var (
	ErrInvalidID = NewError(http.StatusBadRequest, "hx.ett.e.0", "err_invalid_id", errors.New("id value is invalid"))
)

Functions

func PrintBanner

func PrintBanner(banner, product, version, website string)

PrintBanner print the app's banner

Types

type Config

type Config interface {
	// Unmarshal function load viperDriver into viperDriver instance. pass instance by reference.
	Unmarshal(configInstance interface{}) error

	// Get method return config value in any type.
	Get(key string) interface{}

	// GetString method return config value as string
	GetString(key string) string

	// GetInt64 return int64 config value.
	GetInt64(key string) int64

	// GetFloat64 return float64 config value.
	GetFloat64(key string) float64

	// GetBool return bool config value.
	GetBool(key string) bool

	// GetList return config value as string list.
	GetList(key string) []string
}

Config is viperDriver interface that should embed in each Config object.

type Context

type Context interface {
	context.Context

	// WithUser returns new instance of context with provided user.
	WithUser(User) Context

	// Request returns the current request and can be nil for not http requests.
	Request() *http.Request

	// Correlation returns the request correlation id.
	CorrelationID() string

	// User returns the user
	User() User

	// Logger returns the hexa logger customized for specific request.
	Logger() Logger

	// Translator returns the translator localized relative to the users request.
	Translator() Translator

	// ToMap method convert context to map to export and import.
	ToMap(UserExporterImporter) (Map, error)
}

Context is the hexa context to use in services.

func NewCtx

func NewCtx(request *http.Request, correlationID string, locale string, user User, logger Logger, translator Translator) Context

NewCtx returns new hexa Context. locale syntax is just same as HTTP Accept-Language header.

type ContextExporterImporter

type ContextExporterImporter interface {
	Export(Context) (Map, error)
	Import(Map) (Context, error)
}

ContextExporterImporter export and import the context

func NewCtxExporterImporter

func NewCtxExporterImporter(ue UserExporterImporter, l Logger, t Translator) ContextExporterImporter

NewCtxExporterImporter returns new instance of the ContextExporterImporter to export and import context.

type DAO

type DAO interface {
	Map() map[string]interface{}
	Json() ([]byte, error)
	MustJson() []byte
}

DAO is the Data Access Object interface.

func NewDAO

func NewDAO(obj interface{}) DAO

NewDAO returns new instance of the DAO.

type Error

type Error interface {
	error

	// SetError set the internal error.
	SetError(error) Error

	//Is function satisfy Is interface of errors package.
	Is(error) bool

	// HTTPStatus returns the http status code for the Error.
	HTTPStatus() int

	// HTTPStatus returns the http status code for the reply.
	SetHTTPStatus(status int) Error

	// Code return the Error identifier code
	Code() string

	// Key returns unique key for each Error to use as translation key,...
	Key() string

	// Params returns params of the Error to use in translation,...
	Params() Map

	// SetParams set the Error translation parameters to use in reply translation,...
	SetParams(params Map) Error

	// Localize localize te message for you.
	// you can store the gRPC localized error
	// message and return it by this method.
	Localize(t Translator) (string, error)

	// Data returns the extra data of the Error (e.g show this data to user).
	Data() Map

	// SetData set the Error data as extra data of the Error to show to the user.
	SetData(data Map) Error

	// ReportData returns the data that should use on reporting Error to somewhere (e.g log aggregator)
	ReportData() Map

	SetReportData(data Map) Error

	// ReportIfNeeded function report the Error to the log system if
	// http status code is in range 5XX.
	// return value specify that reported or no.
	ReportIfNeeded(Logger, Translator) bool
}

Error is reply to actions when occur error in microservices.

func NewError

func NewError(httpStatus int, code string, key string, err error) Error

NewError returns new instance the Error interface.

func NewLocalizedError

func NewLocalizedError(status int, code string, localizedMsg string, err error) Error

NewError returns new instance the Error interface.

type HttpRespBody

type HttpRespBody struct {
	Code    string `json:"code" mapstructure:"code"`
	Message string `json:"message" mapstructure:"message"`
	Data    Map    `json:"data" mapstructure:"data"`
	// contains filtered or unexported fields
}

HttpRespBody is the http response body format

func NewBody

func NewBody(code string, msg string, data Map) HttpRespBody

NewBody return new instance of the HttpRespBody

func (HttpRespBody) Debug

func (b HttpRespBody) Debug(debug bool, debugData Map) HttpRespBody

Debug set debug flag and debug data.

func (HttpRespBody) MarshalJSON

func (b HttpRespBody) MarshalJSON() ([]byte, error)

MarshalJSON marshall the body to json value.

type ID

type ID interface {
	fmt.Stringer

	// Validate specify provided id is valid or not.
	Validate(id interface{}) error

	// From convert provided value to its id.
	// From will returns error if provided value
	// can not convert to an native id.
	From(id interface{}) error

	// MustFrom Same as FromString but on occur error, it will panic.
	MustFrom(id interface{})

	// Val returns the native id value (e.g ObjectID in mongo, ...).
	Val() interface{}

	// IsEqual say that two hexa id are equal or not.
	IsEqual(ID) bool
}

ID is the id of entities across the hexa packages. This is because hexa does not want to be dependent to specific type of id. (e.g mongo ObjectID, mysql integer,...)

func NewStringID

func NewStringID(id string) ID

NewStringID returns new hexa ID.

type IDGenerator

type IDGenerator func() ID

IDGenerator can generate fresh ID.

type Logger

type Logger interface {

	// Core function returns the logger core concrete struct.
	// this is because sometimes we need to convert one logger
	// interface to another and need to the concrete logger.
	Core() interface{}

	// With get the hexa context and some keyValues
	// and return new logger contains key values as
	// log fields.
	With(ctx Context, keyValues ...interface{}) Logger

	// WithFields method set key,values and return new logger
	// contains this key values as log fields.
	WithFields(keyValues ...interface{}) Logger

	// Debug log debug message.
	Debug(i ...interface{})

	// Info log info message.
	Info(i ...interface{})

	// Message log the value as a message.
	// Use this to send message to some loggers that just want to get messages.
	// all loggers see message as info and just add simple __message__ tag to it.
	// but some other loggers just log messages (like our sentry logger).
	// severity of Message it just like info.
	Message(i ...interface{})

	// Warn log warning message.
	Warn(i ...interface{})

	// Error log error message
	Error(i ...interface{})
}

type Map

type Map map[string]interface{}

Map defines a well-known Golang map: map[string]interface{}

type Reply

type Reply interface {
	// specifically this interface contains the error interface
	// also, to able pass as return value in some frameworks that
	// permit to return error and then set error handler.
	// e.g by this  way we can pass this Reply to the ErrorHandler
	// and error handler can check Reply type and return the proper
	// response.
	// in implementation of Reply we can return just empty string or
	// special value (like "__reply__") as error message.
	error

	//Is function satisfy Is interface of errors package.
	Is(error) bool

	// HTTPStatus returns the http status code for the reply.
	HTTPStatus() int

	// HTTPStatus returns the http status code for the reply.
	SetHTTPStatus(status int) Reply

	// Code return the error identifier code
	Code() string

	// Key returns unique key for each reply to use as translation key,...
	Key() string

	// Params returns params of the reply to use in translation,...
	Params() Map

	// SetParams set the reply parameters to use in reply translation,...
	SetParams(params Map) Reply

	// Data returns the extra data of the reply (e.g show this data to user).
	Data() Map

	// SetData set the reply data as extra data of the reply to show to the user.
	SetData(data Map) Reply
}

Reply is reply to actions in microservices.

func NewReply

func NewReply(httpStatus int, code string, key string) Reply

NewReply returns new instance the Reply interface implemented by defaultReply.

type Rule

type Rule func() error

Rule is a rule signature.

type RuleChecker

type RuleChecker struct{}

RuleChecker get a list of rules and check if a rule is broken, returns that rule error message. You can use rule checker in your aggregates, entities, valueObjects or services,...

func (RuleChecker) CheckRules

func (rc RuleChecker) CheckRules(rules ...Rule) error

CheckRules check rules and returns first broken rule's error. otherwise returns nil.

type Secret

type Secret string

Use secret to string show as * in fmt package.

func (Secret) MarshalJSON

func (s Secret) MarshalJSON() ([]byte, error)

func (Secret) String

func (s Secret) String() string

type Translator

type Translator interface {
	// Localize function returns new localized translator function.
	Localize(langs ...string) Translator

	// Translate get key and params nad return translation.
	Translate(key string, keyParams ...interface{}) (string, error)

	// MustTranslate get key and params and translate,
	//otherwise panic relative error.
	MustTranslate(key string, keyParams ...interface{}) string

	// TranslateDefault translate with default message.
	TranslateDefault(key string, fallback string, keyParams ...interface{}) (string, error)

	// MustTranslateDefault translate with default message, on occur error,will panic it.
	MustTranslateDefault(key string, fallback string, keyParams ...interface{}) string
}

type User

type User interface {
	// Type specifies user's type (guest,regular,...)
	Type() UserType

	// Identifier returns user's identifier
	Identifier() ID

	// Email returns the user's email.
	// This value can be empty.
	Email() string

	// Phone returns the user's phone number.
	// This value can be empty.
	Phone() string

	// Name returns the user name.
	Name() string

	// Username can be unique username,email,phone number or
	// everything else which can be used as username.
	Username() string

	// IsActive specify that user is active or no.
	IsActive() bool

	// Roles returns user's roles.
	Roles() []string
}

User who sends request to the app (can be guest,regular user,service user,...)

func NewGuest

func NewGuest() User

NewGuest returns new instance of guest user.

func NewServiceUser

func NewServiceUser(id, name string, isActive bool, roles []string) User

NewServiceUser returns new instance of Service user.

func NewUser

func NewUser(id ID, utype UserType, email, phone, name, username string, isActive bool, roles []string) User

NewUser returns new hexa user instance.

type UserExporterImporter

type UserExporterImporter interface {
	Export(user User) (Map, error)
	Import(exportedMap Map) (User, error)
}

UserExporterImporter export a user to json and then import it.

func NewUserExporterImporter

func NewUserExporterImporter(idGenerator IDGenerator) UserExporterImporter

NewUserExporterImporter returns new instance of user exporter.

type UserSDK

type UserSDK interface {
	UserExporterImporter
	// GenerateGuest returns new Guest User.
	NewGuest() User
}

UserSDK is the user's kit to import, export and generate guest.

func NewUserSDK

func NewUserSDK(ei UserExporterImporter) UserSDK

NewUserSDK returns new instance of the user SDK.

type UserType

type UserType string

UserType is type of a user. possible values is : guest: Use for guest users. regular: Use for regular users of app (real registered users) service: Use for service users (microservices,...)

const (
	UserTypeGuest   UserType = "__guest__"
	UserTypeRegular UserType = "__regular__"
	UserTypeService UserType = "__service__"
)

Directories

Path Synopsis
db
Package pagination provides support for pagination requests and responses.
Package pagination provides support for pagination requests and responses.

Jump to

Keyboard shortcuts

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