core

package
v2.7.4 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2024 License: MIT Imports: 48 Imported by: 0

Documentation

Overview

Package core provides different functions like error-reporting, logging, localization, etc. to make it easier to create transports. Usage:

package main

import (
    "os"
    "fmt"
    "html/template"

    "github.com/gin-gonic/gin"
    "github.com/retailcrm/mg-transport-core/core"
)

func main() {
    app := core.New()
    app.Config = core.NewConfig("config.yml")
    app.DefaultError = "unknown_error"
    app.TranslationsPath = "./translations"

    app.ConfigureRouter(func(engine *gin.Engine) {
        engine.Static("/static", "./static")
        engine.HTMLRender = app.CreateRenderer(
            func(renderer *core.Renderer) {
                // insert templates here. Example:
                r.Push("home", "templates/layout.html", "templates/home.html")
            },
            template.FuncMap{},
        )
    })

    if err := app.Prepare().Run(); err != nil {
        fmt.Printf("Fatal error: %s", err.Error())
        os.Exit(1)
    }
}

Resource embedding

packr can be used to provide resource embedding, see:

https://github.com/gobuffalo/packr/tree/master/v2

In order to use packr you must follow instruction, and provide boxes with templates, translations and assets to library. You can find instruction here:

https://github.com/gobuffalo/packr/tree/master/v2#library-installation

Example of usage:

package main

import (
    "os"
    "fmt"
    "html/template"
	"net/http"

    "github.com/gin-gonic/gin"
    "github.com/retailcrm/mg-transport-core/core"
)

//go:embed static
var Static fs.FS

//go:embed translations
var Translate fs.FS

//go:embed templates
var Templates fs.FS

func main() {
	staticFS, err := fs.Sub(Static, "static")
	if err != nil {
		panic(err)
	}

	translateFS, err := fs.Sub(Translate, "translate")
	if err != nil {
		panic(err)
	}

	templatesFS, err := fs.Sub(Templates, "templates")
	if err != nil {
		panic(err)
	}

    app := core.New()
    app.Config = core.NewConfig("config.yml")
    app.DefaultError = "unknown_error"
    app.TranslationsFS = translateFS

    app.ConfigureRouter(func(engine *gin.Engine) {
        engine.StaticFS("/static", http.FS(staticFS))
        engine.HTMLRender = app.CreateRendererFS(
            templatesFS,
            func(renderer *core.Renderer) {
                // insert templates here. Example:
                r.Push("home", "layout.html", "home.html")
            },
            template.FuncMap{},
        )
    })

    if err := app.Prepare().Run(); err != nil {
        fmt.Printf("Fatal error: %s", err.Error())
        os.Exit(1)
    }
}

Migration generator

This library contains helper tool for transports. You can install it via go:

$ go get -u github.com/retailcrm/mg-transport-core/cmd/transport-core-tool

Currently, it only can generate new migrations for your transport.

Copyright (c) 2019 RetailDriver LLC. Usage of this source code is governed by a MIT license.

Index

Constants

View Source
const LocalizerContextKey = "localizer"

LocalizerContextKey is a key which is used to store localizer in gin.Context key-value storage.

Variables

View Source
var DefaultHTTPClientConfig = &config.HTTPClientConfig{
	Timeout:         30,
	SSLVerification: &boolTrue,
}

DefaultHTTPClientConfig is a default config for HTTP client. It will be used by Engine for building HTTP client if HTTP client config is not present in the configuration.

View Source
var DefaultLanguage = language.English

DefaultLanguage is a base language which will be chosen if current language is unspecified.

DefaultLanguages for transports.

Functions

func DefaultLocalizerBundle

func DefaultLocalizerBundle() *i18n.Bundle

DefaultLocalizerBundle returns new localizer bundle with English as default language.

func DefaultLocalizerMatcher

func DefaultLocalizerMatcher() language.Matcher

DefaultLocalizerMatcher returns matcher with English, Russian and Spanish tags.

func GetRootLanguageTag

func GetRootLanguageTag(t language.Tag) language.Tag

GetRootLanguageTag returns root language tag for country-specific tags (e.g "es" for "es_CA"). Useful when you don't have country-specific language variations.

func LocalizerBundle

func LocalizerBundle(tag language.Tag) *i18n.Bundle

LocalizerBundle returns new localizer bundle provided language as default.

Types

type AppInfo added in v2.2.0

type AppInfo struct {
	Version   string
	Commit    string
	Build     string
	BuildDate string
}

AppInfo contains information about app version.

func (AppInfo) Release added in v2.2.0

func (a AppInfo) Release() string

Release information for Sentry.

type CloneableLocalizer added in v2.3.0

type CloneableLocalizer interface {
	Clone() CloneableLocalizer
}

CloneableLocalizer is a localizer which can clone itself.

type CrmDomains

type CrmDomains struct {
	CreateDate string   `json:"createDate"`
	Domains    []Domain `json:"domains"`
}

type Domain

type Domain struct {
	Domain string `json:"domain"`
}

func GetBoxDomains added in v2.1.0

func GetBoxDomains() []Domain

func GetSaasDomains added in v2.1.0

func GetSaasDomains() []Domain

type Engine

type Engine struct {
	AppInfo      AppInfo
	Sessions     sessions.Store
	LogFormatter logging.Formatter
	Config       config.Configuration
	Zabbix       metrics.Transport

	db.ORM
	Localizer
	util.Utils
	PreloadLanguages []language.Tag
	Sentry
	// contains filtered or unexported fields
}

Engine struct.

func New

func New(appInfo AppInfo) *Engine

New Engine instance (must be configured manually, gin can be accessed via engine.Router() directly or engine.ConfigureRouter(...) with callback).

func (*Engine) BuildHTTPClient

func (e *Engine) BuildHTTPClient(certs *x509.CertPool, replaceDefault ...bool) *Engine

BuildHTTPClient builds HTTP client with provided configuration.

func (*Engine) ConfigureRouter

func (e *Engine) ConfigureRouter(callback func(*gin.Engine)) *Engine

ConfigureRouter will call provided callback with current gin.Engine, or panic if engine is not present.

func (*Engine) CreateRenderer

func (e *Engine) CreateRenderer(callback func(*Renderer), funcs template.FuncMap) Renderer

CreateRenderer with translation function.

func (*Engine) CreateRendererFS

func (e *Engine) CreateRendererFS(
	templatesFS fs.FS,
	callback func(*Renderer),
	funcs template.FuncMap,
) Renderer

CreateRendererFS with translation function and embedded files.

func (*Engine) GenerateCSRFMiddleware

func (e *Engine) GenerateCSRFMiddleware() gin.HandlerFunc

GenerateCSRFMiddleware returns CSRF generator middleware Usage:

engine.Router().Use(engine.GenerateCSRFMiddleware())

func (*Engine) GetCSRFToken

func (e *Engine) GetCSRFToken(c *gin.Context) string

GetCSRFToken returns CSRF token from provided context.

func (*Engine) GetHTTPClientConfig

func (e *Engine) GetHTTPClientConfig() *config.HTTPClientConfig

GetHTTPClientConfig returns configuration for HTTP client.

func (*Engine) HTTPClient

func (e *Engine) HTTPClient() *http.Client

HTTPClient returns inner http client or default http client.

func (*Engine) InitCSRF

func (e *Engine) InitCSRF(
	secret string, abortFunc middleware.CSRFAbortFunc, getter middleware.CSRFTokenGetter) *Engine

InitCSRF initializes CSRF middleware. engine.Sessions must be already initialized, use engine.WithCookieStore or engine.WithFilesystemStore for that. Syntax is similar to core.NewCSRF, but you shouldn't pass sessionName, store and salt.

func (*Engine) JobManager

func (e *Engine) JobManager() *JobManager

JobManager will return singleton JobManager from Engine.

func (*Engine) Logger

func (e *Engine) Logger() logger.Logger

Logger returns current logger.

func (*Engine) Prepare

func (e *Engine) Prepare() *Engine

Prepare engine for start.

func (*Engine) Router

func (e *Engine) Router() *gin.Engine

Router will return current gin.Engine or panic if it's not present.

func (*Engine) Run

func (e *Engine) Run() error

Run gin.Engine loop, or panic if engine is not present.

func (*Engine) SetHTTPClient

func (e *Engine) SetHTTPClient(client *http.Client) *Engine

SetHTTPClient sets HTTP client to engine.

func (*Engine) SetLogger

func (e *Engine) SetLogger(l logger.Logger) *Engine

SetLogger sets provided logger instance to engine.

func (*Engine) TemplateFuncMap

func (e *Engine) TemplateFuncMap(functions template.FuncMap) template.FuncMap

TemplateFuncMap combines func map for templates.

func (*Engine) UseZabbix added in v2.6.4

func (e *Engine) UseZabbix(collectors []metrics.Collector) *Engine

func (*Engine) VerifyCSRFMiddleware

func (e *Engine) VerifyCSRFMiddleware(ignoredMethods []string) gin.HandlerFunc

VerifyCSRFMiddleware returns CSRF verifier middleware Usage:

engine.Router().Use(engine.VerifyCSRFMiddleware(core.DefaultIgnoredMethods))

func (*Engine) WithCookieSessions

func (e *Engine) WithCookieSessions(keyLength ...int) *Engine

WithCookieSessions generates new CookieStore with optional key length. Default key length is 32 bytes.

func (*Engine) WithFilesystemSessions

func (e *Engine) WithFilesystemSessions(path string, keyLength ...int) *Engine

WithFilesystemSessions generates new FilesystemStore with optional key length. Default key length is 32 bytes.

type ErrorHandlerFunc

type ErrorHandlerFunc func(recovery interface{}, c *gin.Context)

ErrorHandlerFunc will handle errors.

type HTTPResponseLocalizer added in v2.3.0

type HTTPResponseLocalizer interface {
	BadRequestLocalized(string) (int, interface{})
	UnauthorizedLocalized(string) (int, interface{})
	ForbiddenLocalized(string) (int, interface{})
	InternalServerErrorLocalized(string) (int, interface{})
}

HTTPResponseLocalizer can localize strings and return them with HTTP error codes.

type IUploader added in v2.7.3

type IUploader interface {
	Upload(
		ctx context.Context, input *s3.PutObjectInput, optFns ...func(uploader *manager.Uploader),
	) (*manager.UploadOutput, error)
}

type Job

type Job struct {
	Command      JobFunc
	ErrorHandler JobErrorHandler
	PanicHandler JobPanicHandler

	Interval time.Duration

	Regular bool
	// contains filtered or unexported fields
}

Job represents single job. Regular job will be executed every Interval.

type JobAfterCallback added in v2.7.0

type JobAfterCallback func(jobError error, log logger.Logger) error

JobAfterCallback will be called after specific job is done. This can be used to run something after asynchronous job is done. The function will receive an error from the job which can be used to alter the callback behavior. If callback returns an error, it will be processed using job ErrorHandler. The callback won't be executed in case of panic. Panicked callback will be show in logs as if the job itself panicked, ergo, do not write jobs or callbacks that can panic, or process the panic by yourself.

type JobErrorHandler

type JobErrorHandler func(string, error, logger.Logger)

JobErrorHandler is a function to handle jobs errors. First argument is a job name.

func DefaultJobErrorHandler

func DefaultJobErrorHandler() JobErrorHandler

DefaultJobErrorHandler returns default error handler for a job.

type JobFunc

type JobFunc func(logger.Logger) error

JobFunc is empty func which should be executed in a parallel goroutine.

type JobManager

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

JobManager controls jobs execution flow. Jobs can be added just for later use (e.g. JobManager can be used as singleton), or jobs can be executed as regular jobs. Example initialization:

    manager := NewJobManager().
		SetLogger(logger).
		SetLogging(false)
	_ = manager.RegisterJob("updateTokens", &Job{
		Command: func(log logger.Logger) error {
			// logic goes here...
			logger.Info("All tokens were updated successfully")
			return nil
		},
		ErrorHandler: DefaultJobErrorHandler(),
		PanicHandler: DefaultJobPanicHandler(),
		Interval:     time.Hour * 3,
		Regular:      true,
	})
	manager.Start()

func NewJobManager

func NewJobManager() *JobManager

NewJobManager is a JobManager constructor.

func (*JobManager) FetchJob

func (j *JobManager) FetchJob(name string) (value *Job, ok bool)

FetchJob fetches already exist job.

func (*JobManager) Logger

func (j *JobManager) Logger() logger.Logger

Logger returns logger.

func (*JobManager) RegisterJob

func (j *JobManager) RegisterJob(name string, job *Job) error

RegisterJob registers new job.

func (*JobManager) RunJob

func (j *JobManager) RunJob(name string) error

RunJob starts provided regular job if it's exists. It runs asynchronously and error returns only of job wasn't executed at all.

func (*JobManager) RunJobOnce

func (j *JobManager) RunJobOnce(name string, callback ...JobAfterCallback) error

RunJobOnce starts provided job once if it exists. It's also async.

func (*JobManager) RunJobOnceSync

func (j *JobManager) RunJobOnceSync(name string) error

RunJobOnceSync starts provided job once in current goroutine if job exists. Will wait for job to end it's work.

func (*JobManager) RunJobsOnceSequentially added in v2.7.0

func (j *JobManager) RunJobsOnceSequentially(names []string, stopOnError bool) error

RunJobsOnceSequentially will execute provided jobs asynchronously. It uses JobAfterCallback under the hood. You can prevent subsequent jobs from running using stopOnError flag.

func (*JobManager) SetLogger

func (j *JobManager) SetLogger(logger logger.Logger) *JobManager

SetLogger sets logger into JobManager.

func (*JobManager) SetLogging

func (j *JobManager) SetLogging(enableLogging bool) *JobManager

SetLogging enables or disables JobManager logging.

func (*JobManager) Start

func (j *JobManager) Start()

Start all jobs in the manager.

func (*JobManager) StopJob

func (j *JobManager) StopJob(name string) error

StopJob stops provided regular regular job if it's exists.

func (*JobManager) UnregisterJob

func (j *JobManager) UnregisterJob(name string) error

UnregisterJob unregisters job if it's exists. Returns error if job doesn't exist.

func (*JobManager) UpdateJob

func (j *JobManager) UpdateJob(name string, job *Job) error

UpdateJob updates job.

type JobPanicHandler

type JobPanicHandler func(string, interface{}, logger.Logger)

JobPanicHandler is a function to handle jobs panics. First argument is a job name.

func DefaultJobPanicHandler

func DefaultJobPanicHandler() JobPanicHandler

DefaultJobPanicHandler returns default panic handler for a job.

type LocaleControls added in v2.3.0

type LocaleControls interface {
	Preload([]language.Tag)
	SetLocale(string)
	SetLanguage(language.Tag)
	Language() language.Tag
	LoadTranslations()
}

LocaleControls is an instance of localizer with exposed locale controls.

type Localizer

type Localizer struct {
	TranslationsFS fs.FS

	LocaleMatcher    language.Matcher
	LanguageTag      language.Tag
	TranslationsPath string
	// contains filtered or unexported fields
}

Localizer struct.

func (*Localizer) BadRequestLocalized

func (l *Localizer) BadRequestLocalized(err string) (int, interface{})

BadRequestLocalized is same as errorutil.BadRequest(string), but passed string will be localized.

func (*Localizer) Clone

func (l *Localizer) Clone() CloneableLocalizer

Clone *core.Localizer. Clone shares it's translations with the parent localizer. Language tag will not be shared. Because of that you can change clone's language without affecting parent localizer. This method should be used when LocalizationMiddleware is not feasible (outside of *gin.HandlerFunc).

func (*Localizer) FetchLanguage deprecated

func (l *Localizer) FetchLanguage()

FetchLanguage will load language from tag

Deprecated: Use `(*core.Localizer).LoadTranslations()` instead.

func (*Localizer) ForbiddenLocalized

func (l *Localizer) ForbiddenLocalized(err string) (int, interface{})

ForbiddenLocalized is same as errorutil.Forbidden(string), but passed string will be localized.

func (*Localizer) GetLocalizedMessage

func (l *Localizer) GetLocalizedMessage(messageID string) string

GetLocalizedMessage will return localized message by it's ID. It doesn't use `Must` prefix in order to keep BC.

func (*Localizer) GetLocalizedTemplateMessage

func (l *Localizer) GetLocalizedTemplateMessage(messageID string, templateData map[string]interface{}) string

GetLocalizedTemplateMessage will return localized message with specified data. It doesn't use `Must` prefix in order to keep BC. It uses text/template syntax: https://golang.org/pkg/text/template/

func (*Localizer) InternalServerErrorLocalized

func (l *Localizer) InternalServerErrorLocalized(err string) (int, interface{})

InternalServerErrorLocalized is same as errorutil.InternalServerError(string), but passed string will be localized.

func (*Localizer) Language added in v2.3.0

func (l *Localizer) Language() language.Tag

Language returns current language tag.

func (*Localizer) LoadTranslations

func (l *Localizer) LoadTranslations()

LoadTranslations will load all translation files from translations directory or from embedded box.

func (*Localizer) LocalizationFuncMap

func (l *Localizer) LocalizationFuncMap() template.FuncMap

LocalizationFuncMap returns template.FuncMap (html template is used) with one method - trans Usage in code:

engine := gin.New()
engine.FuncMap = localizer.LocalizationFuncMap()

or (with multitemplate)

renderer := multitemplate.NewRenderer()
funcMap := localizer.LocalizationFuncMap()
renderer.AddFromFilesFuncs("index", funcMap, "template/index.html")

funcMap must be passed for every .AddFromFilesFuncs call Usage in templates:

<p class="info">{{"need_login_msg" | trans}}

You can borrow FuncMap from this method and add your functions to it.

func (*Localizer) LocalizationMiddleware

func (l *Localizer) LocalizationMiddleware() gin.HandlerFunc

LocalizationMiddleware returns gin.HandlerFunc which will set localizer language by Accept-Language header Result Localizer instance will share it's internal data (translations, bundles, etc) with instance which was used to append middleware to gin. Because of that all Localizer instances from this middleware will share *same* mutex. This mutex is used to wrap i18n.Bundle methods (those aren't goroutine-safe to use). Usage:

engine := gin.New()
localizer := NewLocalizer("en", DefaultLocalizerMatcher(), "translations")
engine.Use(localizer.LocalizationMiddleware())

func (*Localizer) Localize

func (l *Localizer) Localize(messageID string) (string, error)

Localize will return localized message by it's ID, or error if message wasn't found.

func (*Localizer) LocalizeTemplateMessage

func (l *Localizer) LocalizeTemplateMessage(messageID string, templateData map[string]interface{}) (string, error)

LocalizeTemplateMessage will return localized message with specified data, or error if message wasn't found It uses text/template syntax: https://golang.org/pkg/text/template/

func (*Localizer) Preload

func (l *Localizer) Preload(tags []language.Tag)

Preload provided languages (so they will not be loaded every time in middleware).

func (*Localizer) SetLanguage

func (l *Localizer) SetLanguage(tag language.Tag)

SetLanguage will change language using language tag.

func (*Localizer) SetLocale

func (l *Localizer) SetLocale(al string)

SetLocale will change language for current localizer.

func (*Localizer) UnauthorizedLocalized

func (l *Localizer) UnauthorizedLocalized(err string) (int, interface{})

UnauthorizedLocalized is same as errorutil.Unauthorized(string), but passed string will be localized.

type LocalizerInterface added in v2.2.1

LocalizerInterface contains entire public interface of the localizer component.

func GetContextLocalizer

func GetContextLocalizer(c *gin.Context) (loc LocalizerInterface, ok bool)

GetContextLocalizer returns localizer from context if it is present there. Language will be set using Accept-Language header and root language tag.

func MustGetContextLocalizer

func MustGetContextLocalizer(c *gin.Context) LocalizerInterface

MustGetContextLocalizer returns Localizer instance if it exists in provided context. Panics otherwise.

func NewLocalizer

func NewLocalizer(locale language.Tag, matcher language.Matcher, translationsPath string) LocalizerInterface

NewLocalizer returns localizer instance with specified parameters. Usage:

NewLocalizer(language.English, DefaultLocalizerMatcher(), "translations")

func NewLocalizerFS

func NewLocalizerFS(
	locale language.Tag, matcher language.Matcher, translationsFS fs.FS,
) LocalizerInterface

NewLocalizerFS returns localizer instance with specified parameters. Usage:

NewLocalizerFS(language.English, DefaultLocalizerMatcher(), translationsFS)

TODO This code should be covered with tests.

type LocalizerWithFuncs added in v2.3.0

type LocalizerWithFuncs interface {
	LocalizationFuncMap() template.FuncMap
}

LocalizerWithFuncs can provide template functions.

type LocalizerWithMiddleware added in v2.3.0

type LocalizerWithMiddleware interface {
	LocalizationMiddleware() gin.HandlerFunc
}

LocalizerWithMiddleware can provide middlewares for usage in the app.

type MessageLocalizer added in v2.3.0

type MessageLocalizer interface {
	GetLocalizedMessage(string) string
	GetLocalizedTemplateMessage(string, map[string]interface{}) string
	Localize(string) (string, error)
	LocalizeTemplateMessage(string, map[string]interface{}) (string, error)
}

MessageLocalizer can localize regular strings and strings with template parameters.

type ModuleFeaturesUploader added in v2.6.3

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

func NewModuleFeaturesUploader added in v2.6.3

func NewModuleFeaturesUploader(
	log logger.Logger,
	conf config.AWS,
	loc LocalizerInterface,
	featuresFilename string,
) *ModuleFeaturesUploader

func (*ModuleFeaturesUploader) Upload added in v2.6.3

func (s *ModuleFeaturesUploader) Upload()

type Renderer

type Renderer struct {
	multitemplate.Renderer
	TemplatesFS fs.FS
	FuncMap     template.FuncMap
	// contains filtered or unexported fields
}

Renderer wraps multitemplate.Renderer in order to make it easier to use.

func NewDynamicRenderer

func NewDynamicRenderer(funcMap template.FuncMap) Renderer

NewDynamicRenderer is a Renderer constructor with multitemplate.DynamicRender.

func NewRenderer

func NewRenderer(funcMap template.FuncMap) Renderer

NewRenderer is a Renderer constructor.

func NewStaticRenderer

func NewStaticRenderer(funcMap template.FuncMap) Renderer

NewStaticRenderer is a Renderer constructor with multitemplate.Render.

func (*Renderer) Push

func (r *Renderer) Push(name string, files ...string) *template.Template

Push is an AddFromFilesFuncs wrapper.

type Sentry

type Sentry struct {
	SentryConfig       sentry.ClientOptions
	Logger             logger.Logger
	Localizer          MessageLocalizer
	AppInfo            AppInfo
	SentryLoggerConfig SentryLoggerConfig
	ServerName         string
	DefaultError       string
	TaggedTypes        SentryTaggedTypes
	// contains filtered or unexported fields
}

Sentry struct. Holds SentryTaggedStruct list.

func (*Sentry) CaptureException added in v2.2.0

func (s *Sentry) CaptureException(c *gin.Context, exception error)

CaptureException and send it to Sentry. Use stacktrace.ErrorWithStack to append the stacktrace to the errors without it!

func (*Sentry) InitSentrySDK added in v2.2.0

func (s *Sentry) InitSentrySDK()

InitSentrySDK globally in the app. Only works once per component (you really shouldn't call this twice).

func (*Sentry) SentryMiddlewares added in v2.2.0

func (s *Sentry) SentryMiddlewares() []gin.HandlerFunc

SentryMiddlewares contain all the middlewares required to process errors and panics and send them to the Sentry. It also logs those with account identifiers.

type SentryLoggerConfig added in v2.2.0

type SentryLoggerConfig struct {
	TagForConnection string
	TagForAccount    string
}

SentryLoggerConfig configures how Sentry component will create account-scoped logger for recovery.

type SentryTagged

type SentryTagged interface {
	BuildTags(interface{}) (map[string]string, error)
	GetContextKey() string
	GetTags() SentryTags
	GetName() string
}

SentryTagged interface for both tagged scalar and struct.

type SentryTaggedScalar

type SentryTaggedScalar struct {
	SentryTaggedStruct
	Name string
}

SentryTaggedScalar variable from context.

func NewTaggedScalar

func NewTaggedScalar(sample interface{}, ginCtxKey string, name string) *SentryTaggedScalar

NewTaggedScalar constructor.

func (*SentryTaggedScalar) BuildTags

func (t *SentryTaggedScalar) BuildTags(v interface{}) (items map[string]string, err error)

BuildTags returns map with single item in this format: <tag name> => <scalar value>.

func (*SentryTaggedScalar) Get

func (t *SentryTaggedScalar) Get(v interface{}) (value string, err error)

Get will extract property string representation from specified object. It will be properly formatted.

func (*SentryTaggedScalar) GetContextKey

func (t *SentryTaggedScalar) GetContextKey() string

GetContextKey is getter for GinContextKey.

func (*SentryTaggedScalar) GetName

func (t *SentryTaggedScalar) GetName() string

GetName is getter for Name (tag name for scalar).

func (*SentryTaggedScalar) GetTags

func (t *SentryTaggedScalar) GetTags() SentryTags

GetTags is useless for SentryTaggedScalar.

type SentryTaggedStruct

type SentryTaggedStruct struct {
	Type          reflect.Type
	Tags          SentryTags
	GinContextKey string
}

SentryTaggedStruct holds information about type, it's key in gin.Context (for middleware), and it's properties.

func NewTaggedStruct

func NewTaggedStruct(sample interface{}, ginCtxKey string, tags map[string]string) *SentryTaggedStruct

NewTaggedStruct constructor.

func (*SentryTaggedStruct) AddTag

func (t *SentryTaggedStruct) AddTag(name string, property string) *SentryTaggedStruct

AddTag will add tag with property name which holds tag in object.

func (*SentryTaggedStruct) BuildTags

func (t *SentryTaggedStruct) BuildTags(v interface{}) (tags map[string]string, err error)

BuildTags will extract tags for Sentry from specified object.

func (*SentryTaggedStruct) GetContextKey

func (t *SentryTaggedStruct) GetContextKey() string

GetContextKey is GinContextKey getter.

func (*SentryTaggedStruct) GetName

func (t *SentryTaggedStruct) GetName() string

GetName is useless for SentryTaggedStruct.

func (*SentryTaggedStruct) GetProperty

func (t *SentryTaggedStruct) GetProperty(v interface{}, property string) (name string, value string, err error)

GetProperty will extract property string representation from specified object. It will be properly formatted.

func (*SentryTaggedStruct) GetTags

func (t *SentryTaggedStruct) GetTags() SentryTags

GetTags is Tags getter.

type SentryTaggedTypes

type SentryTaggedTypes []SentryTagged

SentryTaggedTypes list.

type SentryTags

type SentryTags map[string]string

SentryTags list for SentryTaggedStruct. Format: name => property name.

Directories

Path Synopsis
db
Package stacktrace contains code borrowed from the github.com/pkg/errors
Package stacktrace contains code borrowed from the github.com/pkg/errors

Jump to

Keyboard shortcuts

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