hfw

package module
v0.0.0-...-5870b03 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2023 License: GPL-3.0 Imports: 38 Imported by: 4

README

hfw

go small framework

用法:

main.go
func main() {
    _ = hfw.Handler("/", &Index{})
    _ = hfw.Run()
}
type Index struct {
    hfw.Controller
}
func (ctl *Index) Index(httCtx *hfw.HTTPContext) {
    //some coding
}

构建说明:

默认数据库使用mysql,服务发现使用consul,
可以通过tags方式使用其他类型,
目前支持的tags有sqlite3、postgres、mssql、etcd 构建方式如下

go build -tags postgres,etcd

Documentation

Overview

kill -INT pid 终止 kill -TERM pid 重启

Index

Constants

View Source
const (
	NotFound = "NotFound"
)

Variables

View Source
var (
	//废弃,请用configs.Config
	Config configs.AllConfig
)
View Source
var ErrStopRun = errors.New("user stop run")

ErrStopRun ..

Functions

func AddCron

func AddCron(spec string, cmd func()) (cron.EntryID, error)

func AddWrapCron

func AddWrapCron(spec string, cmd func(httpCtx *HTTPContext) error) (cron.EntryID, error)

func DispatchRoute

func DispatchRoute(httpCtx *HTTPContext)

修改httpCtx.Path后重新寻找执行action

func DoWrapCron

func DoWrapCron(spec string, cmd func(httpCtx *HTTPContext) error) (cron.EntryID, error)

func GetGrpcServerListener

func GetGrpcServerListener() net.Listener

func GetHTTPServerAddr

func GetHTTPServerAddr(config configs.HTTPServerConfig) (string, error)

func GetHTTPServerListener

func GetHTTPServerListener() net.Listener

func Handle

func Handle(pattern string, h http.Handler)

Handle register Handle

func Handler

func Handler(pattern string, handler ControllerInterface) (err error)

Handler 暂时只支持2段

func HandlerFunc

func HandlerFunc(pattern string, h http.HandlerFunc)

HandlerFunc register HandlerFunc

func Init

func Init() (err error)

func NewGrpcServer

func NewGrpcServer(config configs.AllConfig) (s *grpc.Server, err error)

func RegisterServeHTTPCook

func RegisterServeHTTPCook(c func(*http.Request) bool, f http.HandlerFunc)

func Router

func Router(w http.ResponseWriter, r *http.Request)

Router 写测试用例会调用

func Run

func Run() (err error)

Run start

func RunGrpc

func RunGrpc(s *grpc.Server, config configs.GrpcServerConfig) (err error)

func StartHTTP

func StartHTTP(config configs.HTTPServerConfig) (err error)

func StaticHandler

func StaticHandler(pattern string, dir string)

StaticHandler ... 如pattern=css,dir=./static,则css在./static下

func StaticStripHandler

func StaticStripHandler(pattern string, dir string)

StaticStripHandler ... 如pattern=css,dir=./static/css,则css就是./static/css

func StopCron

func StopCron()

func StreamServerInterceptor

func StreamServerInterceptor(
	srv interface{}, ss grpc.ServerStream,
	info *grpc.StreamServerInfo, handler grpc.StreamHandler,
) (err error)

func UnaryServerInterceptor

func UnaryServerInterceptor(
	ctx context.Context, req interface{},
	info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
) (resp interface{}, err error)

func WrapCron

func WrapCron(cmd func(httpCtx *HTTPContext) error) func()

Types

type Controller

type Controller struct {
}

Controller ..

func (*Controller) After

func (ctl *Controller) After(httpCtx *HTTPContext)

After ..

func (*Controller) Before

func (ctl *Controller) Before(httpCtx *HTTPContext)

Before ..

func (*Controller) Finish

func (ctl *Controller) Finish(httpCtx *HTTPContext)

Finish 请不要实现Finish方法

func (*Controller) Init

func (ctl *Controller) Init(httpCtx *HTTPContext)

Init 请不要实现Init方法

func (*Controller) NotFound

func (ctl *Controller) NotFound(httpCtx *HTTPContext)

NotFound ..

func (*Controller) ServerError

func (ctl *Controller) ServerError(httpCtx *HTTPContext)

ServerError .. 不要手动调用,用于捕获未知错误,手动请用Throw 该方法不能使用StopRun,也不能panic,因为会被自动调用

type ControllerInterface

type ControllerInterface interface {
	Init(*HTTPContext)
	Before(*HTTPContext)
	After(*HTTPContext)
	Finish(*HTTPContext)
	NotFound(*HTTPContext)
	ServerError(*HTTPContext)
}

ControllerInterface .. init和finish必定会执行,而且不允许被修改 Before和After之间是业务逻辑,所有Before也是必定会执行 用户手动StopRun()后,中止业务逻辑,跳过After,继续Finish

type GrpcServerStream

type GrpcServerStream struct {
	grpc.ServerStream
	// contains filtered or unexported fields
}

func WarpServerStream

func WarpServerStream(ss grpc.ServerStream, httpCtx *HTTPContext) *GrpcServerStream

func (*GrpcServerStream) Context

func (w *GrpcServerStream) Context() context.Context

type HTTPContext

type HTTPContext struct {
	Ctx context.Context `json:"-"`

	HTTPStatus int `json:"-"`

	ResponseWriter http.ResponseWriter `json:"-"`
	Request        *http.Request       `json:"-"`
	Session        *session.Session    `json:"-"`
	Layout         string              `json:"-"`
	//对应的struct名称,大小写一致
	Controller string `json:"-"`
	//对应的struct方法的名称,大小写一致
	Action string `json:"-"`
	Path   string `json:"-"`

	IsZip bool `json:"-"`
	//404和500页面被自动更改content-type,导致压缩后有问题,暂时不压缩
	IsError bool `json:"-"`

	//html文本
	Template string `json:"-"`
	//模板文件
	TemplateFile string `json:"-"`
	//主要用于模板渲染
	Data    map[string]interface{} `json:"-"`
	FuncMap map[string]interface{} `json:"-"`

	IsJSON bool `json:"-"`
	//返回的json是否包含Header
	HasHeader bool `json:"-"`
	//是否只返回Response.Results里的数据
	IsOnlyResults   bool `json:"-"`
	common.Response `json:"response"`
	Header          interface{} `json:"header"`

	//如果是下载文件,不执行After和Finish
	IsCloseRender bool `json:"-"`

	*logger.Logger
	// contains filtered or unexported fields
}

HTTPContext .. 渲染模板的数据放Data Json里的数据放Response Layout的功能未实现 TODO

func NewHTTPContext

func NewHTTPContext() *HTTPContext

func NewHTTPContextWithCtx

func NewHTTPContextWithCtx(ctx *HTTPContext) *HTTPContext

func NewHTTPContextWithGrpcIncomingCtx

func NewHTTPContextWithGrpcIncomingCtx(ctx context.Context) *HTTPContext

func NewHTTPContextWithGrpcOutgoingCtx

func NewHTTPContextWithGrpcOutgoingCtx(ctx context.Context) *HTTPContext

func (*HTTPContext) Cancel

func (httpCtx *HTTPContext) Cancel()

func (*HTTPContext) CheckErr

func (httpCtx *HTTPContext) CheckErr(errNo int64, i interface{}) (int64, string)

CheckErr

func (*HTTPContext) Deadline

func (httpCtx *HTTPContext) Deadline() (deadline time.Time, ok bool)

因为历史原因,不能去掉Ctx,故手动实现context.Context

func (*HTTPContext) Done

func (httpCtx *HTTPContext) Done() <-chan struct{}

func (*HTTPContext) Err

func (httpCtx *HTTPContext) Err() error

func (*HTTPContext) GetCookie

func (httpCtx *HTTPContext) GetCookie(key string) (s string)

func (*HTTPContext) GetForm

func (httpCtx *HTTPContext) GetForm(key string) string

GetForm 优先post和put,然后get

func (*HTTPContext) GetFormInt

func (httpCtx *HTTPContext) GetFormInt(key string) int

GetFormInt 优先post和put,然后get,转为int

func (*HTTPContext) Hijack

func (httpCtx *HTTPContext) Hijack() (conn net.Conn, bufrw *bufio.ReadWriter, err error)

func (*HTTPContext) Redirect

func (httpCtx *HTTPContext) Redirect(url string)

Redirect ..

func (*HTTPContext) Render

func (httpCtx *HTTPContext) Render()

Render ..

func (*HTTPContext) RenderResponse

func (httpCtx *HTTPContext) RenderResponse()

RenderResponse ..

func (*HTTPContext) ReturnFileContent

func (httpCtx *HTTPContext) ReturnFileContent(contentType, filename string, file interface{})

ReturnFileContent 下载文件服务

func (*HTTPContext) ReturnJSON

func (httpCtx *HTTPContext) ReturnJSON()

ReturnJSON ..

func (*HTTPContext) SetCookie

func (httpCtx *HTTPContext) SetCookie(key, value string)

func (*HTTPContext) SetDownloadMode

func (httpCtx *HTTPContext) SetDownloadMode(filename string)

SetDownloadMode ..

func (*HTTPContext) StopRun

func (httpCtx *HTTPContext) StopRun()

StopRun ..

func (*HTTPContext) ThrowCheck

func (httpCtx *HTTPContext) ThrowCheck(errNo int64, i interface{})

ThrowCheck

func (*HTTPContext) Value

func (httpCtx *HTTPContext) Value(key interface{}) interface{}

Directories

Path Synopsis
db
默认是mysql +build mysql mariadb
默认是mysql +build mysql mariadb
grpc
client
支持连接https+grpc共享端口的版本,也支持非证书版 Usage: conn, err := client.NewClientConn("localhost:63333", "server.crt", "server.grpc.io", grpc.WithPerRPCCredentials(&rpc.X{Value: "abc", Key: "x"})) client := rpc.NewHelloServiceClient(conn)
支持连接https+grpc共享端口的版本,也支持非证书版 Usage: conn, err := client.NewClientConn("localhost:63333", "server.crt", "server.grpc.io", grpc.WithPerRPCCredentials(&rpc.X{Value: "abc", Key: "x"})) client := rpc.NewHelloServiceClient(conn)
discovery/register
// register service cr := register.NewConsulRegister(fmt.Sprintf("%s:%d", host, consul_port), 15)
// register service cr := register.NewConsulRegister(fmt.Sprintf("%s:%d", host, consul_port), 15)
server
支持https+grpc的共享端口版,不需要ca证书 获取http+grpc,两个服务必须独立端口 Usage: 如果是grpc+https s, err := server.NewServer(hfw.Config.Server, opt...) RegisterHelloServiceServer(s, &HelloServiceImpl{auth: auth.NewAuthWithHTTPS("value")}) 如果是http+grpc s, err := server.NewServer(hfw.Config.Server, opt...) RegisterHelloServiceServer(s, &HelloServiceImpl{auth: auth.NewAuth("value")}) go server.StartServer(s, ":1234")
支持https+grpc的共享端口版,不需要ca证书 获取http+grpc,两个服务必须独立端口 Usage: 如果是grpc+https s, err := server.NewServer(hfw.Config.Server, opt...) RegisterHelloServiceServer(s, &HelloServiceImpl{auth: auth.NewAuthWithHTTPS("value")}) 如果是http+grpc s, err := server.NewServer(hfw.Config.Server, opt...) RegisterHelloServiceServer(s, &HelloServiceImpl{auth: auth.NewAuth("value")}) go server.StartServer(s, ":1234")
service
信号处理 kill -INT pid 终止 kill -TERM pid 重启 需要调用Wg.Add() 需要监听Shutdown通道
信号处理 kill -INT pid 终止 kill -TERM pid 重启 需要调用Wg.Add() 需要监听Shutdown通道

Jump to

Keyboard shortcuts

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