freefishgo

package module
v0.0.0-...-77cf2aa Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2023 License: Apache-2.0 Imports: 16 Imported by: 4

README

freeFishGo(1分钟学会golang写后端接口)

freeFishGo是通过结构体反射实现的典型的mvc的web框架

FreeFishGo is a typical MVC web framework implemented through struct reflection

使用案例

package main

import (
	"fmt"
	"github.com/freefishgo/freefishgo"
	"github.com/freefishgo/freefishgo/middlewares/mvc"
	"log"
	"time"
)
// 实现mvc控制器的处理ctrTest为控制器 {Controller}的值
type MainController struct {
	mvc.Controller
}

// 作为 Action的请求参数的映射值
type Test struct {
	T  []string `json:"tt"`
	T1 string   `json:"tstst1"`
	Id string   `json:"id"`
}
// 路由地址为 /main/MyControllerActionStrut 请求方式为post
func (c *MainController) MyControllerActionStrutPost(t *Test) {
	c.Data["Website"] = t.Id
	c.Data["Email"] = t.T1
	// 调用模板引擎   默认模板地址为{ Controller}/{Action}.fish    不含请求方式
	c.UseTplPath()
}
// 路由地址为 /main/MyControllerActionStrut 请求方式为get
func (c *MainController) MyControllerActionStrutGet(t *Test) {
	c.Data["Website"] = t.Id
	c.Data["Email"] = t.T1
	//c.HttpContext.Response.Write([]byte("hahaha"))
	c.UseTplPath()
}
// 路由地址为 /main/My 请求方式为get
func (c *MainController) MyGET(t *Test) {
	c.Response.Write([]byte(fmt.Sprintf("数据为:%+v", t)))
}
// 路由地址为 /main/My1 请求方式为get
func (c *MainController) My1(t *Test) {
	c.Response.Write([]byte(fmt.Sprintf("数据为:%+v", t)))
}
func main() {
	// 注册控制器
	mvc.AddHandlers(&MainController{})
	// 把mvc实例注册到管道中
	freefishgo.UseMiddleware(mvc.GetDefaultMvcApp())
	freefishgo.Run()
}

如果你想快速构建项目 请查看 https://github.com/freefishgo/freefish

使用freefishgo的优势(详细文档地址访问 http://freefishgo.com)

1.通过的中间件注入对http请求进行流处理 清楚明白处理流程
2.自定义中间件只需要实现IMiddleware接口 该接口只有两个方法,方便快捷,实现任意地点对请求的处理
3.提供Mvc服务也是通过中间件注入的 该中间件能通过动作器的参数进行参数注入,免去忘记请求参数的烦恼,再也不用再写反序列化获取参数了,框架帮你完成
4.url中任意位置的字符串也能注入到请求参数的
5.你还在为每一个动作器都需要写路由地址而烦恼吗? freefishgo解除你的烦恼,你可以不进行路由设置,实现所有控制器动作器路由注入

  1. Flow processing of HTTP requests through middleware injection to clearly understand the processing process
  2. Custom middleware only needs to implement IMiddleware interface. This interface has only two methods, which are convenient and fast, and can handle requests at any place
  3. The Mvc service is also injected through the middleware. This middleware can inject parameters through the parameters of the actor, so as to avoid the trouble of forgetting the request parameters, and no longer need to write deserialization to get parameters
  4. Strings at any location in the url can also be injected into the request parameters
  5. Are you still worried that every actuator needs to write a routing address? Freefishgo takes care of your worries, you can implement all controller actions without routing Settings

Installation

To install freefishgo use the go get command:

go get github.com/freefishgo/freefishgo

If you already have freefishgo installed, updating freefishgo is simple:

go get -u github.com/freefishgo/freefishgo

Documentation

Index

Constants

View Source
const (
	VERSION = "1.00"
)

Variables

This section is empty.

Functions

func InjectionSession

func InjectionSession(session ISession)

InjectionSession 向默认管道注入session去数据的接口

func Run

func Run()

Run 启动默认中间件web服务

func SetDefaultApplicationBuilderConfig

func SetDefaultApplicationBuilderConfig(config *Config)

func UseMiddleware

func UseMiddleware(middleware ...IMiddleware)

UseMiddleware 向默认中间件注册接口

func UseMiddlewareFunc

func UseMiddlewareFunc(middlewareFunc ...func(ctx *HttpContext, next Next) *HttpContext)

UseMiddlewareFunc 中间件func注册接口

Types

type ApplicationBuilder

type ApplicationBuilder struct {
	Config *Config
	// contains filtered or unexported fields
}

ApplicationBuilder ApplicationBuilder管道构造器

func GetDefaultApplicationBuilder

func GetDefaultApplicationBuilder() *ApplicationBuilder

func NewFreeFishApplicationBuilder

func NewFreeFishApplicationBuilder() *ApplicationBuilder

NewFreeFishApplicationBuilder 创建一个ApplicationBuilder管道

func (*ApplicationBuilder) InjectionSession

func (app *ApplicationBuilder) InjectionSession(session ISession)

InjectionSession 向管道注入session去数据的接口

func (*ApplicationBuilder) Run

func (app *ApplicationBuilder) Run()

Run 启动web服务

func (*ApplicationBuilder) UseMiddleware

func (app *ApplicationBuilder) UseMiddleware(middleware ...IMiddleware)

UseMiddleware 中间件注册接口

func (*ApplicationBuilder) UseMiddlewareFunc

func (app *ApplicationBuilder) UseMiddlewareFunc(middlewareFunc ...func(ctx *HttpContext, next Next) *HttpContext)

UseMiddlewareFunc 中间件func注册接口

type Config

type Config struct {
	AppName    string
	RunMode    string
	ServerName string
	// EnableGzip 是否开启Gzip压缩
	EnableGzip bool
	// EnableSession 是否启用Session
	EnableSession bool
	// SessionAliveTime Session的存在时间
	SessionAliveTime time.Duration
	// MaxResponseCacheLen 响应数据最大缓存长度
	MaxResponseCacheLen int
	// SessionCookieName Session的客户端Cookie名字
	SessionCookieName string
	// RecoverPanic 是否在管道最末端捕获Panic,以取代框架的处理Panic函数
	RecoverPanic bool
	// RecoverFunc 捕获Panic的处理函数
	RecoverFunc func(ctx *HttpContext)
	Listen      Listen
}

func NewConfig

func NewConfig() *Config

type HttpContext

type HttpContext struct {
	Response IResponse
	Request  *Request
}

type HttpMethod

type HttpMethod string
const (
	MethodGet     HttpMethod = "GET"
	MethodHead    HttpMethod = "HEAD"
	MethodPost    HttpMethod = "POST"
	MethodPut     HttpMethod = "PUT"
	MethodPatch   HttpMethod = "PATCH" // RFC 5789
	MethodDelete  HttpMethod = "DELETE"
	MethodConnect HttpMethod = "CONNECT"
	MethodOptions HttpMethod = "OPTIONS"
	MethodTrace   HttpMethod = "TRACE"
)

type IMiddleware

type IMiddleware interface {
	// Middleware 中间件的逻辑处理函数 框架会调用
	Middleware(ctx *HttpContext, next Next) *HttpContext
	// LastInit 注册框架后 框架会自动调用这个函数
	LastInit(*Config)
}

IMiddleware 中间件类型接口

type IResponse

type IResponse interface {
	// WebSocket 升级为WebSocket服务 upgrades为空时采用默认的参数 为多个时只采用第一个作为WebSocket参数
	WebSocket(upgrades ...*websocket.Upgrader) (conn *websocket.Conn, err error)
	Hijack() (net.Conn, *bufio.ReadWriter, error)

	// RemoveSession 移除Session
	RemoveSession()
	// GetSession 获取指定key的session值
	GetSession(key string) (interface{}, error)

	// UpdateSession 更新session值
	UpdateSession() error
	// SetSession 设置session值
	SetSession(key string, val interface{}) error
	// SetCookie 设置Cookie
	SetCookie(c *http.Cookie)
	// SetCookieUseKeyValue 设置Cookie
	SetCookieUseKeyValue(key string, val string)
	// RemoveCookieByName 通过cookie名字移除Cookie
	RemoveCookieByName(name string)
	// WriteHeader 设置响应状态值
	WriteHeader(statusCode int)
	// ReadStatusCode 读取响应状态值
	ReadStatusCode() int
	// RemoveCookie 通过cookie移除Cookie
	RemoveCookie(ck *http.Cookie)
	// Write 写入前端的数据
	Write(b []byte) (int, error)
	// GetWriteCache 获取写入前端的缓存
	GetWriteCache() []byte
	// ClearWriteCache 清除写入前端的缓存
	ClearWriteCache()
	// WriteJson 写入前端的json数据
	WriteJson(i interface{}) error
	// Redirect 重定向路径
	Redirect(redirectPath string)

	// GetStarted 是否已经向前端写入数据了,默认是开启的,且GetMaxResponseCacheLen()设置很小
	GetStarted() bool
	// GetIsWriteInCache 获取当前请求是否临时缓存数据进入缓存中
	GetIsWriteInCache() bool
	// SetIsWriteInCache 设置是否延迟把写入前端的数据写入前端,即使设置了延迟写入前端,
	// 但当数据长度超过了配置文件设置的 MaxResponseCacheLen是依然会写入前端,
	// 判断是否已经写入前端 调用 GetStarted()进行判断
	SetIsWriteInCache(bool)
	Header() http.Header
	// GetMaxResponseCacheLen 查看延迟写入前端的数据的最大值
	GetMaxResponseCacheLen() int
	// SetMaxResponseCacheLen 设置延迟写入前端的数据的最大值,GetIsWriteInCache()为True时生效
	SetMaxResponseCacheLen(int)
	// GetMsgData 获取传送数据
	GetMsgData() map[string]interface{}
	// SetMsgData 设置传送数据
	SetMsgData(map[string]interface{})
	// Stack 500 错误的堆栈信息,其他状态为空
	Stack() string
	// Error 500 错误的信息,其他状态为空
	Error() interface{}
	SetStack(string)
	SetError(interface{})
	// contains filtered or unexported methods
}

type ISession

type ISession interface {
	// Init 初始化接口
	Init(SessionAliveTime time.Duration) error
	// GetSession 获取指定sessionID的值
	GetSession(sessionID string) (map[interface{}]interface{}, error)
	// GetSessionKeyValue 创建一个sessionID
	GetSessionKeyValue() (string, error)
	// SetSession 设置sessionID的值
	SetSession(sessionID string, m map[interface{}]interface{}) error
	// RemoveBySessionID 移除sessionID及其值
	RemoveBySessionID(sessionID string) error
}

ISession Session接口

type Listen

type Listen struct {
	// ServerTimeOut 服务超时时间
	ServerTimeOut time.Duration
	// WriteTimeout 写超时时间
	WriteTimeout time.Duration

	MaxHeaderBytes int
	// EnableHTTP 是否开启http服务
	EnableHTTP bool
	// HTTPAddr http服务运行ip地址
	HTTPAddr string
	// HTTPPort http服务运行端口
	HTTPPort int
	// EnableHTTPS 是否开启Https服务
	EnableHTTPS bool
	// HTTPSAddr https服务运行ip地址
	HTTPSAddr string
	// HTTPSPort https服务运行端口
	HTTPSPort int
	// HTTPSCertFile httpsCertFile文件地址
	HTTPSCertFile string
	// HTTPSKeyFile HTTPSKeyFile文件地址
	HTTPSKeyFile string
}

type Next

type Next func(*HttpContext) *HttpContext

Next 下一个中间件

type Request

type Request struct {
	*http.Request
}

type Response

type Response struct {
	http.ResponseWriter

	// 是否调用过Write
	Started bool

	Gzip       *gzip.Writer
	IsOpenGzip bool

	SessionId         string
	SessionCookieName string
	SessionAliveTime  time.Duration
	// contains filtered or unexported fields
}

func (*Response) ClearWriteCache

func (r *Response) ClearWriteCache()

ClearWriteCache 清除写入前端的缓存

func (*Response) Error

func (r *Response) Error() interface{}

Error 错误的信息

func (*Response) GetIsWriteInCache

func (r *Response) GetIsWriteInCache() bool

func (*Response) GetMaxResponseCacheLen

func (r *Response) GetMaxResponseCacheLen() int

func (*Response) GetMsgData

func (r *Response) GetMsgData() map[string]interface{}

GetMsgData 获取传递的信息

func (*Response) GetSession

func (r *Response) GetSession(key string) (interface{}, error)

func (*Response) GetStarted

func (r *Response) GetStarted() bool

func (*Response) GetWriteCache

func (r *Response) GetWriteCache() []byte

GetWriteCache 获取写入前端的缓存

func (*Response) Hijack

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

func (*Response) ReadStatusCode

func (r *Response) ReadStatusCode() int

func (*Response) Redirect

func (r *Response) Redirect(redirectPath string)

func (*Response) RemoveCookie

func (r *Response) RemoveCookie(ck *http.Cookie)

RemoveCookie 通过cookie移除Cookie

func (*Response) RemoveCookieByName

func (r *Response) RemoveCookieByName(name string)

RemoveCookieByName 通过cookie名字移除Cookie

func (*Response) RemoveSession

func (r *Response) RemoveSession()

func (*Response) SetCookie

func (r *Response) SetCookie(c *http.Cookie)

SetCookie 设置Cookie

func (*Response) SetCookieUseKeyValue

func (r *Response) SetCookieUseKeyValue(key string, val string)

SetCookieUseKeyValue 设置Cookie

func (*Response) SetError

func (r *Response) SetError(err interface{})

SetError 设置错误的信息

func (*Response) SetIsWriteInCache

func (r *Response) SetIsWriteInCache(b bool)

func (*Response) SetMaxResponseCacheLen

func (r *Response) SetMaxResponseCacheLen(b int)

func (*Response) SetMsgData

func (r *Response) SetMsgData(data map[string]interface{})

SetMsgData 设置传递的信心

func (*Response) SetSession

func (r *Response) SetSession(key string, val interface{}) error

func (*Response) SetStack

func (r *Response) SetStack(str string)

SetStack 设置错误的堆栈信息

func (*Response) Stack

func (r *Response) Stack() string

Stack 错误的堆栈信息

func (*Response) UpdateSession

func (r *Response) UpdateSession() error

func (*Response) WebSocket

func (r *Response) WebSocket(upgrades ...*websocket.Upgrader) (conn *websocket.Conn, err error)

WebSocket 升级为WebSocket服务 upgrades为空时采用默认的参数 为多个时只采用第一个作为WebSocket参数

func (*Response) Write

func (r *Response) Write(b []byte) (int, error)

Write 写入前端的数据

func (*Response) WriteHeader

func (r *Response) WriteHeader(statusCode int)

func (*Response) WriteJson

func (r *Response) WriteJson(i interface{}) error

WriteJson 写入前端的json数据

type Session

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

Session 会话

type SessionMgr

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

SessionMgr Session会话管理

func NewSessionMgr

func NewSessionMgr(maxLifeTime time.Duration) *SessionMgr

NewSessionMgr 创建会话管理器(cookieName:在浏览器中cookie的名字;maxLifeTime:最长生命周期)

func (*SessionMgr) GC

func (mgr *SessionMgr) GC()

GC GC回收

func (*SessionMgr) GetLastAccessTime

func (mgr *SessionMgr) GetLastAccessTime(sessionID string) time.Time

GetLastAccessTime 更新最后访问时间

func (*SessionMgr) GetSession

func (mgr *SessionMgr) GetSession(sessionID string) (map[interface{}]interface{}, error)

GetSession 得到session里面的值

func (*SessionMgr) GetSessionIDList

func (mgr *SessionMgr) GetSessionIDList() []string

GetSessionIDList 得到sessionID列表

func (*SessionMgr) GetSessionKeyValue

func (mgr *SessionMgr) GetSessionKeyValue() (string, error)

func (*SessionMgr) Init

func (mgr *SessionMgr) Init(SessionAliveTime time.Duration) error

func (*SessionMgr) NewSessionID

func (mgr *SessionMgr) NewSessionID() string

NewSessionID 创建唯一ID

func (*SessionMgr) RemoveBySessionID

func (mgr *SessionMgr) RemoveBySessionID(sessionID string) error

func (*SessionMgr) SetSession

func (mgr *SessionMgr) SetSession(sessionID string, m map[interface{}]interface{}) error

SetSession 设置session里面的值

Directories

Path Synopsis
middlewares
mvc

Jump to

Keyboard shortcuts

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