water

package module
v0.8.6 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2024 License: MIT Imports: 28 Imported by: 6

README

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

星星增长趋势

Stargazers over time

安装

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

技术概览

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

用例

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/go-water/water"
	"github.com/go-water/water/multitemplate"
)

func main() {
	router := water.New()
	router.HTMLRender = createMyRender()

	router.Use(Logger)
	router.GET("/", Index)
	v2 := router.Group("/v2")
	{
		v2.GET("/hello", GetHello)
	}

	router.Serve(":80")
}

func Index(ctx *water.Context) {
	ctx.HTML(http.StatusOK, "index", water.H{"title": "我是标题", "body": "你好,朋友。"})
}

func GetHello(ctx *water.Context) {
	ctx.JSON(http.StatusOK, water.H{"msg": "Hello World!"})
}

func Logger(handlerFunc water.HandlerFunc) water.HandlerFunc {
	return func(ctx *water.Context) {
		start := time.Now()
		defer func() {
			msg := fmt.Sprintf("[WATER] %v | %15s | %13v | %-7s %s",
				time.Now().Format("2006/01/02 - 15:04:05"),
				ctx.ClientIP(),
				time.Since(start),
				ctx.Request.Method,
				ctx.Request.URL.Path,
			)

			fmt.Println(msg)
		}()

		handlerFunc(ctx)
	}
}

func createMyRender() multitemplate.Renderer {
	r := multitemplate.NewRenderer()
	r.AddFromFiles("index", "views/layout.html", "views/index.html", "views/_header.html", "views/_footer.html")
	return r
}

views/layout.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>{{.title}}</title>
</head>
<body>
<div>
    <div>
        {{template "_header"}}
    </div>
    <div>
        {{template "content" .}}
    </div>
    <div>
        {{template "_footer"}}
    </div>
</div>
</body>
</html>

views/index.html

{{define "content"}}
我是内容:{{.body}}
{{end}}

views/_header.html

{{define "_header"}}
我是 Header。
{{end}}

views/_footer.html

{{define "_footer"}}
我是 Footer。
{{end}}

样例仓库

官方文档

参考仓库

Documentation

Index

Constants

View Source
const ContextKey = "_go-water/context-key"
View Source
const Version = "v0.8.6"

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 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)

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) 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)

Deadline returns that there is no deadline (ok==false) when c.Request has no Context.

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{}

Done returns nil (chan which will wait forever) when c.Request has no Context.

func (*Context) Err added in v0.5.0

func (c *Context) Err() error

Err returns nil when c.Request has no Context.

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) GetHeader added in v0.6.0

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

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) 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) 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) 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) Value added in v0.5.0

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

Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result.

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 ServerFinalizer added in v0.0.5

func ServerFinalizer(f ...ServerFinalizerFunc) ServerOption

func ServerLimiter added in v0.3.0

func ServerLimiter(interval time.Duration, b int) 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) Serve added in v0.8.0

func (w *Water) Serve(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