infra

package module
v0.29.0 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: MIT Imports: 28 Imported by: 67

README

infrago

infrago 是框架核心运行时(module: github.com/infrago/infra)。

包定位

  • 类型:核心主包(运行时)
  • 作用:统一管理模块生命周期、配置加载、模块装配与调用入口

主要功能

  • 运行流程(infra.Run()):Load -> Config -> Setup -> Open -> Start -> Wait -> Stop -> Close
  • 生命周期(模块接口):Setup -> Open -> Start -> Stop -> Close
  • 统一启动:infra.Run()
  • 统一调用:infra.Invoke()
  • 自定义配置:infra.Setting()
  • 模块挂载:模块通过 infra.Mount(module) 接入

最小可运行示例

package main

import (
    _ "github.com/infrago/http"
    _ "github.com/infrago/log"
    "github.com/infrago/infra"
)

func main() {
    infra.Run()
}
[infrago]
name = "demo"
profile = "dev"

[http]
port = 8100

[log]
driver = "default"

[setting]
tenant = "demo"

Documentation

Index

Constants

View Source
const (
	JSON   = "json"
	XML    = "xml"
	GOB    = "gob"
	TOML   = "toml"
	DIGIT  = "digit"
	DIGITS = "digits"
	TEXT   = "text"
	TEXTS  = "texts"
)
View Source
const (
	INFRAGO = "infrago"
	DEFAULT = "default"
	GLOBAL  = "global"
)
View Source
const (
	TraceKindMethod  = "method"
	TraceKindService = "service"
	TraceKindTrigger = "trigger"
	TraceKindHTTP    = "http"
	TraceKindWeb     = "web"
	TraceKindEvent   = "event"
	TraceKindQueue   = "queue"
	TraceKindCron    = "cron"
	TraceKindCustom  = "custom"
)
View Source
const (
	START = "start"
	STOP  = "stop"
)

Variables

View Source
var (
	// ErrInvalidCodec is returned when codec name is unknown.
	ErrInvalidCodec = errInvalidCodec
	// ErrInvalidCodecData is returned when codec data is invalid.
	ErrInvalidCodecData = errInvalidCodecData
)
View Source
var (
	OK       = Result(0, "ok", "成功")
	Fail     = Result(1, "fail", "失败")
	Retry    = Result(2, "retry", "重试").Retry()
	Invalid  = Result(3, "invalid", "无效请求或数据")
	Denied   = Result(4, "denied", "拒绝访问")
	Unsigned = Result(5, "unsigned", "无权访问")
	Unauthed = Result(6, "unauthed", "无权访问")
)

Functions

func Arguments

func Arguments(name string, extends ...Vars) Vars

func AssetDir added in v0.7.0

func AssetDir(name string) ([]fs.DirEntry, error)

AssetDir reads one directory from global asset filesystem.

func AssetFS added in v0.7.0

func AssetFS(fss ...fs.FS) fs.FS

AssetFS sets/gets global asset filesystem. call AssetFS(fsys) to set; call AssetFS() to get.

func AssetFile added in v0.7.0

func AssetFile(name string) ([]byte, error)

AssetFile reads one file from global asset filesystem.

func AssetStat added in v0.7.0

func AssetStat(name string) (fs.FileInfo, error)

AssetStat stats one file from global asset filesystem.

func Broadcast added in v0.7.0

func Broadcast(name string, value Map) error

Broadcast dispatches one async event to all subscribers.

func CodecDigitAlphabet added in v0.8.1

func CodecDigitAlphabet() string

CodecDigitAlphabet returns configured digit alphabet.

func CodecLength added in v0.8.1

func CodecLength() int

CodecLength returns configured encoded length.

func CodecSalt added in v0.8.1

func CodecSalt() string

CodecSalt returns configured codec salt.

func CodecTextAlphabet added in v0.8.1

func CodecTextAlphabet() string

CodecTextAlphabet returns configured text alphabet.

func Decode

func Decode(name string, data Any, obj Any) (Any, error)

func DecodeInt64 added in v0.8.1

func DecodeInt64(v string) (int64, error)

DecodeInt64 decodes one int64 using current codec config.

func DecodeInt64Slice added in v0.8.1

func DecodeInt64Slice(v string) ([]int64, error)

DecodeInt64Slice decodes int64 slice using current codec config.

func DecodeTextBytes added in v0.8.1

func DecodeTextBytes(v string) ([]byte, error)

DecodeTextBytes decodes bytes using current codec text config.

func Decrypt

func Decrypt(name string, obj Any) (Any, error)

func Dispatch added in v0.13.0

func Dispatch(name string, value Map) error

Dispatch dispatches one async queued service request.

func Encode

func Encode(name string, v Any) (Any, error)

wrappers

func EncodeInt64 added in v0.8.1

func EncodeInt64(v int64) (string, error)

EncodeInt64 encodes one int64 using current codec config.

func EncodeInt64Slice added in v0.8.1

func EncodeInt64Slice(v []int64) (string, error)

EncodeInt64Slice encodes int64 slice using current codec config.

func EncodeTextBytes added in v0.8.1

func EncodeTextBytes(v []byte) (string, error)

EncodeTextBytes encodes bytes using current codec text config.

func Encrypt

func Encrypt(name string, obj Any) (string, error)

func Enqueue added in v0.7.0

func Enqueue(name string, value Map) error

Enqueue is compatibility alias of Dispatch.

func ErrorResult added in v0.7.0

func ErrorResult(err error) Res

ErrorResult exposes error-to-Res conversion.

func Execute

func Execute(name string, values ...Map) (Map, Res)

Execute executes one local method only.

func Expressions

func Expressions(name string, defs ...string) []string

Expressions 获取正则的表达式

func Extension

func Extension(mime string, defs ...string) string

Extension 按MIMEType获取扩展名

func Generate

func Generate(prefixs ...string) string

func GenerateTokenID added in v0.10.0

func GenerateTokenID(lengths ...int) string

GenerateTokenID returns a random hex token id with configurable length. Default length is 16.

func Go

func Go(profile ...string)

Go is an alias of Run for compatibility.

func Identity added in v0.7.0

func Identity() infragoIdentity

func Invoke added in v0.7.0

func Invoke(name string, values ...Map) (Map, Res)

Invoke executes one entry as a new request context.

func InvokeFail added in v0.7.0

func InvokeFail(name string, values ...Map) bool

InvokeFail executes one entry and returns whether result is failed.

func InvokeList added in v0.12.0

func InvokeList(name string, values ...Map) (Map, []Map)

InvokeList executes one entry and returns response data with parsed "items" list.

func InvokeOK added in v0.7.0

func InvokeOK(name string, values ...Map) bool

InvokeOK executes one entry and returns whether result is OK.

func Invokes added in v0.7.0

func Invokes(name string, values ...Map) ([]Map, Res)

Invokes executes one entry and returns response items list.

func Invoking added in v0.7.0

func Invoking(name string, offset, limit int64, values ...Map) (int64, []Map)

Invoking executes one entry and returns paged items with total count.

func IsRetry added in v0.13.0

func IsRetry(res Res) bool

IsRetry reports whether one result is marked as retryable.

func Languages

func Languages() map[string]Language

func Mapping

func Mapping(config Vars, data Map, value Map, argn bool, pass bool, zones ...*time.Location) Res

Mapping is a convenience wrapper.

func Marshal

func Marshal(name string, obj Any) ([]byte, error)

func Match

func Match(regular, value string) bool

Match 正则做匹配校验

func Mimetype

func Mimetype(ext string, defs ...string) string

Mimetype 按扩展名获取 MIME 中的 类型

func Node

func Node() string

func Override

func Override(args ...bool) bool

Override controls whether registrations can overwrite existing entries.

func Prepare added in v0.7.0

func Prepare(profile ...string)

Prepare initializes and opens modules without starting them.

func Publish added in v0.7.0

func Publish(name string, value Map) error

Publish is compatibility alias of Rolecast.

func Ready

func Ready(profile ...string)

Ready is an alias of Prepare for compatibility.

func Register

func Register(args ...Any)

Register registers anything into mounted modules.

func RegisterProfile added in v0.7.0

func RegisterProfile(key string, profile Profile)

func Request added in v0.13.0

func Request(name string, value Map, timeout ...time.Duration) (Map, Res)

Request executes one remote service call only.

func Result

func Result(code int, status string, text string) Res

Result 定义一个result,并自动注册status status 表示状态key text 表示状态对应的默认文案

func ResultGroup

func ResultGroup(name string, bases ...int) *resultGroup

func Results

func Results(langs ...string) map[Status]string

func RetryResult added in v0.13.0

func RetryResult(res Res, args ...Any) Res

RetryResult marks one result as retryable and optionally overrides message args.

func Role

func Role() string

func Rolecast added in v0.13.0

func Rolecast(name string, value Map) error

Rolecast dispatches one async event to one node per role group.

func Run added in v0.7.0

func Run(profile ...string)

Run starts the full lifecycle and blocks until stop.

func Scope added in v0.11.1

func Scope(name string) *registerScope

Scope creates a named registration scope so names can omit repeated prefix.

func Sequence

func Sequence() int64

func Setting

func Setting() Map

func StateCode

func StateCode(name string, defs ...int) int

StateCode is deprecated, use StatusCode.

func StatusCode added in v0.7.0

func StatusCode(name string, defs ...int) int

StateCode 返回状态码

func String

func String(lang, name string, args ...Any) string

String 获取多语言字串

func SyncToggle

func SyncToggle(name string, values ...Map)

func Toggle

func Toggle(name string, values ...Map)

func TraceAttrs added in v0.7.0

func TraceAttrs(service, kind, entry string, attrs ...Map) Map

TraceAttrs builds a normalized trace attrs map.

func Types

func Types() map[string]Type

Types 获取所有类型定义

func Unmarshal

func Unmarshal(name string, data []byte, obj Any) error

Types

type BusHook added in v0.7.0

type BusHook interface {
	Request(meta *Meta, name string, value base.Map, timeout time.Duration) (base.Map, base.Res)
	Broadcast(meta *Meta, name string, value base.Map) error
	Rolecast(meta *Meta, name string, value base.Map) error
	Dispatch(meta *Meta, name string, value base.Map) error

	// compatibility aliases
	Publish(meta *Meta, name string, value base.Map) error
	Enqueue(meta *Meta, name string, value base.Map) error
	Stats() []ServiceStats
	ListNodes() []NodeInfo
	ListServices() []ServiceInfo
}

type Codec

type Codec struct {
	Name   string
	Text   string
	Alias  []string
	Encode EncodeFunc
	Decode DecodeFunc
}

type Codecs

type Codecs map[string]Codec

type ConfigHook added in v0.7.0

type ConfigHook interface {
	LoadConfig() (base.Map, error)
}

type Context

type Context struct {
	*Meta

	Name    string
	Config  *coreEntry
	Setting Map
	Value   Map
	Args    Map
	// contains filtered or unexported fields
}

Context carries invocation data for method/service.

func (*Context) Attempts added in v0.13.0

func (ctx *Context) Attempts() int

func (*Context) Final added in v0.13.0

func (ctx *Context) Final() bool

type DecodeFunc

type DecodeFunc func(d Any, v Any) (Any, error)

type EncodeFunc

type EncodeFunc func(v Any) (Any, error)

type Host added in v0.7.0

type Host interface {
	InvokeLocal(meta *Meta, name string, value Map) (Map, Res, bool)
	InvokeLocalMethod(meta *Meta, name string, value Map) (Map, Res, bool)
	InvokeLocalService(meta *Meta, name string, value Map, settings ...Map) (Map, Res, bool)
	InvokeLocalMessage(meta *Meta, name string, value Map) (Map, Res, bool)
	RegisterLocal(name string, value Any)
}

func Mount

func Mount(mod Module) Host

Mount attaches a module into the infrago runtime and returns a host.

type Language

type Language struct {
	// Name 语言名称
	Name string
	// Desc 语言说明
	Desc string
	// Accepts 匹配的语言
	// 比如,znCN, zh, zh-CN 等自动匹配
	Accepts []string
	// Strings 当前语言是字符串列表
	Strings Strings
}

多语言配置

type Library

type Library struct {
	Name    string
	Desc    string
	Setting Map
	Methods Methods
}

Library defines a method group with defaults. Example:

Register("mail.sendcloud", Library{
  Name: "SendCloud",
  Methods: Methods{"send": Method{...}},
})

func (Library) RegistryComponent added in v0.7.0

func (Library) RegistryComponent() string

type Message added in v0.13.0

type Message struct {
	Name     string
	Desc     string
	Nullable bool
	Args     Vars
	Data     Vars
	Action   Any
	Setting  Map
}

func (Message) RegistryComponent added in v0.13.0

func (Message) RegistryComponent() string

type Messages added in v0.13.0

type Messages map[string]Message

func (Messages) RegistryComponent added in v0.13.0

func (Messages) RegistryComponent() string

type Meta

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

func NewMeta added in v0.7.0

func NewMeta() *Meta

func (*Meta) Authed

func (m *Meta) Authed() bool

Authed returns whether token is valid and auth flag is true.

func (*Meta) Begin added in v0.7.0

func (m *Meta) Begin(name string, attrs ...Map) TraceSpan

Begin starts a trace span through trace hook.

func (*Meta) Broadcast added in v0.13.0

func (m *Meta) Broadcast(name string, value Map) error

func (*Meta) Context added in v0.7.0

func (m *Meta) Context() context.Context

func (*Meta) Dispatch added in v0.13.0

func (m *Meta) Dispatch(name string, value Map) error

func (*Meta) Enqueue added in v0.13.0

func (m *Meta) Enqueue(name string, value Map) error

Enqueue is compatibility alias of Dispatch.

func (*Meta) Execute added in v0.13.0

func (m *Meta) Execute(name string, values ...Map) Map

Execute calls local method only.

func (*Meta) Invoke

func (m *Meta) Invoke(name string, values ...Map) Map

Invoke calls another service (local first, then bus). It stores the result in meta and returns only the data.

func (*Meta) InvokeFail added in v0.7.0

func (m *Meta) InvokeFail(name string, values ...Map) bool

InvokeFail executes one call and returns whether result is failed.

func (*Meta) InvokeList added in v0.12.0

func (m *Meta) InvokeList(name string, values ...Map) (Map, []Map)

InvokeList executes one call and also returns parsed "items" list from response data.

func (*Meta) InvokeOK added in v0.7.0

func (m *Meta) InvokeOK(name string, values ...Map) bool

InvokeOK executes one call and returns whether result is OK.

func (*Meta) Invokes

func (m *Meta) Invokes(name string, values ...Map) []Map

Invokes executes one call and returns response items list.

func (*Meta) Invoking

func (m *Meta) Invoking(name string, offset, limit int64, values ...Map) (int64, []Map)

Invoking executes one call and returns paged items from response.

func (*Meta) Language

func (m *Meta) Language(v ...string) string

func (*Meta) Library

func (m *Meta) Library(name string, settings ...Map) *libraryInvoker

func (*Meta) Metadata

func (m *Meta) Metadata(data ...Metadata) Metadata

func (*Meta) NewSign

func (m *Meta) NewSign(auth bool, payload Map, expires ...time.Duration) string

NewSign issues token with a new token id. expires is optional duration, begin defaults to current time.

func (*Meta) NewSignAt added in v0.9.0

func (m *Meta) NewSignAt(auth bool, payload Map, begin time.Time, expires ...time.Duration) string

NewSignAt issues token with a new token id and custom begin time. expires is optional duration.

func (*Meta) ParentSpanId added in v0.7.0

func (m *Meta) ParentSpanId(id ...string) string

func (*Meta) ParseTraceParent added in v0.7.0

func (m *Meta) ParseTraceParent(traceparent string) bool

ParseTraceParent parses W3C traceparent: 00-<traceid>-<spanid>-<flags>.

func (*Meta) Payload

func (m *Meta) Payload() Map

Payload returns token payload placeholder.

func (*Meta) PopSpanFrame added in v0.7.0

func (m *Meta) PopSpanFrame() (string, string, bool)

func (*Meta) Publish added in v0.13.0

func (m *Meta) Publish(name string, value Map) error

Publish is compatibility alias of Rolecast.

func (*Meta) PushSpanFrame added in v0.7.0

func (m *Meta) PushSpanFrame(prevSpanId, prevParentId string)

func (*Meta) Request added in v0.13.0

func (m *Meta) Request(name string, value Map, timeout ...time.Duration) Map

Request calls remote service only.

func (*Meta) Result

func (m *Meta) Result(res ...Res) Res

func (*Meta) RevokeCurrentToken added in v0.26.0

func (m *Meta) RevokeCurrentToken(expires ...int64) error

RevokeCurrentToken revokes the current raw token, defaulting to current token expiry.

func (*Meta) RevokeCurrentTokenID added in v0.26.0

func (m *Meta) RevokeCurrentTokenID(expires ...int64) error

RevokeCurrentTokenID revokes the current token id, defaulting to current token expiry.

func (*Meta) RevokeToken added in v0.9.0

func (m *Meta) RevokeToken(token string, expires ...int64) error

RevokeToken revokes one raw token.

func (*Meta) RevokeTokenID added in v0.9.0

func (m *Meta) RevokeTokenID(tokenID string, expires ...int64) error

RevokeTokenID revokes one token id.

func (*Meta) Rolecast added in v0.13.0

func (m *Meta) Rolecast(name string, value Map) error

func (*Meta) Sign

func (m *Meta) Sign(auth bool, payload Map, expires ...time.Duration) string

Sign issues token with current token id. expires is optional duration, begin defaults to current time.

func (*Meta) SignAt added in v0.9.0

func (m *Meta) SignAt(auth bool, payload Map, begin time.Time, expires ...time.Duration) string

SignAt issues token with current token id and custom begin time. expires is optional duration.

func (*Meta) Signed

func (m *Meta) Signed() bool

Signed returns whether token is valid.

func (*Meta) SpanId added in v0.7.0

func (m *Meta) SpanId(id ...string) string

func (*Meta) String

func (m *Meta) String(key string, args ...Any) string

String returns localized string by language.

func (*Meta) Timezone

func (m *Meta) Timezone(zones ...*time.Location) *time.Location

func (*Meta) Token

func (m *Meta) Token(v ...string) string

func (*Meta) TokenExpires added in v0.26.0

func (m *Meta) TokenExpires() int64

TokenExpires returns current token expiry as a Unix timestamp.

func (*Meta) TokenId added in v0.7.0

func (m *Meta) TokenId() string

TokenId returns token id placeholder.

func (*Meta) Trace added in v0.7.0

func (m *Meta) Trace(name string, attrs ...Map) error

Trace emits one trace event through trace hook.

func (*Meta) TraceEntry added in v0.7.0

func (m *Meta) TraceEntry(entry ...string) string

func (*Meta) TraceId added in v0.7.0

func (m *Meta) TraceId(id ...string) string

func (*Meta) TraceKind added in v0.7.0

func (m *Meta) TraceKind(kind ...string) string

func (*Meta) TraceParent added in v0.7.0

func (m *Meta) TraceParent() string

TraceParent builds W3C traceparent using current trace/span ids.

func (*Meta) Unauthed

func (m *Meta) Unauthed() bool

Unauthed is the negation of Authed.

func (*Meta) Unsigned

func (m *Meta) Unsigned() bool

Unsigned is the negation of Signed.

func (*Meta) Verify

func (m *Meta) Verify(token string) error

Verify validates token signature and payload.

func (*Meta) WithContext added in v0.7.0

func (m *Meta) WithContext(ctx context.Context) *Meta

type Metadata

type Metadata struct {
	TraceId      string `json:"tid,omitempty"`
	SpanId       string `json:"sid,omitempty"`
	ParentSpanId string `json:"psid,omitempty"`
	Language     string `json:"l,omitempty"`
	Timezone     int    `json:"z,omitempty"`
	Token        string `json:"t,omitempty"`
}

type Method

type Method struct {
	Name     string
	Desc     string
	Nullable bool
	Args     Vars
	Data     Vars
	Action   Any
	Setting  Map
}

func (Method) RegistryComponent added in v0.7.0

func (Method) RegistryComponent() string

type Methods added in v0.7.0

type Methods map[string]Method

func (Methods) RegistryComponent added in v0.7.0

func (Methods) RegistryComponent() string

type Mime

type Mime []string

MIME mimetype集合

type Mimes

type Mimes map[string]Mime

type Module

type Module interface {
	Register(string, Any)
	Config(Map)
	Setup()
	Open()
	Start()
	Stop()
	Close()
}

type NodeInfo added in v0.7.0

type NodeInfo struct {
	Project  string   `json:"project"`
	Node     string   `json:"node"`
	Role     string   `json:"role"`
	Profile  string   `json:"profile"`
	Services []string `json:"services"`
	Updated  int64    `json:"updated"`
}

NodeInfo contains one online node's exposed service set.

type Profile added in v0.7.0

type Profile struct {
	Name     string
	Desc     string
	Includes []string
	Excludes []string
}

type RegistryComponent added in v0.7.0

type RegistryComponent interface {
	RegistryComponent() string
}

type Regular

type Regular []string

Regular 正则表达式,方便注册

type Regulars

type Regulars map[string]Regular

type Service

type Service struct {
	Name     string
	Desc     string
	Nullable bool
	Args     Vars
	Data     Vars
	Action   Any
	Retry    []time.Duration
	Setting  Map
}

func (Service) RegistryComponent added in v0.7.0

func (Service) RegistryComponent() string

type ServiceInfo added in v0.7.0

type ServiceInfo struct {
	Service   string        `json:"service"`
	Name      string        `json:"name"`
	Desc      string        `json:"desc"`
	Updated   int64         `json:"updated"`
	Instances int           `json:"instances"`
	Nodes     []ServiceNode `json:"nodes"`
}

ServiceInfo is a service-centric online view.

type ServiceNode added in v0.7.0

type ServiceNode struct {
	Node    string `json:"node"`
	Role    string `json:"role"`
	Profile string `json:"profile"`
}

ServiceNode indicates one node serving a service.

type ServiceStats added in v0.7.0

type ServiceStats struct {
	Name         string `json:"name"`
	Version      string `json:"version"`
	NumRequests  int    `json:"num_requests"`
	NumErrors    int    `json:"num_errors"`
	TotalLatency int64  `json:"total_latency_ms"`
	AvgLatency   int64  `json:"avg_latency_ms"`
}

ServiceStats contains service statistics.

type Services added in v0.7.0

type Services map[string]Service

func (Services) RegistryComponent added in v0.7.0

func (Services) RegistryComponent() string

type State

type State = Status

Deprecated aliases for compatibility.

type States

type States = Statuses

Deprecated aliases for compatibility.

type Status added in v0.7.0

type Status int

Status 状态定义,方便注册

type Statuses added in v0.7.0

type Statuses map[string]Status

type Strings

type Strings map[string]string

type Token

type Token struct {
	Token   string
	TokenID string
	Auth    bool
	Payload Map
	Begin   int64
	Expires int64
}

type TokenHook added in v0.9.0

type TokenHook interface {
	Sign(req Token) (string, error)
	Verify(token string) (Token, error)
	RevokeToken(token string, expires int64) error
	RevokeTokenID(tokenID string, expires int64) error
}

type TraceHook added in v0.7.0

type TraceHook interface {
	Begin(meta *Meta, name string, attrs base.Map) TraceSpan
	Trace(meta *Meta, name string, status string, attrs base.Map) error
}

type TraceSpan added in v0.7.0

type TraceSpan interface {
	End(...base.Any)
}

type Trigger

type Trigger struct {
	Name     string
	Desc     string
	Nullable bool
	Args     Vars
	Data     Vars
	Action   func(*Context)
}

func (Trigger) RegistryComponent added in v0.7.0

func (Trigger) RegistryComponent() string

type Type

type Type struct {
	// Name 类型名称
	Name string

	// Desc 类型说明
	Desc string

	// Alias 类型别名
	Alias []string

	// Valid 类型检查方法
	Valid TypeValidFunc

	// Value 类型值包装方法
	Value TypeValueFunc
}

Type 类型定义

type TypeValidFunc

type TypeValidFunc func(Any, Var) bool

type TypeValueFunc

type TypeValueFunc func(Any, Var) Any

Jump to

Keyboard shortcuts

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