kratos

package module
v1.0.26 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2023 License: MIT Imports: 38 Imported by: 2

README

基于kratos进行二开,可以进行项目的快速接入和开发,对新手友好。

项目安装

安装kratos

go install github.com/limes-cloud/kratos/cmd/kratos@latest 

安装protoc

进入一下连接,安装自己合适的版本即可
https://github.com/protocolbuffers/protobuf/releases/

安装扩展包

go install github.com/limes-cloud/kratos/cmd/protoc-gen-go-http@latest &&\
go install github.com/limes-cloud/kratos/cmd/protoc-gen-go-errors@latest &&\
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest &&\
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest &&\
go install github.com/google/gnostic/cmd/protoc-gen-openapi@latest &&\
go install github.com/envoyproxy/protoc-gen-validate@latest

进行自动生成grpc代码配置

  • 1)打开Goland设置
  • 2)找到Tool 》 File Watcher
  • 3)添加custom配置,文件类型选择proto buffer
  • 4)配置一下命令,program 选择你下载的protoc,args配置为以下代码
--proto_path=$FileDir$
--proto_path=$ProjectFileDir$/third_party
--go_out=:.
--go-http_out=.
--go-grpc_out=.
--go-errors_out=.
--validate_out=lang=go:.
$FilePath$

这样你只要保存proto文件就会自动生成对应的grpc go的代码了。

目录说明

internal 我们的业务实现主要在这里
    |- service 主要实现grpc的接口,新加一个proto方法,就需要在这里新增一个对应的方法调用
    |- logic 主要是具体函数的业务逻辑实现
    |- model 主要是具体函数的数据层的操作

配置说明

配置主要在config/config.yaml文件夹下定义,接下来我们对配置字段进行详细讲解。

服务配置

服务配置主要是配置服务的启动端口以及超时时间的

server:
  http: #http配置
    addr: 0.0.0.0:8000 #http地址
    timeout: 1s #超时时间
    formatResponse: true #是否格式化
    cors: #跨域配置
      allowHeader: "Content-Type, Content-Length, Authorization" #允许准入的header
      allowMethod: "POST, GET, OPTIONS, PUT, DELETE, UPDATE, PATCH" #允许准入的方法
      allowOrigin: "*" #允许准入的域名
      exposeHeader: "Content-Length, Access-Control-Allow-Headers"  #暴露的header
      credentials: true
  grpc:
    addr: 0.0.0.0:9000
    timeout: 1s

formatResponse 开启的情况下会讲返回结果进行格式化为如下格式

{
    "code": 200,
    "message": "success!",
    "data": {
        "message": "fangweiye"
    }
}

日志配置

可以通过ctx.Logger() 进行使用

log:
  level: 0 #日志输出等级
  output:
    - stdout # stdout:控制台输出,k8s日志收集
    - file # file:输出到文件
  file: #output存在file时此配置才可生效
    name: ./tmp/runtime/output.log #日志存放地址
    maxSize: 1 #日志文件最大容量,单位m
    maxBackup: 5 #日志文件最多保存个数
    maxAge: 1 #保留就文件的最大天数,单位天
    compress: false #是否进行压缩归档

数据库配置

可以通过ctx.DB()进行使用,多个数据库配置可以使用ctx.DB('实例名称')

database:
  system: #数据库实例名称,如有多个数据库可新增
    enable: false #是否启用数据库
    drive: mysql #数据库类型
    dsn: root:root@tcp(127.0.0.1:3306)/operation?charset=utf8mb4&parseTime=True&loc=Local #连接dsn
    maxLifetime: 2h #最大生存时间
    maxOpenConn: 10 #最大连接数量
    maxIdleConn: 10 #最大空闲数量
    logLevel: 1 #日志等级
    slowThreshold: 2s #慢sql阈值

redis配置

可以通过ctx.Redis()进行使用,多个redis配置可以使用ctx.Redis('实例名称')

redis:
  catch: #redis实例名称,如有多个redis可新增
    enable: false #是否启用redis
    host: 127.0.0.1:6379 #redis地址
    username:  #连接账号
    password:  #连接密码

证书文件配置

在我们开发过程中,有很多需要去读取各种密钥的操作,而loader组件把这些操作进行简单话,可以通过以下快速获取。 ctx.Loader('实例名称') ctx.Loader("login")

loader:
  login: static/cert/login.key

并发池配置

可以通过ctx.Go() 进行快速使用

pool: #并非池配置
  size: 100000 #最大协程数量
  expiryDuration: 30s #过期时间
  preAlloc: true #是否预分配
  maxBlockingTasks: 1000 #最大的并发任务
  nonblocking: true #设置为true时maxBlockingTasks讲失效,不限制并发任务

邮箱配置

可使用 ctx.Email() 进行使用,在使用之前需要先配置邮箱相关参数

email: # 邮件发送相关配置
  template: #邮件模板
    captcha:  #邮件模板名称
      subject: 验证码发送通知 #邮件模板主题
      path: static/template/email/default.html #邮件模板路径
      from: xxx@qq.com
      type: "text/html" #文本内容格式
  user: xxx@qq.com #发送者
  host: smtp.qq.com #发送host
  port: 25  #发送端口
  name: 青柠校园 #发送着名称
  password: xxx # 发送者授权码

验证码配置

可以通过ctx.Captcha() 进行使用。

captcha:
  login:  #验证码名称
    type: image #验证码类型 目前支持image/email
    length: 6 #验证码长度
    expire: 180s #过期时间
    redis: cache #redis名称
    height: 801 #图片高度,仅image有效
    width: 240 #图片宽度,仅image有效
    skew: 0.7 #验证数字倾斜程度,仅image有效
    dotCount: 80 #干扰像素点数量,仅image有效
  changePassword:  #验证码名称
    type: email #验证码类型
    length: 6 #验证码长度
    expire: 180s #过期时间
    redis: cache #redis名称
    template: captcha #邮箱模板名称,仅email有效

JWT 访问鉴权配置 主要是用来判断用户是否有访问权限,只要配置了就会自动开启,可以使用ctx.JWT()进行生成token

jwt:
  redis: cache #redis名称
  secret: "limeschool" #密钥
  expire: 2h #过期时间
  renewal: 1s #续期时间
  whitelist: #忽略token校验以及鉴权的白名单
    POST:/v1/login/captcha: true #http 方法名:path  grpc GRPC:operation
    POST:/v1/login: true
    POST:/v1/logout: true
    POST:/v1/token/refresh: true

authentication 资源鉴权 主要是用来判断用户是否对某一些特殊接口是否具有权限

authentication:
  db: system #db名称
  redis: cache #redis名称
  roleKey: role_keyword #jwt中存储角色的关键字的下标
  skipRole: ["super_admin"] #跳过检查的角色
  whitelist:
    method:path: true

限流器配置

ratelimit: true #是否开启限流

Documentation

Index

Constants

View Source
const Release = "v2.7.0"

Release is the current kratos version.

Variables

This section is empty.

Functions

func NewContextFromApp

func NewContextFromApp(ctx context.Context, s AppInfo) context.Context

NewContextFromApp returns a new Context that carries value.

Types

type App

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

App is an application components lifecycle manager.

func New

func New(opts ...Option) *App

New create an application lifecycle manager.

func (*App) Config

func (a *App) Config() config.Config

Config returns service config.

func (*App) Endpoint

func (a *App) Endpoint() []string

Endpoint returns endpoints.

func (*App) ID

func (a *App) ID() string

ID returns app instance id.

func (*App) Metadata

func (a *App) Metadata() map[string]string

Metadata returns service metadata.

func (*App) Name

func (a *App) Name() string

Name returns service name.

func (*App) Run

func (a *App) Run() error

Run executes all OnStart hooks registered with the application's Lifecycle.

func (*App) Stop

func (a *App) Stop() (err error)

Stop gracefully stops the application.

func (*App) Version

func (a *App) Version() string

Version returns app version.

type AppInfo

type AppInfo interface {
	ID() string
	Name() string
	Version() string
	Metadata() map[string]string
	Endpoint() []string
	Config() config.Config
}

AppInfo is application context value.

func GetAppFromContext

func GetAppFromContext(ctx context.Context) (s AppInfo, ok bool)

GetAppFromContext returns the Transport value stored in ctx, if any.

type Context

type Context interface {
	Logger() *log.Helper
	DB(name ...string) *gorm.DB
	Go(runner pool.Runner) error
	Loader(name string) []byte
	Email() email.Email
	ClientIP() string
	Captcha() captcha.Captcha
	JWT() jwt.Jwt
	Token() string
	Authentication() authentication.Authentication
	Ctx() context.Context
	GetMetadata(string) string
	SetMetadata(key, value string)

	ID() string
	Name() string
	Version() string
	Metadata() map[string]string
	Config() config.Config
	Endpoint() []string

	Deadline() (deadline time.Time, ok bool)
	Done() <-chan struct{}
	Err() error
	Value(key any) any
}

func MustContext

func MustContext(c context.Context) Context

MustContext returns the Transport value stored in ctx, if any.

type LogField

type LogField map[string]any

type Option

type Option func(o *options)

Option is an application option.

func AfterStart

func AfterStart(fn func(context.Context) error) Option

AfterStart run funcs after app starts

func AfterStop

func AfterStop(fn func(context.Context) error) Option

AfterStop run funcs after app stops

func BeforeStart

func BeforeStart(fn func(context.Context) error) Option

BeforeStart run funcs before app starts

func BeforeStop

func BeforeStop(fn func(context.Context) error) Option

BeforeStop run funcs before app stops

func Config

func Config(source config.Source) Option

Config with service config.

func Endpoint

func Endpoint(endpoints ...*url.URL) Option

Endpoint with service endpoint.

func ID

func ID(id string) Option

ID with service id.

func LoggerWith

func LoggerWith(fields LogField) Option

LoggerWith with service logger with field.

func Metadata

func Metadata(md map[string]string) Option

Metadata with service metadata.

func Name

func Name(name string) Option

Name with service name.

func Registrar

func Registrar(r registry.Registrar) Option

Registrar with service registry.

func RegistrarServer

func RegistrarServer(fn registrarServerFn) Option

RegistrarServer with service register server.

func RegistrarTimeout

func RegistrarTimeout(t time.Duration) Option

RegistrarTimeout with registrar timeout.

func Server

func Server(srv ...transport.Server) Option

Server with transport servers.

func Signal

func Signal(sigs ...os.Signal) Option

Signal with exit signals.

func StopTimeout

func StopTimeout(t time.Duration) Option

StopTimeout with app stop timeout.

func Version

func Version(version string) Option

Version with service version.

Directories

Path Synopsis
api
cmd
kratos Module
env
contrib
registry/kubernetes
Package kuberegistry registry simply implements the Kubernetes-based Registry
Package kuberegistry registry simply implements the Kubernetes-based Registry
proto
Package proto defines the protobuf codec.
Package proto defines the protobuf codec.
xml
nolint:gomnd
nolint:gomnd
extra
internal
group
Package group provides a sample lazy load container.
Package group provides a sample lazy load container.
p2c
wrr

Jump to

Keyboard shortcuts

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