quick

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2021 License: MIT Imports: 26 Imported by: 0

README

quick

Installation

go get github.com/hiwjd/quick

Example

package main

import (
	"context"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"time"

	"github.com/hiwjd/quick"
	"github.com/labstack/echo/v4"
)

func main() {
	app := quick.NewApp(quick.Config{
		APIAddr:  ":5555",
		MysqlDSN: "root:@/test?charset=utf8&parseTime=True&loc=Local",
		Redis: quick.Redis{
			Addr:     "127.0.0.1:6379",
			Password: "",
			DB:       0,
		},
	})
	app.RegisterModules(
		quick.ModuleFunc(demoModule),
	)
	close := app.Start()

	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt)
	<-sig

	app.Logf("[INFO] Start closing")

	close()
}

type Comment struct {
	ID uint `gorm:"primaryKey"`
	Content string `gorm:"varchar(100)"`
	CreatedAt time.Time
}

func demoModule(ac quick.AppContext) {
	// register HTTP GET router
	ac.GET("/hello", func(c echo.Context) error {
		return c.String("world")
	})

	// register HTTP POST router
	ac.POST("/comment", func(c echo.Context) error {
		content := c.FormValue("content")
		comment := Comment{
			Content: content,
			CreatedAt: time.Now(),
		}
		if err := ac.GetDB().Save(&comment).Error; err != nil {
			return echo.NewHTTPError(500, "failed")
		}
		return comment
	})

	// register schedule job
	ac.Schedule("*/5 * * * * *", func(c context.Context) error {
		ac.Logf("job scheduled")

		// publish events
		ac.Publish("job-scheduled", "some payload")
	})

	// subscribe events
	ac.Subscribe("job-scheduled", func(payload string) {
		ac.Logf(payload) // some payload
	})

	// register shutdown hook
	ac.RegisterShutdown(func() {
		ac.Logf("shutdown...")
	})
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnsupported 表示Checker遇到了不支持的情况
	ErrUnsupported = errors.New("Checker not support this type")
)

Functions

func Check

func Check(v interface{}) error

Check 调用默认实现的Check

func NewCustomHTTPErrorHandler

func NewCustomHTTPErrorHandler(e *echo.Echo, logf Logf) echo.HTTPErrorHandler

NewCustomHTTPErrorHandler 构造 echo.HTTPErrorHandler

func NewCustomValidator

func NewCustomValidator() echo.Validator

NewCustomValidator 构造echo.Validator实例

Types

type App

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

func New

func New(config Config) *App

New 构造App

func (*App) Context

func (a *App) Context() Context

func (*App) Logf

func (a *App) Logf(format string, args ...interface{})

func (*App) Migrate

func (a *App) Migrate(migrators ...Migrator)

func (*App) RegisterModules

func (a *App) RegisterModules(modules ...Module)

RegisterModules 注册模块,详情见Module

func (*App) Start

func (a *App) Start() func()

Start 启动服务,并返回停止服务的方法 内部会根据配置启动HTTP服务、定时任务服务

type BizErr

type BizErr struct {
	Type ErrType
	// contains filtered or unexported fields
}

func NewBadArgs

func NewBadArgs(code string, cause error) BizErr

func NewSrvErr

func NewSrvErr(code string, cause error) BizErr

func (BizErr) Caller

func (be BizErr) Caller() (file string, line int, fn string)

func (BizErr) Error

func (be BizErr) Error() string

func (BizErr) Is

func (be BizErr) Is(err error) bool

func (BizErr) Unwrap

func (be BizErr) Unwrap() error

type Checker

type Checker interface {
	// Check 校验v,并返回结构化的错误信息ErrorArray或者其他error
	Check(v interface{}) error
}

Checker 校验器

func NewChecker

func NewChecker(ruleTagName, titleTagName string, errorMsgMap map[string]string) Checker

New 返回Checker实例

type Config

type Config struct {
	APIAddr     string `toml:"api_addr"`
	MysqlDSN    string `toml:"mysql_dsn"`
	EnableDBLog bool   `toml:"enable_db_log"`
	Log         Log    `toml:"log"`
	Redis       Redis  `toml:"redis"`
}

Config 配置

func MustLoadConfig

func MustLoadConfig(fn string) Config

MustLoadConfig 读取配置

type Context

type Context interface {
	// GET 注册HTTP GET路由
	GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc)
	// POST 注册HTTP POST路由
	POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc)
	// 注册中间件
	Use(middlewares ...echo.MiddlewareFunc)
	// Schedule 注册定时任务
	Schedule(expr string, job Job)
	// Publish 发布事件
	Publish(topic string, payload string)
	// Subscribe 订阅事件
	Subscribe(topic string, cb func(string))
	// GetDB 获取数据库连接实例
	GetDB() *gorm.DB
	// GetRedis 获取Redis连接实例
	GetRedis() *redis.Client
	// Logf 日志方法
	Logf(format string, args ...interface{})
	// Provide 提供资源,和Take配套使用
	Provide(id string, obj interface{})
	// Take 获取资源,即通过Provide提供的资源
	Take(id string) interface{}
	// RegisterShutdown 注册停止服务前调用的方法
	// 当服务停止时,会先停止HTTP服务、定时任务、事件系统,当这3者停止后,
	// 调用通过ReigsterShutdown注册的方法
	RegisterShutdown(hook OnShutdown)
}

Context 是模块初始化时可获取的资源和可调用的方法

type ErrType

type ErrType int
const (
	BadArgs ErrType = iota
	SrvErr
)

type ErrorArray

type ErrorArray []ErrorData

ErrorArray 是字段的错误信息

func (ErrorArray) Error

func (eArr ErrorArray) Error() string

type ErrorData

type ErrorData struct {
	Field  string   `json:"field"`  // 字段
	Title  string   `json:"title"`  // 字段标题
	Errors []string `json:"errors"` // 错误
}

ErrorData 是某个字段的校验错误

type FineErr

type FineErr struct {
	Code    int
	Message string
	Caller  string
	// contains filtered or unexported fields
}

FineErr 是一个可以对用户友好点的错误

func NewFineErr

func NewFineErr(code int, message string) *FineErr

NewFineErr 构造FineErr

func TraceError

func TraceError(err error) *FineErr

func (*FineErr) Error

func (fe *FineErr) Error() string

func (*FineErr) SetError

func (fe *FineErr) SetError(err error) *FineErr

SetError 设置err

type Job

type Job func(context.Context) error

Job 是定时任务

type Log

type Log struct {
	Level      string `toml:"level"`       // 日志级别
	Output     string `toml:"output"`      // 文件路径(例子:log/http.log)或者`stdout`
	MaxSize    int    `toml:"max_size"`    // 单个日志文件的大小上限,单位MB
	MaxBackups int    `toml:"max_backups"` // 最多保留几个日志文件
	MaxAge     int    `toml:"max_age"`     // 保留天数
	Compress   bool   `toml:"compress"`    // 是否压缩
}

Log 日志配置

type Logf

type Logf func(format string, args ...interface{})

type Migrator

type Migrator func(db *gorm.DB) error

Migrator 迁移表

type Module

type Module interface {
	Init(ac Context)
}

Module 是模块 设定这个接口的作用是把繁杂的系统组成分离成独立的部分 对具体什么是模块并没有任何约束,可以:

提供HTTP服务
执行定时任务
独立存在的一段for循环
仅仅打印一段话
等等

只要最终包装成Module接口传入RegisterModules方法即可 可以查看samples中的项目找找感觉

func Provide

func Provide(id string, obj interface{}) Module

Provide 和Context.Provide拥有相同的功能,即注册资源到Context中 该方法返回Module,因此可以做为创建模块的快捷方式 比如这样使用: app.RegisterModules(quick.Provide("id-res1", obj))

type ModuleFunc

type ModuleFunc func(ac Context)

ModuleFunc 方便把方法转换成Module

func (ModuleFunc) Init

func (mf ModuleFunc) Init(ac Context)

Init 实现Module

type OnShutdown

type OnShutdown func()

OnShutdown 在App停止前执行的方法

type PubSub

type PubSub interface {
	// 发布事件
	Publish(topic string, payload string)
	// 订阅事件
	Subscribe(topic string, cb func(string))
	// 关闭
	Close()
}

type Redis

type Redis struct {
	Addr     string `toml:"addr"`
	Password string `toml:"password"`
	DB       int    `toml:"db"`
}

Redis redis配置

Directories

Path Synopsis
contrib
samples
sms

Jump to

Keyboard shortcuts

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