bingo_mvc

package module
v0.0.0-...-84fae08 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2020 License: MIT Imports: 21 Imported by: 6

README

bingo_mvc

简单高效的mvc框架,支持go自带的http库,和性能卓越的fasthttp库实现。

特性

  • 双http引擎
  • 支持GET、POST多种方式访问
  • 支持json参数
  • 支持xml参数
  • 支持序列化成json、xml格式
  • 支持返回modeview格式,自动调用模板进行渲染
  • 支持静态文件处理
  • 提供Inject tag进行自动装载
  • 提供Value tag进行属性从配置文件中自动赋值
  • 提供sqltemplate实现,不用写sql也能增删改查
  • 提供本地和分布式session实现方式
  • 提供多request mapper的方式
  • 提供自动将请求参数赋值给方法参数
  • 提供Field tag,来指明对应的输入参数名
  • 提供拦截器扩展,可以在服务执行前后进行响应处理
  • 提供了Boot方式启动,通过加载配置文件,将引擎配制好。
  • Boot中提供简单的IOC容器,自动装载对象和赋值

样例

简单的例子

func main(){
  f:=fasthttp.FastHTTPDispatcher{}
  f.Port=8080
  f.Run()

}
来个有点意思的
import (
	"fmt"
	"github.com/aosfather/bingo_mvc"
	"log"
)
//方法需要的输入参数
type MyRequest struct {
	Name string `Field:"name"`  //指定参数输入名称是name
}
//主要的服务提供者,提供了两个url,一个/test,一个/test1
type MyHandle struct {
	Test  string `mapper:"name(test);url(/test);method(GET);style(HTML)"`
	Test1 string `mapper:"name(test1);url(/test1);method(GET);style(JSON)"`
}
// 这个框架会调用的方法,通过这个方法返回了对应url响应的方法及对应的参数对象
func (this *MyHandle) GetHandles() bingo_mvc.HandleMap {
	result := bingo_mvc.NewHandleMap()
	r:=&MyRequest{}
	result.Add("test",this.DoTest,r)
	result.Add("test1",this.DoTest1,r)
	return result
}

func (this *MyHandle) DoTest(a interface{}) interface{} {
	t:=a.(*MyRequest)//框架会按指定的参数类型,进行赋值回调
	log.Println(t.Name)
	return "hello"
}

func (this *MyHandle) DoTest1(a interface{}) interface{} {
	t:=a.(*MyRequest)
	log.Println(t.Name)
	return fmt.Sprintf("hello %s",t.Name)
}
func main() {
	h := HttpDispatcher{}
	h.Port = 8090
    //向dispatch注册url mapping信息,简单明了
	h.AddRequestMapperBystruct(&MyHandle{})
	h.Run()
}

使用 curl localhost:8090/test?name=xxxx,试验一下吧。两个例子用的dispatcher类不一样, 只是为了演示了下双引擎,两者的方法是一样的,外部行为没有什么不一样。

基于boot来启动应用
import "github.com/aosfather/bingo_mvc/context"
//MyRequest 和MyHandle和上面一样,只是来了点小魔法,自动装载数据库链接
type MyHandle struct {
	Test  string `mapper:"name(test);url(/test);method(GET);style(HTML)"`
	Test1 string `mapper:"name(test1);url(/test1);method(GET);style(JSON)"`
    DB *sqltemplate.Datasource `Inject` //系统将自动装载
}
//演示了使用数据库,至于需不需要强制分 controller、service等的方式
//仁者见仁,智者见智了。根据系统复杂程度来定吧。
func (this *MyHandle) DoTest(a interface{}) interface{} {
	t:=a.(*MyRequest)//框架会按指定的参数类型,进行赋值回调
	log.Println(t.Name)
    dao:=this.DB.GetDao()
    dao.FindBySql(t,"select name from mytest1 where id=123")
    log.Println(t.Name) //看看是不是不一样了
	return "hello"
}
func main(){
    boot:=context.Boot{}
    boot.Init(&HttpDispatcher{},onLoad)
    boot.Start()
}

func onLoad()[]interface{}{
    return []interface{}{&MyHandle{}}
}

boot会自动加载bingo.yaml文件,该文件放在应用的根目录下

# bingo.yaml
bingo:
  port: 8080   #监听的端口
  static: statics #静态资源的目录,可以没有
  template: templates #模板目录
  template_fix: tp #模板文件后缀
  useddB:true   # 启用数据库,可以不启用
  db:
     type: mysql      #数据库类型
     name: test       # 数据库名
     url: localhost:3306 #服务器地址及端口
     user: dev          #数据库用户名
     password: dev      #数据库用户对应的密码
  

使用boot后就拥有了一个ioc容器,使用Inject tag,会自动装载,可以指明对象的名称。 使用Value tag会将配置中对应的属性值赋值。

Documentation

Index

Constants

View Source
const (
	//http方法
	Method_GET    = "GET"
	Method_POST   = "POST"
	Method_PUT    = "PUT"
	Method_DELETE = "DELETE"
	Method_PATCH  = "PATCH"
	Method_HEAD   = "HEAD"

	//返回码
	Code_OK             = 200
	Code_CREATED        = 201
	Code_EMPTY          = 204
	Code_NOT_MODIFIED   = 304
	Code_BAD            = 400
	Code_UNAUTHORIZED   = 401
	Code_FORBIDDEN      = 403
	Code_NOT_FOUND      = 404
	Code_CONFLICT       = 409
	Code_ERROR          = 500
	Code_NOT_IMPLEMENTS = 501
	Code_NOT_ALLOWED    = 405

	CONTENT_TYPE = "Content-Type"
)
View Source
const (
	Default_Port = 8080
)

Variables

This section is empty.

Functions

func RegisterValidate

func RegisterValidate(af AutoValidateFunction)

func TypeOfEmpty

func TypeOfEmpty() interface{}

func TypeOfMap

func TypeOfMap() interface{}

Types

type AbstractDispatcher

type AbstractDispatcher struct {
	Port int
	// contains filtered or unexported fields
}

func (*AbstractDispatcher) AddController

func (this *AbstractDispatcher) AddController(domain string, name string, url string, control Controller)

func (*AbstractDispatcher) AddInterceptor

func (this *AbstractDispatcher) AddInterceptor(ins ...Interceptor)

func (*AbstractDispatcher) AddRequestMapper

func (this *AbstractDispatcher) AddRequestMapper(r *RequestMapper)

func (*AbstractDispatcher) AddRequestMapperByHandleFunction

func (this *AbstractDispatcher) AddRequestMapperByHandleFunction(name string, url []string, input interface{}, handle HandleFunction, methods []HttpMethodType)

func (*AbstractDispatcher) AddRequestMapperBystruct

func (this *AbstractDispatcher) AddRequestMapperBystruct(target interface{})

*

通过mapper 的struct tag标签加入映射

func (*AbstractDispatcher) ConfigPort

func (this *AbstractDispatcher) ConfigPort(p int)

func (*AbstractDispatcher) ConfigStatic

func (this *AbstractDispatcher) ConfigStatic(root string)

func (*AbstractDispatcher) ConfigTemplate

func (this *AbstractDispatcher) ConfigTemplate(root string, suffix string)

func (*AbstractDispatcher) ExecuteRequest

func (this *AbstractDispatcher) ExecuteRequest(r Controller, writer io.Writer, context HttpContext, input func(interface{}) error) StyleType

执行请求

func (*AbstractDispatcher) HandlePainc

func (this *AbstractDispatcher) HandlePainc(after func(v interface{}))

func (*AbstractDispatcher) MatchUrl

func (this *AbstractDispatcher) MatchUrl(u string) (Controller, Params)

func (*AbstractDispatcher) ProcessStaticUrl

func (this *AbstractDispatcher) ProcessStaticUrl(url string, writer io.Writer) (string, error)

func (*AbstractDispatcher) SetDispatchManager

func (this *AbstractDispatcher) SetDispatchManager(d *DispatchManager)

func (*AbstractDispatcher) SetSessionManager

func (this *AbstractDispatcher) SetSessionManager(s *SessionManager)

type AutoValidateFunction

type AutoValidateFunction func(v interface{}) []error

type BingoError

type BingoError interface {
	error
	Code() int
}

带错误码的错误接口

type CMap

type CMap struct {
	Handle    HandleFunction
	Parameter interface{}
}

controller的mapp

type Context

type Context interface {
	GetCookie(key string) string
}

type Controller

type Controller interface {
	Select(writer io.Writer, input func(interface{}) error) StyleType
	IsSupportMethod(m HttpMethodType) bool
}

控制器

type Convertor

type Convertor func(writer io.Writer, obj interface{}) error

结果集转换器

type CookieFace

type CookieFace interface {
	CookieRead(key string) map[CookieKey]interface{}
	CookieWrite(key string, value map[CookieKey]interface{}) error
}

cookie接口

type CookieKey

type CookieKey byte

cookie 的属性

const (
	CK_Name     CookieKey = 1
	CK_Value    CookieKey = 2
	CK_Path     CookieKey = 3
	CK_MaxAge   CookieKey = 4
	CK_HttpOnly CookieKey = 5
)

type DispatchManager

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

*

请求分发管理

func (*DispatchManager) AddApi

func (this *DispatchManager) AddApi(domain string, name, url string, handle Handle)

* 增加单个api的映射

func (*DispatchManager) AddRequestMapper

func (this *DispatchManager) AddRequestMapper(domain string, r *RequestMapper)

*

新增一个requestmapper的映射。

一个requestmapper会对应多个url

func (*DispatchManager) GetApi

func (this *DispatchManager) GetApi(domain, url string) (Handle, Params)

根据域名和url获取对应的API

func (*DispatchManager) GetController

func (this *DispatchManager) GetController(domain, url string) (Controller, Params)

func (*DispatchManager) GetRequestMapper

func (this *DispatchManager) GetRequestMapper(domain, url string) *RequestMapper

func (*DispatchManager) Init

func (this *DispatchManager) Init()

type Error

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

func CreateError

func CreateError(c int, text string) Error

func CreateErrorF

func CreateErrorF(c int, f string, textobj ...interface{}) Error

func (Error) Code

func (this Error) Code() int

func (Error) Error

func (this Error) Error() string

type FileContainer

type FileContainer interface {
	AddFileForm(f *FileForm)
}

文件容器,用于实现自定义的参数

type FileForm

type FileForm struct {
	FileName string
	FileSize int64
	IsError  bool
	Error    string
	File     FileHandler
}

文件表单

type FileHandler

type FileHandler interface {
	io.Reader
	io.Closer
}

type Handle

type Handle interface{}

url path :id.etc:/xx/:id.例如 /xx/:name/:id/info,其中name和id为参数

type HandleFunction

type HandleFunction func(interface{}) interface{}

Request响应函数

type HandleMap

type HandleMap map[string]CMap

func NewHandleMap

func NewHandleMap() HandleMap

handle的map,用户获取handle列表

func (HandleMap) Add

func (this HandleMap) Add(name string, handle HandleFunction, p interface{})

type HttpContext

type HttpContext interface {
	HttpHeaderFace
	CookieFace
}

type HttpHeaderFace

type HttpHeaderFace interface {
	RequestHeaderRead(key string) string
	GetRequestURI() string
	ResponseHeaderwrite(key string, v string) error
}

协议头接口

type HttpMethodType

type HttpMethodType byte
const (
	Get  HttpMethodType = 20
	Post HttpMethodType = 21
	Put  HttpMethodType = 22
	Del  HttpMethodType = 23
	Head HttpMethodType = 24
)

func ParseHttpMethodType

func ParseHttpMethodType(method string) HttpMethodType

func (HttpMethodType) MarshalYAML

func (this HttpMethodType) MarshalYAML() (interface{}, error)

func (*HttpMethodType) UnmarshalYAML

func (this *HttpMethodType) UnmarshalYAML(unmarshal func(interface{}) error) error

type HttpSession

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

会话

func (*HttpSession) GetValue

func (this *HttpSession) GetValue(key string) interface{}

func (*HttpSession) ID

func (this *HttpSession) ID() string

func (*HttpSession) IsNew

func (this *HttpSession) IsNew() bool

func (*HttpSession) SetValue

func (this *HttpSession) SetValue(key string, value interface{})

func (*HttpSession) Touch

func (this *HttpSession) Touch()

type Interceptor

type Interceptor interface {
	PreHandle(writer io.Writer, context HttpContext) bool
	InputProcess(context HttpContext, input interface{}) error
	PostHandle(writer io.Writer, context HttpContext, mv *ModelView) BingoError
	AfterCompletion(writer io.Writer, context HttpContext, err BingoError) BingoError
}

type ModelView

type ModelView struct {
	View  string
	Model interface{}
}

type MutiController

type MutiController interface {
	GetHandles() HandleMap
}

多个handle的控制器

type Param

type Param struct {
	Key   string
	Value string
}

type Params

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func (Params) ByName

func (ps Params) ByName(name string) string

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

type RequestMapper

type RequestMapper struct {
	Name    string   //名称
	Url     []string //url路径
	Methods []HttpMethodType
	//请求参数类型
	Request interface{}
	//返回值处理器
	Response      Convertor
	Handle        HandleFunction
	ResponseStyle StyleType
}

url元信息描述

func (*RequestMapper) IsSupportMethod

func (this *RequestMapper) IsSupportMethod(m HttpMethodType) bool

func (*RequestMapper) Select

func (this *RequestMapper) Select(writer io.Writer, input func(interface{}) error) StyleType

type SessionManager

type SessionManager struct {
	CookieName string //客户端cookie名称
	// contains filtered or unexported fields
}

func (*SessionManager) Create

func (this *SessionManager) Create(face CookieFace) *HttpSession

func (*SessionManager) DeleteSession

func (this *SessionManager) DeleteSession(id string)

func (*SessionManager) GetSession

func (this *SessionManager) GetSession(face CookieFace) *HttpSession

func (*SessionManager) GetSessionById

func (this *SessionManager) GetSessionById(id string) *HttpSession

func (*SessionManager) Init

func (this *SessionManager) Init()

func (*SessionManager) SetStore

func (this *SessionManager) SetStore(store SessionStore)

type SessionStore

type SessionStore interface {
	Exist(id string) bool
	Create(id string)
	GetValue(id, key string) interface{}
	SetValue(id, key string, value interface{})
	Touch(id string)
	Delete(id string)
}

type StaticView

type StaticView struct {
	Name   string      //资源名称
	Media  string      //资源类型
	Length int         //资源长度
	Reader FileHandler //资源内容
}

type StyleType

type StyleType byte

数据格式类型

const (
	Json    StyleType = 11
	Xml     StyleType = 12
	UrlForm StyleType = 13
	Stream  StyleType = 20
)

func ParseHttpStyleType

func ParseHttpStyleType(styleName string) StyleType

func (StyleType) GetContentType

func (this StyleType) GetContentType() string

func (StyleType) MarshalYAML

func (this StyleType) MarshalYAML() (interface{}, error)

func (*StyleType) UnmarshalYAML

func (this *StyleType) UnmarshalYAML(unmarshal func(interface{}) error) error

type TemplateEngine

type TemplateEngine struct {
	RootPath        string //模板根路径
	SubTemplatePath string //子模板及片段定义的目录
	Suffix          string //模板文件后缀
	CacheSize       int    //缓存模板个数
	ErrorTemplate   string //错误模板
	// contains filtered or unexported fields
}

func (*TemplateEngine) Init

func (this *TemplateEngine) Init()

func (*TemplateEngine) Render

func (this *TemplateEngine) Render(w io.Writer, templateName string, data interface{}) BingoError

func (*TemplateEngine) WriteError

func (this *TemplateEngine) WriteError(w io.Writer, err BingoError)

Directories

Path Synopsis
* SQL生成模板 用于根据struct的定义生成update语句和insert语句 规则 1、表名 默认t_stuct的名称(小写,驼峰转 xx_xx) 可以通过setTablePreFix来指定默认的表前缀 可以通过tag Table:""指定表名 2、字段名称 默认字段名称(小写,驼峰转 xx_xx) 可以通过 tag Field:""指定字段名 3、特例 通过tag Option:"" 来指定。
* SQL生成模板 用于根据struct的定义生成update语句和insert语句 规则 1、表名 默认t_stuct的名称(小写,驼峰转 xx_xx) 可以通过setTablePreFix来指定默认的表前缀 可以通过tag Table:""指定表名 2、字段名称 默认字段名称(小写,驼峰转 xx_xx) 可以通过 tag Field:""指定字段名 3、特例 通过tag Option:"" 来指定。

Jump to

Keyboard shortcuts

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