water

package module
v0.9.9 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2024 License: MIT Imports: 29 Imported by: 6

README

简介:go-water 是一款设计层面的 web 框架(类似 gin,iris,beego,echo),更好的业务隔离,更好的系统设计,通过一系列接口、规范、约定、中间件,深度解耦业务系统。

星星增长趋势

Stargazers over time

安装

go get -u github.com/go-water/water

技术概览

  • 支持原生路由(1.22)
  • slog 日志
  • 中间件
  • 多模板支持
  • rsa 加密,openssl 生成公/私钥对
  • jwt 登陆认证
  • pool 管理请求参数
  • option 配置修改
  • rate limit(限流)
  • circuit breaker(熔断)

这个样例,复制代码,就可以直接跑

package main

import (
	"context"
	"fmt"
	"github.com/go-water/water"
	"github.com/sony/gobreaker"
	"net/http"
	"time"
)

func main() {
	InitService()
	router := water.New()
	router.GET("/", H.Index)
	_ = router.Run(":80")
}

// 控制层,这里定义了一个 Handlers 来管理所有业务接口

var (
	H *Handlers
)

type Handlers struct {
	index water.Handler
}

func NewService() *Handlers {
	var options []water.ServerOption
	// 一分钟内,连续10次后,将限流
	options = append(options, water.ServerErrorLimiter(time.Minute, 10))
	// 熔断定义,服务层异常将触发,见服务层代码以及注释
	options = append(options, water.ServerBreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{})))
	return &Handlers{
		index: water.NewHandler(
			&IndexService{ServerBase: &water.ServerBase{}}, options...,
		)}
}

func InitService() {
	H = NewService()
}

func (h *Handlers) Index(ctx *water.Context) {
	request, err := water.BindJSON[IndexRequest](ctx)
	if err != nil {
		_ = ctx.JSON(http.StatusBadRequest, water.H{"err": err.Error()})
		return
	}

	request.Name = "Jimmy"
	resp, err := h.index.ServerWater(ctx, request)
	if err != nil {
		_ = ctx.JSON(http.StatusBadRequest, water.H{"err": err.Error()})
		return
	}

	_ = ctx.JSON(http.StatusOK, resp)
}

// 业务服务层,业务接口服务结构体包含一个water.ServerBase,同时必须实现 Handle 方法

type IndexService struct {
	*water.ServerBase
}

type IndexRequest struct {
	Name string
}

type IndexResponse struct {
	Message string
}

func (s *IndexService) Handle(ctx context.Context, req *IndexRequest) (interface{}, error) {
	resp := new(IndexResponse)
	resp.Message = fmt.Sprintf("Hello, %s!", req.Name)
	return resp, nil
	// 如果要测试服务熔断,可以打开下面代码,让代码返回异常,测试连续6次错误,第7次将不再进入这个方法
	// return nil, errors.New("service failure")
}

在浏览器输入

http://localhost/

运行结果

{
    "Message": "Hello, Jimmy!"
}
一分钟内连续10次后,限流
{
  "err": "rate limit exceeded"
}
熔断前,连续错误6次
{
  "err": "service failure"
}
熔断后
{
  "err": "circuit breaker is open"
}

样例仓库

使用的网站列表

参考仓库

Documentation

Index

Constants

View Source
const (
	ContextKey = "_go-water/context-key"
)
View Source
const Version = "v0.9.7"

Variables

View Source
var MaxMultipartMemory int64 = 32 << 20 // 32 MB

Functions

func BindJSON added in v0.5.0

func BindJSON[T any](c *Context) (t *T, err error)

func Dir added in v0.6.0

func Dir(root string, listDirectory bool) http.FileSystem

Dir returns a http.FileSystem that can be used by http.FileServer(). It is used internally in router.Static(). if listDirectory == true, then it works the same as http.Dir() otherwise it returns a filesystem that prevents http.FileServer() to list the directory files.

func Error added in v0.2.8

func Error(msg string, args ...any)

func Info added in v0.2.8

func Info(msg string, args ...any)

func ParseFromRequest added in v0.2.6

func ParseFromRequest(req *http.Request, publicKeyPath string) (uniqueUser, issuer, signature string, err error)

ParseFromRequest 兼容 http,ws

func SetAuthToken added in v0.2.0

func SetAuthToken(uniqueUser, issuer, privateKeyPath string, expire time.Duration) (tokenString string, err error)

func Warn added in v0.2.8

func Warn(msg string, args ...any)

Types

type Context added in v0.5.0

type Context struct {
	Request *http.Request
	Writer  http.ResponseWriter

	Keys map[string]any
	// contains filtered or unexported fields
}

func (*Context) BindHeader added in v0.9.1

func (c *Context) BindHeader(obj any) error

func (*Context) BindJSON added in v0.9.1

func (c *Context) BindJSON(obj any) error

func (*Context) BindQuery added in v0.9.1

func (c *Context) BindQuery(obj any) error

func (*Context) ClientIP added in v0.8.0

func (c *Context) ClientIP() string

func (*Context) ContentType added in v0.8.4

func (c *Context) ContentType() string

func (*Context) Cookie added in v0.6.0

func (c *Context) Cookie(name string) (string, error)

func (*Context) Deadline added in v0.5.0

func (c *Context) Deadline() (deadline time.Time, ok bool)

func (*Context) DefaultPostForm added in v0.8.6

func (c *Context) DefaultPostForm(key, defaultValue string) string

func (*Context) DefaultQuery added in v0.8.6

func (c *Context) DefaultQuery(key, defaultValue string) string

func (*Context) Done added in v0.5.0

func (c *Context) Done() <-chan struct{}

func (*Context) Err added in v0.5.0

func (c *Context) Err() error

func (*Context) File added in v0.6.0

func (c *Context) File(filepath string)

func (*Context) FormFile added in v0.6.0

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

func (*Context) Get added in v0.5.0

func (c *Context) Get(key string) (value any, exists bool)

func (*Context) GetBool added in v0.8.8

func (c *Context) GetBool(key string) (b bool)

func (*Context) GetDuration added in v0.8.8

func (c *Context) GetDuration(key string) (d time.Duration)

func (*Context) GetFloat64 added in v0.8.8

func (c *Context) GetFloat64(key string) (f64 float64)

func (*Context) GetHeader added in v0.6.0

func (c *Context) GetHeader(key string) string

func (*Context) GetInt added in v0.8.8

func (c *Context) GetInt(key string) (i int)

func (*Context) GetInt64 added in v0.8.8

func (c *Context) GetInt64(key string) (i64 int64)

func (*Context) GetPostForm added in v0.8.6

func (c *Context) GetPostForm(key string) (string, bool)

func (*Context) GetPostFormArray added in v0.8.6

func (c *Context) GetPostFormArray(key string) (values []string, ok bool)

func (*Context) GetQuery added in v0.8.6

func (c *Context) GetQuery(key string) (string, bool)

func (*Context) GetQueryArray added in v0.8.6

func (c *Context) GetQueryArray(key string) (values []string, ok bool)

func (*Context) GetString added in v0.6.0

func (c *Context) GetString(key string) (s string)

func (*Context) GetStringMap added in v0.8.8

func (c *Context) GetStringMap(key string) (sm map[string]any)

func (*Context) GetStringMapString added in v0.8.8

func (c *Context) GetStringMapString(key string) (sms map[string]string)

func (*Context) GetStringMapStringSlice added in v0.8.8

func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)

func (*Context) GetStringSlice added in v0.8.8

func (c *Context) GetStringSlice(key string) (ss []string)

func (*Context) GetTime added in v0.8.8

func (c *Context) GetTime(key string) (t time.Time)

func (*Context) GetUint added in v0.8.8

func (c *Context) GetUint(key string) (ui uint)

func (*Context) GetUint64 added in v0.8.8

func (c *Context) GetUint64(key string) (ui64 uint64)

func (*Context) HTML added in v0.6.0

func (c *Context) HTML(code int, name string, obj any)

func (*Context) Header added in v0.6.0

func (c *Context) Header(key, value string)

func (*Context) JSON added in v0.5.0

func (c *Context) JSON(status int, data any) error

func (*Context) MustBindWith added in v0.9.1

func (c *Context) MustBindWith(obj any, b binding.Binding) error

func (*Context) Param added in v0.5.0

func (c *Context) Param(key string) string

func (*Context) PostForm added in v0.8.6

func (c *Context) PostForm(key string) (value string)

func (*Context) PostFormArray added in v0.8.6

func (c *Context) PostFormArray(key string) (values []string)

func (*Context) Query added in v0.8.6

func (c *Context) Query(key string) (value string)

func (*Context) QueryArray added in v0.8.6

func (c *Context) QueryArray(key string) (values []string)

func (*Context) Redirect added in v0.6.0

func (c *Context) Redirect(code int, location string)

func (*Context) RemoteIP added in v0.7.0

func (c *Context) RemoteIP() string

func (*Context) Render added in v0.6.0

func (c *Context) Render(code int, r render.Render)

func (*Context) SaveUploadedFile added in v0.6.0

func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error

func (*Context) Set added in v0.5.0

func (c *Context) Set(key string, value any)

func (*Context) SetCookie added in v0.6.0

func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

func (*Context) SetSameSite added in v0.7.0

func (c *Context) SetSameSite(sameSite http.SameSite)

func (*Context) ShouldBind added in v0.8.2

func (c *Context) ShouldBind(obj any) error

func (*Context) ShouldBindJSON added in v0.5.0

func (c *Context) ShouldBindJSON(obj any) error

func (*Context) ShouldBindQuery added in v0.9.1

func (c *Context) ShouldBindQuery(obj any) error

func (*Context) ShouldBindWith added in v0.5.0

func (c *Context) ShouldBindWith(obj any, b binding.Binding) error

func (*Context) Status added in v0.6.0

func (c *Context) Status(code int)

func (*Context) Text added in v0.9.2

func (c *Context) Text(code int, format string, values ...any)

func (*Context) Value added in v0.5.0

func (c *Context) Value(key any) any

type Err added in v0.9.8

type Err string

func (Err) Error added in v0.9.8

func (e Err) Error() string

type H added in v0.5.0

type H map[string]any

type Handler

type Handler interface {
	ServerWater(ctx context.Context, req any) (any, error)
	GetLogger() *slog.Logger
}

func NewHandler

func NewHandler(srv Service, options ...ServerOption) Handler

type HandlerFunc added in v0.5.0

type HandlerFunc func(*Context)

type HttpHandler added in v0.6.0

type HttpHandler func(http.Handler) http.Handler

type Middleware added in v0.6.0

type Middleware func(HandlerFunc) HandlerFunc

type Router added in v0.5.0

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

func (*Router) Delete added in v0.8.0

func (r *Router) Delete(route string, handler HandlerFunc)

func (*Router) GET added in v0.6.0

func (r *Router) GET(route string, handler HandlerFunc)

func (*Router) Group added in v0.5.0

func (r *Router) Group(prefix string) *Router

func (*Router) HEAD added in v0.6.0

func (r *Router) HEAD(route string, handler HandlerFunc)

func (*Router) Method added in v0.5.0

func (r *Router) Method(method, route string, handler HandlerFunc)

func (*Router) OPTIONS added in v0.8.0

func (r *Router) OPTIONS(route string, handlers HandlerFunc)

func (*Router) POST added in v0.6.0

func (r *Router) POST(route string, handler HandlerFunc)

func (*Router) Patch added in v0.8.0

func (r *Router) Patch(route string, handler HandlerFunc)

func (*Router) Put added in v0.8.0

func (r *Router) Put(route string, handler HandlerFunc)

func (*Router) Static added in v0.6.0

func (r *Router) Static(relativePath, root string) *Router

func (*Router) StaticFS added in v0.6.0

func (r *Router) StaticFS(relativePath string, fs http.FileSystem) *Router

func (*Router) StaticFile added in v0.6.0

func (r *Router) StaticFile(relativePath, filepath string) *Router

func (*Router) Use added in v0.5.0

func (r *Router) Use(middlewares ...Middleware)

type RouterHandler added in v0.8.0

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

func (*RouterHandler) ServeHTTP added in v0.8.0

func (r *RouterHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)

type ServerBase added in v0.0.12

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

func (*ServerBase) GetLogger added in v0.0.18

func (s *ServerBase) GetLogger() *slog.Logger

func (*ServerBase) Name added in v0.0.12

func (s *ServerBase) Name(srv Service) string

func (*ServerBase) SetLogger added in v0.0.19

func (s *ServerBase) SetLogger(l *slog.Logger)

type ServerFinalizerFunc

type ServerFinalizerFunc func(ctx context.Context, err error)

type ServerOption

type ServerOption func(h *handler)

func ServerBreaker added in v0.3.3

func ServerBreaker(breaker *gobreaker.CircuitBreaker) ServerOption

func ServerDelayLimiter added in v0.9.4

func ServerDelayLimiter(interval time.Duration, b int) ServerOption

func ServerErrorLimiter added in v0.9.5

func ServerErrorLimiter(interval time.Duration, b int) ServerOption

func ServerFinalizer added in v0.0.5

func ServerFinalizer(f ...ServerFinalizerFunc) ServerOption

type Service

type Service interface {
	Name(srv Service) string
	SetLogger(l *slog.Logger)
}

type Water added in v0.8.0

type Water struct {
	Router
	ContextWithFallback bool
	HTMLRender          render.HTMLRender

	TrustedPlatform string
	RemoteIPHeaders []string

	MaxMultipartMemory int64
	// contains filtered or unexported fields
}

func New added in v0.7.0

func New() *Water

func (*Water) Run added in v0.9.2

func (w *Water) Run(addr string, server ...*http.Server) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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