Panizza

package module
v0.0.0-...-c404136 Latest Latest
Warning

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

Go to latest
Published: May 20, 2020 License: MIT Imports: 20 Imported by: 3

README

PANIZZA

web https://cp-panizza.github.io/Panizza/

Quickly to build a restapi web application!!!

QUICK START

Install panizza

go get github.com/CP-Panizza/Panizza

Add panizza to environment variable path

Path=${GOPATH}\src\github.com\CP-Panizza\Panizza\bin

Open cmd

Pan -n "your project name like `my_first_pro`"

And then, the cli created a project named my_first_pro on the current path,like this:

/my_first_pro
        |--src
            |--/conf
            |     |__application.conf 
            |
            |--/initPro
            |        |__initPro.go
            |
            |--/resource
            |
            |__my_first_pro.go

Finally, open browser enter http://127.0.0.1:8080, you will see the welcome page of Panizza!

Document

Controller & Service

First,make a dir named controller and defind tow structs as controller and service:

package controller

import(
    ."github.com/CP-panizza/panizza"
)

//@Controller
type MyController struct{
    Hello Handle `methods:"GET" path:"/hello" inject:"Hello"`
}

//@Service
type MyService struct {
    DB *sql.DB `inject:"db"`
}

func (this *MyService)Hello(ctx *HandleContext){
    ctx.JSON_write(200, JSONObject{
        "msg": "hello!",
    })
}

  We can use //@Controller to mark struct MyController as a controller, MyController like a interface, method is assign the http method, has GET, POST, PUT, DELETE...
tip: betwen // and @ do not has space!!
  And then, we defind a struct who has a function named Hello to implement MyController's Helle inline function.
Open cmd and goto my_first_pro direction enter order:

Pan -c    # -c it means complie.

This order is auto complie the components for current project. Add the MyController and MyService to the Ioc as a component.

Finally, build my_first_pro.go and run, visit the http://127.0.0.1:8080/mycontroller/hello
you will get the result.

 {"msg": "hello!"}

tip:  panizza support @Controller,@Service,@Filter,@Aspect.All of them are called component.

If you make a new component,must be run the order Panizza -c to make it work!!!

project config

A project has a config file, it name is application.conf and in this file has three already exsist varibles.
PROJECT_PACKAGE: your project's rootpath.
PORT: your app listening port.
FILE_SERVER: your file rootpath.
you can set the 'inject' tag on your component field to get config.

Example:

application.conf

APPID=wx264sd6sd844c

Service.go

//@Service
type MyService struct{
    AppId string `inject:"APPID"`  //you can get the config by inject:"APPID" tag
}

func (this *MyService)Handle(ctx *HandleContext){
        fmt.Println(this.AppId) //wx264sd6sd844c
}

And you can defind another data type in config like this:

#[]string
MYLIST=[aaaa,bbbb,cccc,dddd]
#map[string]string
MYMAP={name:aaaa,school:bbb}

inject

It likes springboot's @AotoWired

Set it on your component field like this:

//@Service
type MyService struct{
    GormDB *gorm.DB `inject:"db"`
}

ioc will inject value into that field.

Add been to Ioc.

You can defind a function to add a been to ioc by use @Been:

var db *gorm.DB

//db will be add to ioc. and you can use `inject:"gorm_db"` tag get this been.
//@Been(name="gorm_db")
func DB_Been()interface{}{
	return db
}

func init() {
	var err error
	db, err = gorm.Open("mysql", "localhost:3306@xxxxxx")
	if err != nil {
		panic(err)
	}

	db.DB().SetMaxIdleConns(10)

	db.DB().SetMaxOpenConns(100)

	if err := db.DB().Ping(); err != nil {
		panic("connect err!")
	}

	fmt.Println("connect seccess!")
}

router group

type MyController struct{
    Hello Handle `method:"GET" path:"/Hello" inject:"Hello"`
    World Handle `method:"GET" path:"/World" inject:"World"`
    Say Handle `method:"GET" path:"/Say" inject:"Say"`
}
//accordding to this controller struct,the router default perfix is struct name,
//the router is build to /MyController/Hello, /MyController/World,/MyController/Say
//if you want to change router perfix, you can make MyController implement method "GroupName()string" like this:

func (this *MyController)GroupName()string {
	return "xxx"
}
//the router is build to /xxx/Hello, /xxx/World,/xxx/Say

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	IocInstance        = NewIoc() //导入ioc包的时候实例化的全局单例
	ErrFactoryNotFound = errors.New("factory not found")
)
View Source
var ApiTemplate1 = `` /* 1078-byte string literal not displayed */
View Source
var ApiTemplate2 = `` /* 1202-byte string literal not displayed */
View Source
var Aspecters = sync.Map{}

全局存放注册的Aspect

View Source
var GlobalApi = APIManeger{
	APIMapper: []API{},
	APILength: 0,
}
View Source
var IsOpenController bool = false

controller开启

Functions

func DeepCopy

func DeepCopy(dst, src interface{}) error

func Existe

func Existe(path string) bool

判断访问的文件路径是否存在

func FindFilesFromStartPath

func FindFilesFromStartPath(startPath string, rightFileName string, outStr *[]string)

从给定的目录下寻找某个文件,返回该文件绝对路径

func FindProjectPathByPKGName

func FindProjectPathByPKGName(projectPKG string) string

func FindPropertiesFile

func FindPropertiesFile(confFileName string) string

寻找application.conf配置文件

func FindStaticPath

func FindStaticPath(ProjectPath string, rightPath string, outStr *string)

从给定的目录下寻找某个文件夹,结果为该文件夹的绝对路径

func GetFunctionName

func GetFunctionName(i interface{}) string

出入一个函数指针,返回函数名字

func Inject

func Inject(instance interface{})

提供外部调用依赖注入,传入实例指针

func IsDir

func IsDir(path string) bool

func PanizzaWelcomePage

func PanizzaWelcomePage() string

func ReadConfigFromProperties

func ReadConfigFromProperties(propertiesPath string) map[string]interface{}

func RegistAspecter

func RegistAspecter(aspect interface{})

传入Aspect指针,注册Aspect

func RegisterComponents

func RegisterComponents(been interface{})

传入结构体指针,向ioc容器注册组件

func RegisterController

func RegisterController(i interface{}) interface{}

注册controller,传入结构体指针,此函数不应该recover():此函数运行成功就能保证运用运行起来

func RegisterService

func RegisterService(s interface{}) interface{}

注册service,传入service结构体指针

func UseTimePrint

func UseTimePrint(ctx *HandleContext) func()

用于打印程序执行时间

Types

type API

type API struct {
	Method      string
	URL         string
	Description string
	Param       []string
	Location    string
}

func (*API) String

func (a *API) String() string

type APIManeger

type APIManeger struct {
	APIMapper []API
	APILength int
}

func (*APIManeger) Add

func (api *APIManeger) Add(Method string, URL string, Description string, Param []string, Location string)

func (*APIManeger) ToHtmlFile

func (api *APIManeger) ToHtmlFile(saveFilePath string)

传入保存的文件的绝对路径

func (*APIManeger) ToHtmlString

func (api *APIManeger) ToHtmlString() string

生成API文档字符串

type Aspect

type Aspect interface {
	Config() string                                                    //配置切面 return "xxxxx|xxxxx|xxxxx"  xxxxx表示需要配置的目标函数名称
	Before(ctx *HandleContext, HandleName string)                      //目标方法执行之前执行
	After(ctx *HandleContext, HandleName string)                       //目标方法执行之后执行
	AfterPanic(err interface{}, ctx *HandleContext, HandleName string) //目标方法出现异常后执行
}

type Configer

type Configer map[string]interface{}
var AppConfig Configer

全局配置实例

func (*Configer) GetConfiger

func (c *Configer) GetConfiger(key string) (interface{}, bool)

通过key获取配置文件中的配置

type ExceptionHandle

type ExceptionHandle struct {
}

func (*ExceptionHandle) ExceptionHandleRegist

func (e *ExceptionHandle) ExceptionHandleRegist()

type Filter

type Filter interface {
	Use(i interface{})
	RunFilter(ctx *HandleContext)
}

--------------------------------------------------------------------------------------------- Filter interface

type FilterFun

type FilterFun func(w http.ResponseWriter, r *http.Request, Data sync.Map) bool

--------------------------------------------------------------------------------------------- 静态资源访问的过滤器函数

type FilterImpl

type FilterImpl struct {
	FilterHandles []Handle
}

func (*FilterImpl) RunFilter

func (mw *FilterImpl) RunFilter(ctx *HandleContext)

func (*FilterImpl) Use

func (mw *FilterImpl) Use(s interface{})

type Handle

type Handle func(ctx *HandleContext)

处理函数类型预定义

func RecoverAspectHandle

func RecoverAspectHandle(handle Handle, aspect interface{}, HandleName string) Handle

异常处理和切面执行

func RecoverHandle

func RecoverHandle(handle Handle) Handle

异常处理

type HandleContext

type HandleContext struct {
	ResponseWriter *http.ResponseWriter
	Request        *http.Request
	ParamParser
	Data      sync.Map
	CloseHttp bool
}

func NewHandleContext

func NewHandleContext(w *http.ResponseWriter, r *http.Request) *HandleContext

func (*HandleContext) Abort

func (ctx *HandleContext) Abort(code int)

终止当前http请求

func (*HandleContext) Bind

func (ctx *HandleContext) Bind(i interface{}) error

传入结构体指针,把请求参数绑定到结构体内部

func (*HandleContext) JSON_write

func (ctx *HandleContext) JSON_write(code int, e interface{})

--------------------------------------------------------------------------------------------- 传入map、array、slice、struct

func (*HandleContext) Str_write

func (ctx *HandleContext) Str_write(code int, msg string)

向客户端写入一个字符串

type Ioc

type Ioc struct {
	sync.Mutex
	// contains filtered or unexported fields
}

容器

func NewIoc

func NewIoc() *Ioc

容器实例化

func (*Ioc) AddBeen

func (ioc *Ioc) AddBeen(name string, singleton interface{})

注册单例对象

func (*Ioc) GetBeen

func (ioc *Ioc) GetBeen(name string) interface{}

获取单例对象

func (*Ioc) GetPrototype

func (ioc *Ioc) GetPrototype(name string) (interface{}, error)

获取实例对象

func (*Ioc) Inject

func (ioc *Ioc) Inject(instance interface{}) interface{}

注入依赖,此函数不应该recover():此函数运行成功就能保证运用运行起来

func (*Ioc) SetPrototypeFactory

func (ioc *Ioc) SetPrototypeFactory(name string, factory factory)

设置实例对象工厂

func (*Ioc) String

func (ioc *Ioc) String() string

打印容器内部实例

type JSONArray

type JSONArray []interface{}

func (*JSONArray) Add

func (ja *JSONArray) Add(obj interface{})

type JSONObject

type JSONObject map[string]interface{}

func (*JSONObject) Put

func (jo *JSONObject) Put(key string, val interface{})

type MDContext

type MDContext struct {
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	Data           interface{}
}

---------------------------------------------------------------------------------------------

type ModelMap

type ModelMap map[string]interface{}

---------------------------------------------------------------------------------------------

func (*ModelMap) AddAttribute

func (M *ModelMap) AddAttribute(key string, val interface{})

type PKGenarater

type PKGenarater struct {
	DB        *sql.DB `inject:"db"`
	TableName string
	IdLength  int
	PK        string
	Sign      string
}

* idLength:主键生成的长度 table_name:表名,数据库内表的真实名字 pk:表的主键字段 sign: user00000012 中的user

func (*PKGenarater) GetPK

func (p *PKGenarater) GetPK() (string, error)

type Panizza

type Panizza struct {
	Configer

	Filter
	*Ioc
	// contains filtered or unexported fields
}

func New

func New() *Panizza

实例化panizza,首先寻找项目中的配置文件application.conf并加载配置

func (*Panizza) ServeHTTP

func (pz *Panizza) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Panizza) StartServer

func (pz *Panizza) StartServer()

开启panizza服务,如果没有配置PORT则默认监听8080端口

func (*Panizza) Static

func (fs *Panizza) Static()

设置文件服务根路径

type ParamParser

type ParamParser struct {
	ParamMap map[string]string
	ParamKey []string
	ParamVal []string
}

func (*ParamParser) Add

func (pp *ParamParser) Add(key string, value string)

func (*ParamParser) Check

func (pp *ParamParser) Check(registRouter string, url string) bool

检查自定义路由与访问路由是否匹配,如果匹配则返回true, 若不匹配则返回false

func (*ParamParser) GetParams

func (pp *ParamParser) GetParams(registRouter string, url string)

在Check方法通过之后便可以调用此方法获得url参数,参数放在对象的ParamMap之内

func (*ParamParser) Parame

func (pp *ParamParser) Parame(key string) string

func (*ParamParser) ParameBool

func (pp *ParamParser) ParameBool(key string) bool

func (*ParamParser) ParameFloat32

func (pp *ParamParser) ParameFloat32(key string) (float64, error)

func (*ParamParser) ParameFloat64

func (pp *ParamParser) ParameFloat64(key string) (float64, error)

func (*ParamParser) ParameInt

func (pp *ParamParser) ParameInt(key string) (int, error)

func (*ParamParser) ParameInt64

func (pp *ParamParser) ParameInt64(key string) (int64, error)

Directories

Path Synopsis
example
src

Jump to

Keyboard shortcuts

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