core

package
v0.0.0-...-5ced209 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2024 License: MIT Imports: 52 Imported by: 0

Documentation

Index

Constants

View Source
const (
	KV     = "kv"
	PWD    = "pwd"
	RSA    = "rsa"
	JWT    = "jwt"
	SECRET = "secret"
	SALT   = "salt"
	PUK    = "puk"
	PRK    = "prk"
	ID     = "id"
	APP    = "app"
)

vault

View Source
const (
	EmptyString = ""
	Bearer      = "Bearer "
	UserID      = "userID"
	// headers params
	Method        = "method"
	URI           = "uri"
	ClientIp      = "client_ip"
	UserAgent     = "user-agent"
	TraceId       = "trace_id"
	SpanId        = "span_id"
	ParentId      = "parent_id"
	Authorization = "authorization"
	AppId         = "app_id"
	RequestId     = "request_id"
	UserId        = "user_id"
	RequestURI    = "request_uri"
	// redis
	Signature = "signature"
	// jaeger
	Tracer      = "tracer"
	Parent      = "parent"
	UberTraceId = "uber-trace-id"
)
View Source
const (
	TokenExpired     = "Token已过期"
	TokenNotValidYet = "Token不再有效"
	TokenMalformed   = "Token非法"
	TokenInvalid     = "Token无效"
)
View Source
const (
	Username = "liuzhao"
	Password = "123456"
)

vault access

View Source
const FAILURE = "失败"
View Source
const SUCCESS = "成功"

logger

Variables

Functions

func BASE64Decode

func BASE64Decode(str string) ([]byte, error)

func BASE64DecodeStr

func BASE64DecodeStr(str string) (string, error)

func BASE64Encode

func BASE64Encode(byt []byte) string

func BASE64EncodeStr

func BASE64EncodeStr(str string) string

func FormatCaller

func FormatCaller(ok bool, desc string) string

func FormatError

func FormatError(code Code, desc string, err error) error

func FormatInfo

func FormatInfo(desc string) string

func GenAppSignature

func GenAppSignature(id string, secret string, userId string, nonce string) string

func GenRSAKeyPair

func GenRSAKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error)

func GetCallerFileAndLine

func GetCallerFileAndLine(level int) string

func GetCallerInfo

func GetCallerInfo(level int) (string, string, int)

func GetCallerName

func GetCallerName(level int) string

func GetClientIP

func GetClientIP(c *gin.Context) string

func GetEncodedPwd

func GetEncodedPwd(pwd string) (string, string)

func GetFuncName

func GetFuncName() string

func GetPrivateKey

func GetPrivateKey() *rsa.PrivateKey

func GetProjectPath

func GetProjectPath() string

func GetPublicKey

func GetPublicKey() *rsa.PublicKey

func GetPublicKeyStr

func GetPublicKeyStr() string

func GetPwdEncodingOpts

func GetPwdEncodingOpts() *password.Options

func GetRandomIdlePort

func GetRandomIdlePort() string

func GetUserAgent

func GetUserAgent(c *gin.Context) string

func HmacSHA256

func HmacSHA256(byt []byte, secret string) string

func HmacSHA256Str

func HmacSHA256Str(str string, secret string) string

func In

func In(haystack interface{}, needle interface{}) bool

In 判断某数据结构中,有没有给出的值(needle)

func InitDB

func InitDB() (*gorm.DB, func(), error)

func InitGinEngine

func InitGinEngine() *gin.Engine

InitGinEngine Gin引擎的provider

func InitLogger

func InitLogger() func()

初始化系统日志

func InitLogrus

func InitLogrus() *logrus.Logger

日志扩展loggerx的Provider

func InitPrometheusRegistry

func InitPrometheusRegistry() *prometheus.Registry

func InitRedis

func InitRedis() (*redis.Client, func(), error)

func InitTracer

func InitTracer() *jConfig.Configuration

func InitVault

func InitVault()

func LoadEnv

func LoadEnv() string

加载环境变量ENV,设置配置文件路径

func LogFailure

func LogFailure(code Code, desc string, err error)

func LogSuccess

func LogSuccess(desc string)

func LoggerForHTTP

func LoggerForHTTP() gin.HandlerFunc

HTTP 日志中间件

func LoggerForRPC

func LoggerForRPC(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)

RPC 日志中间件

func MD5

func MD5(byt []byte) string

func MD5Str

func MD5Str(str string) string

func PrivateKeyB64StrToStruct

func PrivateKeyB64StrToStruct(privateKeyStr string) (*rsa.PrivateKey, error)

func PrivateKeyToString

func PrivateKeyToString(privateKey *rsa.PrivateKey) (string, error)

func PublicKeyB64StrToStruct

func PublicKeyB64StrToStruct(publicKeyStr string) (*rsa.PublicKey, error)

func PublicKeyToString

func PublicKeyToString(publicKey *rsa.PublicKey) (string, error)

func RSADecrypt

func RSADecrypt(privateKey *rsa.PrivateKey, encryptedStr string) (string, error)

func RSAEncrypt

func RSAEncrypt(publicKey *rsa.PublicKey, str string) (string, error)

func SHA1

func SHA1(byt []byte) string

func SHA1MD5Str

func SHA1MD5Str(str string) string

func SHA1Str

func SHA1Str(str string) string

func SHA256

func SHA256(byt []byte) string

func SHA256MD5Str

func SHA256MD5Str(str string) string

func SHA256Str

func SHA256Str(str string) string

func SelectFromMetadata

func SelectFromMetadata(md metadata.MD, key string) string

func SetHeadersForDownstream

func SetHeadersForDownstream(c *gin.Context, downstreamName string, client *redis.Client) error

func SetMetadataForDownstreamFromHttpHeaders

func SetMetadataForDownstreamFromHttpHeaders(ctx context.Context, c *gin.Context, downstreamName string, client *redis.Client) (context.Context, error)

func ShortUUID

func ShortUUID() string

func SpanID

func SpanID() string

func TraceID

func TraceID() string

func UUIDInLower

func UUIDInLower() string

func UUIDInUpper

func UUIDInUpper() string

func ValidateHeaders

func ValidateHeaders(c *gin.Context) error

func ValidateMetadata

func ValidateMetadata(md metadata.MD) error

func VerifyEncodedPwd

func VerifyEncodedPwd(pwdHeldRaw string, salt string, pwdTarget string) bool

Types

type App

type App struct {
	Id            string
	Secret        string
	Name          string `mapstructure:"name"`
	Version       string `mapstructure:"version"`
	Domain        string `mapstructure:"domain"`
	PublicKey     *rsa.PublicKey
	PrivateKey    *rsa.PrivateKey
	PublicKeyStr  string
	PrivateKeyStr string
	Salt          string
	JWTSecret     string
	Logger        *logrus.Logger
	Enabled       Enabled     `mapstructure:"enabled"`
	WhiteList     []WhiteList `mapstructure:"white_list"`
}

type Code

type Code uint32
const (
	OK                  Code = 0
	Unknown             Code = 1
	ConfigError         Code = 2
	ConnectionFailed    Code = 3
	ParseIssue          Code = 4
	MissingParameters   Code = 400
	Unauthorized        Code = 401
	Forbidden           Code = 403
	NotFound            Code = 404
	InternalServerError Code = 500
	DownstreamDown      Code = 5
	IOException         Code = 6
	PermissionDenied    Code = 7
	DBDenied            Code = 8
	CacheDenied         Code = 9
	VaultDenied         Code = 10
)

func (Code) String

func (c Code) String() string

type Config

type Config struct {
	App
	Lib
	Server
	Downstreams []Downstream
}

func GetConfig

func GetConfig() *Config

func (*Config) ConvertRSAKeys

func (cfg *Config) ConvertRSAKeys()

func (*Config) GetSecret

func (cfg *Config) GetSecret()

GetSecret 使用client token访问vault,获取secret,存入配置对象

func (*Config) HandleLoadedConfig

func (cfg *Config) HandleLoadedConfig() func()

func (*Config) LoadConfig

func (cfg *Config) LoadConfig(configFile string) func()

加载配置

func (*Config) PutAppSecret

func (cfg *Config) PutAppSecret()

PutAppSecret 新增修改AppId和AppSecret

func (*Config) PutRSA

func (cfg *Config) PutRSA()

PutRSA 新增和修改rsa

func (*Config) PutSalt

func (cfg *Config) PutSalt()

PutSalt 新增和修改salt

func (*Config) SetRSAKeys

func (cfg *Config) SetRSAKeys()

type Consul

type Consul struct {
	Timeout         int `mapstructure:"timeout"`
	Interval        int `mapstructure:"interval"`
	DeregisterAfter int `mapstructure:"deregister_after"`
	Endpoint
}

func (*Consul) ServiceDiscover

func (c *Consul) ServiceDiscover() error

ServiceDiscover 服务发现

func (*Consul) ServiceRegister

func (c *Consul) ServiceRegister() error

ServiceRegister 服务注册

type CustomClaims

type CustomClaims struct {
	jwt.StandardClaims
	UserID   string
	ClientIP string
}

type DB

type DB struct {
	Type         string `mapstructure:"type"`
	Debug        bool   `mapstructure:"debug"`
	MaxLifeTime  int    `mapstructure:"max_life_time"`
	MaxOpenConns int    `mapstructure:"max_open_conns"`
	MaxIdleConns int    `mapstructure:"max_idle_conns"`
	Name         string `mapstructure:"name"`
	Params       string `mapstructure:"params"`
	Username     string `mapstructure:"username"`
	Password     string `mapstructure:"password"`
	Endpoint
}

func (*DB) DSN

func (d *DB) DSN() string

func (*DB) LoadDB

func (d *DB) LoadDB() (*gorm.DB, func(), error)

type Downstream

type Downstream struct {
	Id     string
	Secret string
	Name   string `mapstructure:"name"`
	Endpoint
}

type ETCD

type ETCD struct {
	DialTimeout          int `mapstructure:"dial_timeout"`
	DialKeepAliveTime    int `mapstructure:"dial_keep_alive_time"`
	DialKeepAliveTimeout int `mapstructure:"dial_keep_alive_timeout"`
	Endpoint
}

type Enabled

type Enabled struct {
	Vault            bool `mapstructure:"vault"`
	RSA              bool `mapstructure:"rsa"`
	Signature        bool `mapstructure:"signature"`
	RandomPort       bool `mapstructure:"random_port"`
	ServiceDiscovery bool `mapstructure:"service_discovery"`
}

type Endpoint

type Endpoint struct {
	Host string `mapstructure:"host"`
	Port string `mapstructure:"port"`
}

type Error

type Error struct {
	Code Code // 对错误类型的分类
	Desc string
	Err  error
}

func (*Error) Error

func (err *Error) Error() string

type Gin

type Gin struct {
	RunMode string `mapstructure:"run_mode"`
}

type GormLogger

type GormLogger struct {
	Config logger.Config
}

func InitGormLogger

func InitGormLogger() *GormLogger

func (*GormLogger) Error

func (l *GormLogger) Error(ctx context.Context, msg string, data ...interface{})

func (*GormLogger) Info

func (l *GormLogger) Info(ctx context.Context, msg string, data ...interface{})

func (*GormLogger) LogMode

func (l *GormLogger) LogMode(lev logger.LogLevel) logger.Interface

func (*GormLogger) Trace

func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)

func (*GormLogger) Warn

func (l *GormLogger) Warn(ctx context.Context, msg string, data ...interface{})

type ILogger

type ILogger interface {
	Succeed(string)
	Fail(Code, string, error)
	SucceedWithField(*gin.Context, string)
	FailWithField(*gin.Context, Code, string, error)
	SucceedWithFieldForRPC(context.Context, string)
	FailWithFieldForRPC(context.Context, Code, string, error)
}

ILogger 主要用于中间件和handler

type IRocketMQ

type IRocketMQ interface {
	GenProducer(string) (*rocketmq.Producer, error)
	GenPushConsumer(string) (*rocketmq.PushConsumer, error)
}

type Jaeger

type Jaeger struct {
	Endpoint
}

type Jwt

type Jwt struct {
	SigningKey []byte
}

func NewJWT

func NewJWT() *Jwt

func (*Jwt) GenerateToken

func (j *Jwt) GenerateToken(userID string, clientIP string, duration time.Duration) (string, error)

func (*Jwt) ParseToken

func (j *Jwt) ParseToken(tokenStr string) (string, string, error)

func (*Jwt) RefreshToken

func (j *Jwt) RefreshToken(tokenStr string) (string, error)

type Lib

type Lib struct {
	Log
	Vault
	Gin
	DB
	Redis
	ETCD
	Consul
	Jaeger
	Rocketmq
}

type Log

type Log struct {
	Level    string `mapstructure:"level"`
	Format   string `mapstructure:"format"`
	Color    bool   `mapstructure:"color"`
	FilePath string `mapstructure:"file_path"`
	FileName string `mapstructure:"file_name"`
}

type Logger

type Logger struct {
	Logger *logrus.Logger
}

func (*Logger) Fail

func (l *Logger) Fail(code Code, desc string, err error)

func (*Logger) FailWithField

func (l *Logger) FailWithField(c *gin.Context, code Code, desc string, err error)

func (*Logger) FailWithFieldForRPC

func (l *Logger) FailWithFieldForRPC(ctx context.Context, code Code, desc string, err error)

func (*Logger) Succeed

func (l *Logger) Succeed(desc string)

func (*Logger) SucceedWithField

func (l *Logger) SucceedWithField(c *gin.Context, desc string)

func (*Logger) SucceedWithFieldForRPC

func (l *Logger) SucceedWithFieldForRPC(ctx context.Context, desc string)

type Redis

type Redis struct {
	Endpoint
}

func (*Redis) LoadRedis

func (r *Redis) LoadRedis() (*redis.Client, func(), error)

type RocketMQ

type RocketMQ struct {
}

func (*RocketMQ) GenProducer

func (r *RocketMQ) GenProducer(groupName string) (*rocketmq.Producer, error)

func (*RocketMQ) GenPushConsumer

func (r *RocketMQ) GenPushConsumer(groupName string) (*rocketmq.PushConsumer, error)

type Rocketmq

type Rocketmq struct {
	Timeout int `mapstructure:"timeout"`
	Retry   int `mapstructure:"retry"`
	Endpoint
}

type Server

type Server struct {
	Protocol        string `mapstructure:"protocol"`
	Host            string `mapstructure:"host"`
	Port            string `mapstructure:"port"`
	BaseUrl         string `mapstructure:"base_url"`
	ReadTimeout     int    `mapstructure:"read_timeout"`
	WriteTimeout    int    `mapstructure:"write_timeout"`
	IdleTimeout     int    `mapstructure:"idle_timeout"`
	ShutdownTimeout int    `mapstructure:"shutdown_timeout"`
}

type Vault

type Vault struct {
	Address string `mapstructure:"address"`
}

type WhiteList

type WhiteList struct {
	Name   string `mapstructure:"name"`
	Domain string `mapstructure:"domain"`
}

Jump to

Keyboard shortcuts

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