rady

package module
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2018 License: MIT Imports: 12 Imported by: 0

README

Welcome to Rady-framework!

Coverage Status Go Report Card Build Status Documentation

Example and Docs are under updating

What can rady do now?

  • Dependency injection (Include components and value in config file).
  • Structured route registration (annotation route. router, controller and middleware, can be embedded in other router).
  • Middleware registration.
  • Initialize components in factory function.
  • Entities registration.
  • Config file hot-reload (Include factories' recall).
  • Some wrappers (cors, jwt, logger) for echo-middleware.
  • DI test
  • Env-dependent config file

Todos

  • Complete lifetime system for beans

  • Gorm integration (In project rorm).

  • Integration with htest

  • Editor plugin (Goland and vscode):

    • Tag indecator.
    • Route inspection.
    • Injection inspection.
    • Config file injection inspection (Can jump between config and code).
  • AOP

  • More middleware wrappers

  • Cache

  • Dashbord

  • Cloud

Documentation

Overview

Package rady provides framework for web developer

The Rady Framework is a spring like web framework base on echo-framework

Index

Constants

View Source
const (
	// COMPONENT is a tag to mark a field as a Component
	COMPONENT = "component"

	// CONFIGURATION is a tag to mark a field as a Configuration
	CONFIGURATION = "configuration"

	// SERVICE is a tag to mark a field as a Service
	SERVICE = "service"

	// CONTROLLER is a tag to mark a field as a Controller
	CONTROLLER = "controller"

	// ROUTER is a tag to mark a field as a Router
	ROUTER = "router"

	// MIDDLEWARE is a tag to mark a field as a Middleware
	MIDDLEWARE = "middleware"

	// HANDLER is a tag to mark a field as a Handler
	HANDLER = "handler"

	// REPOSITORY is a tag to mark a field as a Repository
	REPOSITORY = "repository"

	// DATABASE is a tag to mark a field as a Database
	DATABASE = "database"
)
View Source
const (
	// DefaultPath is the path of config file for default
	DefaultPath = "./resources/application.conf"

	DefaultConfType = YAML

	// YAML is the suffix of yaml file
	YAML = "yaml"

	// JSON is the suffix of json file
	JSON = "json"
)
View Source
const (
	ModeEnv         = "RADY_MODE"
	AutoRollbackEnv = "RADY_ROLLBACK"
	TestMod         = "test"
	AutoRollback    = "true"
)
View Source
const (
	PreInit  = "PreInit"
	PostInit = "PostInit"
)
View Source
const (
	GetStr     = "Get"
	PostStr    = "Post"
	PutStr     = "Put"
	HeadStr    = "Head"
	DeleteStr  = "Delete"
	ConnectStr = "Connect"
	OptionsStr = "Options"
	TraceStr   = "Trace"
	PatchStr   = "Patch"
)
View Source
const ENTITIES = "entities"

ENTITIES is a tag to mark a field as a Entities

View Source
const TESTING = "testing"

Variables

View Source
var (
	// COMPONENTS is a map to check if a field is COMPONENT, SERVICE or REPOSITORY
	COMPONENTS = make(map[string]bool)

	// ComponentTypes is a map to check if a struct is Component, Service, Repository or Parameter
	ComponentTypes = make(map[reflect.Type]bool)
)
View Source
var (
	INT         int64
	UINT        uint64
	FLOAT       float64
	STRING      string
	BOOL        bool
	TIME        time.Time
	ARRAY       []gjson.Result
	MAP         map[string]gjson.Result
	ArrayInt    []int64
	ArrayUint   []uint64
	ArrayFloat  []float64
	ArrayString []string
	ArrayBool   []bool
	ArrayTime   []time.Time

	IntType            = reflect.TypeOf(INT)
	UintType           = reflect.TypeOf(UINT)
	FloatType          = reflect.TypeOf(FLOAT)
	StringType         = reflect.TypeOf(STRING)
	BoolType           = reflect.TypeOf(BOOL)
	TimeType           = reflect.TypeOf(TIME)
	ArrayType          = reflect.TypeOf(ARRAY)
	ArrayIntType       = reflect.TypeOf(ArrayInt)
	ArrayUintType      = reflect.TypeOf(ArrayUint)
	ArrayFloatType     = reflect.TypeOf(ArrayFloat)
	ArrayStringType    = reflect.TypeOf(ArrayString)
	ArrayBoolType      = reflect.TypeOf(ArrayBool)
	ArrayTimeType      = reflect.TypeOf(ArrayTime)
	MapType            = reflect.TypeOf(MAP)
	IntPtrType         = reflect.TypeOf(&INT)
	UintPtrType        = reflect.TypeOf(&UINT)
	FloatPtrType       = reflect.TypeOf(&FLOAT)
	StringPtrType      = reflect.TypeOf(&STRING)
	BoolPtrType        = reflect.TypeOf(&BOOL)
	TimePtrType        = reflect.TypeOf(&TIME)
	ArrayPtrType       = reflect.TypeOf(&ARRAY)
	MapPtrType         = reflect.TypeOf(&MAP)
	ArrayIntPtrType    = reflect.TypeOf(&ArrayInt)
	ArrayUintPtrType   = reflect.TypeOf(&ArrayUint)
	ArrayFloatPtrType  = reflect.TypeOf(&ArrayFloat)
	ArrayStringPtrType = reflect.TypeOf(&ArrayString)
	ArrayBoolPtrType   = reflect.TypeOf(&ArrayBool)
	ArrayTimePtrType   = reflect.TypeOf(&ArrayTime)

	GJsonPtrTypesSet = map[reflect.Type]bool{
		IntPtrType:         true,
		UintPtrType:        true,
		FloatPtrType:       true,
		StringPtrType:      true,
		BoolPtrType:        true,
		TimePtrType:        true,
		ArrayPtrType:       true,
		MapPtrType:         true,
		ArrayIntPtrType:    true,
		ArrayUintPtrType:   true,
		ArrayFloatPtrType:  true,
		ArrayStringPtrType: true,
		ArrayBoolPtrType:   true,
		ArrayTimePtrType:   true,
	}

	GJsonTypesSet = map[reflect.Type]bool{
		IntType:         true,
		UintType:        true,
		FloatType:       true,
		StringType:      true,
		BoolType:        true,
		TimeType:        true,
		ArrayType:       true,
		MapType:         true,
		ArrayIntType:    true,
		ArrayUintType:   true,
		ArrayFloatType:  true,
		ArrayStringType: true,
		ArrayBoolType:   true,
		ArrayTimeType:   true,
	}
)
View Source
var (
	StrToMethod = map[string]interface{}{
		GetStr:     GET{},
		PostStr:    POST{},
		PutStr:     PUT{},
		HeadStr:    HEAD{},
		DeleteStr:  DELETE{},
		ConnectStr: CONNECT{},
		OptionsStr: OPTIONS{},
		TraceStr:   TRACE{},
		PatchStr:   PATCH{},
	}
	MethodToStr = map[interface{}]string{
		GET{}:     GetStr,
		POST{}:    PostStr,
		PUT{}:     PutStr,
		HEAD{}:    HeadStr,
		DELETE{}:  DeleteStr,
		CONNECT{}: ConnectStr,
		OPTIONS{}: OptionsStr,
		TRACE{}:   TraceStr,
		PATCH{}:   PatchStr,
	}

	MethodsTypeSet = make(map[reflect.Type]string)
)
View Source
var (
	FileType   = reflect.TypeOf(FILE{})
	StaticType = reflect.TypeOf(STATIC{})
)

Functions

func CheckComponents

func CheckComponents(field reflect.StructField) bool

CheckComponents return true when type in its tag is in COMPONENTS or ContainsFields(field.Type.Elem(), ComponentTypes)

func CheckConfiguration

func CheckConfiguration(field reflect.StructField) bool

CheckConfiguration return true when type in its tag is CONFIGURATION or ContainsField(field.Type.Elem(), Configuration{})

func CheckController

func CheckController(field reflect.StructField) bool

CheckController return true when type in its tag is CONTROLLER or ContainsField(field.Type.Elem(), Controller{})

func CheckEntities

func CheckEntities(field reflect.StructField) bool

CheckEntities return true when type in its tag is entities or ContainsField(field.Type.Elem(), Entities{})

func CheckFieldPtr

func CheckFieldPtr(fieldType reflect.Type) bool

CheckFieldPtr return true when fieldType is kind of Ptr

func CheckFilenameValid

func CheckFilenameValid(Name string) bool

func CheckMiddleware

func CheckMiddleware(field reflect.StructField) bool

CheckMiddleware return true when type in its tag is MIDDLEWARE or ContainsField(field.Type.Elem(), Middleware{})

func CheckPtrOfStruct added in v0.4.0

func CheckPtrOfStruct(fieldType reflect.Type) bool

func CheckPtrValues added in v0.4.0

func CheckPtrValues(field reflect.StructField) bool

func CheckRouter

func CheckRouter(field reflect.StructField) bool

CheckRouter return true when type in its tag is ROUTER or ContainsField(field.Type.Elem(), Router{})

func CheckStruct

func CheckStruct(fieldType reflect.Type) bool

func CheckTesting added in v0.4.0

func CheckTesting(field reflect.StructField) bool

CheckTesting return true when type in its tag is TESTING or ContainsField(field.Type.Elem(), Testing{})

func CheckValues

func CheckValues(field reflect.StructField) bool

func ConfirmAddBeanMap

func ConfirmAddBeanMap(BeanMap map[reflect.Type]map[string]*Bean, fieldType reflect.Type, name string) bool

ConfirmAddBeanMap return true when BeanMap[fieldType] == nil or BeanMap[fieldType][name] doesn't exist

and this function will make a map if BeanMap[fieldType] == nil

func ConfirmBeanInMap

func ConfirmBeanInMap(BeanMap map[reflect.Type]map[string]*Bean, fieldType reflect.Type, name string) bool

ConfirmBeanInMap return true when BeanMap[fieldType][name] exist

func ConfirmSameTypeInMap

func ConfirmSameTypeInMap(BeanMap map[reflect.Type]map[string]*Bean, fieldType reflect.Type) bool

ConfirmSameTypeInMap return true when len(BeanMap[fieldType]) > 0

and this function will also make a map if BeanMap[fieldType] == nil, but return false

func ContainsField

func ContainsField(Mother reflect.Type, field interface{}) bool

ContainsField return true when Mother has a child as same type as filed

func ContainsFields

func ContainsFields(Mother reflect.Type, Set map[reflect.Type]bool) bool

ContainsFields return true when Mother has a child with a type Set contains

func GetBeanName

func GetBeanName(Type reflect.Type, tag reflect.StructTag) string

GetBeanName get name from tag or from Type

func GetConfigFileByMode added in v0.4.0

func GetConfigFileByMode(filePath string) string

func GetDynamicPath

func GetDynamicPath(upper string) string

func GetJSONFromAnyFile

func GetJSONFromAnyFile(path string, fileType string) (string, error)

GetJSONFromAnyFile can get json string from file

This function work well only when:

  1. fileType == "yaml" or (fileType != "json" and path end with ".yml" or ".yaml"), and content in file is yaml
  2. content in file is json

func GetModeEnv added in v0.4.0

func GetModeEnv() string

func GetNewPrefix

func GetNewPrefix(prefix string, path string) string

func GetPathFromType

func GetPathFromType(field reflect.StructField, Type interface{}) string

func GetTagFromName

func GetTagFromName(name string) reflect.StructTag

GetTagFromName generate tag from name

func IsAutoRollback added in v0.4.0

func IsAutoRollback() bool

func IsStringAllUpper

func IsStringAllUpper(str string) bool

func IsTestMode added in v0.4.0

func IsTestMode() bool

func ParseHandlerName

func ParseHandlerName(Name string) (ok bool, method interface{}, path string)

func ResetEnv added in v0.4.0

func ResetEnv(key string)

func SplitByUpper

func SplitByUpper(raw string) []string

Types

type Application

type Application struct {
	BootStrap
	Root            interface{}
	BeanMap         map[reflect.Type]map[string]*Bean
	BeanMethodMap   map[reflect.Type]map[string]*Method
	ValueBeanMap    map[string]*ValueBean
	FactoryToRecall map[*Method]bool
	CtrlBeanMap     map[string]*CtrlBean
	MdWareBeanMap   map[string]*MdWareBean
	Entities        []reflect.Type
	TestingBeans    []*TestingBean
	Server          *echo.Echo
	Logger          *Logger
	ConfigFile      string
	Addr            *string `value:"rady.server.addr" default:":8081"`
}

Application is the bootstrap of a Rady app

Root is pointer of app for config, controller and handler registry

BeanMap is map to find *Bean by `Type` and `Name`(when type is the same)

value in bean is Elem(), can get Addr() when set to other field

BeanMethodMap is map to find *Method by `Type` and `Name`(when type is the same)

Value in method can be call later to set value to other filed

ValueBeanMap is map to find / set value in config file, going to implement hot-reload

CtrlBeanMap is slice to store controller

MdWareBeanMap is slice to store middleware

Entities is slice to store type of entity

Server is the echo server

Logger is the global logger

ConfigFile is the string json value of config file

func CreateApplication

func CreateApplication(root interface{}) *Application

CreateApplication can initial application with root

if root is not kinds of Ptr, there will be an error

func CreateTest added in v0.4.1

func CreateTest(root interface{}) *Application

func (*Application) AddTest added in v0.4.0

func (a *Application) AddTest(testPointer interface{}) *Application

func (*Application) AddTests added in v0.4.0

func (a *Application) AddTests(testPointer interface{}) *Application

func (*Application) CallFactory

func (a *Application) CallFactory()

func (*Application) GetRealConfigPathAndType added in v0.4.2

func (a *Application) GetRealConfigPathAndType() (string, string)

func (*Application) LoadBean

func (a *Application) LoadBean(fieldType reflect.Type, fieldValue reflect.Value, tag reflect.StructTag) *Application

LoadBean can load normal bean

normal bean can have a name, only if there is a prime bean with same name and type, and this method will do nothing

if a normal bean doesn't a name

  1. there is only one loaded bean with the same type, this method do nothing

  2. there are more than one loaded bean with the same type, error and exit

  3. there is no loaded bean with the same type, this method with initialize a new bean

func (*Application) LoadPrimeBean

func (a *Application) LoadPrimeBean(fieldType reflect.Type, fieldValue reflect.Value, tag reflect.StructTag) bool

LoadPrimeBean as its name

load field in configuration and out of beanMethod in configuration

func (*Application) Prepare added in v0.4.0

func (a *Application) Prepare() *Application

func (*Application) PrepareTest added in v0.4.0

func (a *Application) PrepareTest() *Application

func (*Application) RecursivelyLoad

func (a *Application) RecursivelyLoad(fieldType reflect.Type)

RecursivelyLoad recursively load children of a normal bean

only if there is no prime bean among the children

func (*Application) ReloadValues

func (a *Application) ReloadValues()

func (*Application) Run

func (a *Application) Run()

Run is the boot method of a whole Rhapsody app

Start with the Root, Get Fields of Root

First, we load "PrimeBean", which mean field define in config, are basic of all bean

PrimeBean include all component Fields in config, which can defined unique name

Then, we load BeanMethodOut, which mean result of "bean method", however, what's bean method?

Bean method mean methods defined in config, return only bean(component), and all parameters can init with dependency injection

returned value of Bean method is same as PrimeBean

parameter value is same as normal field

And then, we load normal bean recursively

func (*Application) Test added in v0.4.0

func (a *Application) Test(t *testing.T) *Application

func (*Application) WriteConfigFile added in v0.4.2

func (a *Application) WriteConfigFile(value string) error

type Bean

type Bean struct {
	Tag   reflect.StructTag
	Value reflect.Value
}

Bean contains the value and tag of a type

func NewBean

func NewBean(Value reflect.Value, Tag reflect.StructTag) *Bean

NewBean is factory function of Bean

type BootStrap

type BootStrap struct {
}

BootStrap is a tag to mark a struct as a Bootstrap

type CONF

type CONF struct {
}

CONF is a tag of Boot to define the path and type of config file

Usage:

type Root struct {
	CONF `path:"./resources/app.conf" type:"yaml"`
}

func main() {
	CreateApplication(new(Root)).Run()
}

type CONNECT

type CONNECT struct {
}

CONNECT is a tag to mark a method with path and http CONNECT method

type Component

type Component struct {
}

Component is a tag to mark a struct as a Component

type Configuration

type Configuration struct {
}

Configuration is a tag to mark a struct as a Configuration

type Context

type Context = echo.Context

type Controller

type Controller struct {
}

Controller is a tag to mark a struct as a Controller

type CtrlBean

type CtrlBean struct {
	Name  string
	Value reflect.Value
	Tag   reflect.StructTag
}

CtrlBean contains value and tag of a controller

func NewCtrlBean

func NewCtrlBean(Value reflect.Value, Tag reflect.StructTag, Name string) *CtrlBean

NewCtrlBean is factory function of CtrlBean

type DELETE

type DELETE struct {
}

DELETE is a tag to mark a method with path and http DELETE method

type Database added in v0.4.0

type Database struct {
}

Database is a tag to mark a struct as a Database

type Entities

type Entities struct {
}

Entities is a tag to mark a struct as a Entities

type FILE

type FILE struct {
}

FILE is a tag to bind a path with a file

Usage:

type UserController struct {
	Controller 	`prefix:"api/v1"`
	FILE		`path:"static" file:"./index.html"`
}

type Root struct {
	UserController
}

func main() {
	CreateApplication(new(Root)).Run()
}

type GET

type GET struct {
}

GET is a tag to mark a method with path and http GET method

Usage:

type UserController struct {
	Controller 	`prefix:"api/v1"`
	GET 		`path:":id" method:"GetUserInfo"`
}

func (u *UserController) GetUserInfo(ctx echo.Context) error {
	// do something
}

type Root struct {
	*UserController
}

func main() {
	CreateApplication(new(Root)).Run()
}

type Group

type Group = echo.Group
type HEAD struct {
}

HEAD is a tag to mark a method with path and http HEAD method

type Handler

type Handler struct {
}

Handler is a tag to mark a struct as a Handler

type HandlerFunc

type HandlerFunc = echo.HandlerFunc

type Logger

type Logger struct {
	*logging.Logger
}

Logger is a logger base on `github.com/op/go-logging`

func NewLogger

func NewLogger() *Logger

NewLogger is the factory function of Logger

type MdWareBean

type MdWareBean struct {
	Name  string
	Value reflect.Value
	Tag   reflect.StructTag
}

MdWareBean contains value and tag of a middleware

func NewMdWareBean

func NewMdWareBean(Value reflect.Value, Tag reflect.StructTag, Name string) *MdWareBean

NewMdWareBean is factory function of MdwareBean

type Method

type Method struct {
	Value    reflect.Value
	Ins      []reflect.Type
	Name     string
	OutValue reflect.Value
	InValues []reflect.Value
}

Method contains value, param list and name of a 'BeanMethod'

func NewBeanMethod

func NewBeanMethod(Value reflect.Value, Name string) *Method

NewBeanMethod is factory function of Method

func (*Method) Call

func (m *Method) Call(app *Application)

func (*Method) LoadIns

func (m *Method) LoadIns(app *Application)

type Middleware

type Middleware struct {
}

Middleware is a tag to mark a struct as a Middleware

type MiddlewareFunc

type MiddlewareFunc = echo.MiddlewareFunc

type OPTIONS

type OPTIONS struct {
}

OPTIONS is a tag to mark a method with path and http OPTIONS method

type PATCH

type PATCH struct {
}

PATCH is a tag to mark a method with path and http PATCH method

type POST

type POST struct {
}

POST is a tag to mark a method with path and http POST method

type PUT

type PUT struct {
}

PUT is a tag to mark a method with path and http PUT method

type Parameter

type Parameter struct {
}

Parameter is a tag to mark a struct as a Parameter

type Repository

type Repository struct {
}

Repository is a tag to mark a struct as a Repository

type Router

type Router struct {
}

Router is a tag to mark a struct as a Router

type STATIC

type STATIC struct {
}

STATIC is a tag bind a prefix with a directory

type Service

type Service struct {
}

Service is a tag to mark a struct as a Service

type TRACE

type TRACE struct {
}

TRACE is a tag to mark a method with path and http TRACE method

type Testing added in v0.4.0

type Testing struct {
}

Testing is a tag to mark a struct as a Testing

type TestingBean added in v0.4.0

type TestingBean struct {
	Type  reflect.Type
	Value reflect.Value
}

Testing is a tag to mark a struct as a Testing

func NewTestingBean added in v0.4.0

func NewTestingBean(Type reflect.Type, Value reflect.Value) *TestingBean

type ValueBean

type ValueBean struct {
	Value     gjson.Result
	ValueMap  map[reflect.Type]reflect.Value
	MethodSet map[*Method]bool
	Key       string
	Default   gjson.Result
}

ValueBean contains value from config file parsed by 'gjson'

ValueMap is different types the value converted to

ParamSlice is the param list contain this value

func NewValueBean

func NewValueBean(Value gjson.Result, key string, defaultValue gjson.Result) *ValueBean

NewValueBean is factory function of ValueBean

func (*ValueBean) Reload

func (v *ValueBean) Reload(a *Application)

func (*ValueBean) SetValue

func (v *ValueBean) SetValue(value reflect.Value, Type reflect.Type) bool

Jump to

Keyboard shortcuts

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