web

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2024 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnknown           = NewError("UnKnow", "未知错误")
	ErrBadRequest        = NewError("ErrBadRequest", "请求参数有误")
	ErrDB                = NewError("ErrStore", "数据发生错误")
	ErrServer            = NewError("ErrServer", "服务器发生错误")
	ErrUnauthorizedToken = NewError("ErrUnauthorizedToken", "用户已过期或错误")
	ErrJSON              = NewError("ErrUnmarshal", "JSON 编解码出错")
	ErrNotFound          = NewError("ErrNotFound", "资源未找到")
	ErrUsedLogic         = NewError("ErrUsedLogic", "使用逻辑错误")
	ErrLoginLimiter      = NewError("ErrLoginLimiter", "触发登录限制")
	ErrPermissionDenied  = NewError("ErrPermissionDenied", "没有该资源的权限")
	ErrTimeout           = NewError("ErrTimeout", "请求超时")
	ErrDevice            = NewError("ErrDevice", "设备异常")
	ErrDeviceOffline     = NewError("ErrDeviceOffline", "设备离线")

	ErrAddNewDevice = NewError("ErrAddNewDevice", "请重新添加此设备") // 待删除
)

常用错误

View Source
var (
	ErrNameOrPasswd    = NewError("ErrNameOrPasswd", "用户名或密码错误")
	ErrCaptchaWrong    = NewError("ErrCaptchaWrong", "验证码错误")
	ErrAccountDisabled = NewError("ErrAccountDisabled", "登录限制")
)

业务错误

Functions

func AbortWithStatusJSON

func AbortWithStatusJSON(c ResponseWriter, err error, fn ...WithData)

func AddHead

func AddHead() gin.HandlerFunc

func AuthLevel

func AuthLevel(level int) gin.HandlerFunc

func AuthMiddleware

func AuthMiddleware(secret string) gin.HandlerFunc

AuthMiddleware 鉴权

func Fail

func Fail(c ResponseWriter, err error, fn ...WithData)

Fail 通用错误返回

func GetBaseURL added in v1.0.2

func GetBaseURL(req *http.Request) string

GetBaseURL 提取请求地址 例如 http://127.0.0.1:8080/health 提取出 http://127.0.0.1:8080

func GetGroupLevel

func GetGroupLevel(c *gin.Context) int8

func GetRole

func GetRole(c *gin.Context) string

GetRole 获取用户角色

func GetUID

func GetUID(c *gin.Context) int

GetUID 获取用户 ID

func GetUsername

func GetUsername(c *gin.Context) string

GetUsername 获取用户名

func HanddleJSONErr

func HanddleJSONErr(err error) error

func HandlerResponseMsg

func HandlerResponseMsg(resp http.Response) error

HandlerResponseMsg 获取响应的结果

func IPRateLimiter

func IPRateLimiter(r rate.Limit, b int) func(ip string) bool

IPRateLimiter IP 限流器

func IPRateLimiterForGin

func IPRateLimiterForGin(r rate.Limit, b int) gin.HandlerFunc

IPRateLimiter IP 限流器

func Limit

func Limit(v, min, max int) int

func Logger

func Logger(log *slog.Logger, recordBodyFn func(*gin.Context) bool) gin.HandlerFunc

Logger 第二个参数是否记录 请求与响应的 body。

func Mertics

func Mertics() gin.HandlerFunc

Mertics ...

func Message

func Message(err error) string

Message 获取错误消息

func MustTraceID

func MustTraceID(ctx context.Context) string

func NewToken

func NewToken(input TokenInput) (string, error)

NewToken 创建 token

func Offset

func Offset(page, size int) int

func RateLimiter

func RateLimiter(r rate.Limit, b int) gin.HandlerFunc

RateLimiter 限流器

func RecordResponse

func RecordResponse() gin.HandlerFunc

func Recover

func Recover() gin.HandlerFunc

Recover from panics and converts the panic to an error so it is reported in Metrics and handled in Errors.

func SendChunk

func SendChunk(ch <-chan Chunk, c *gin.Context)

SendChunk 发送分块数据

func SendChunkPro

func SendChunkPro(ch <-chan Chunk, c *gin.Context)

SendChunkPro 高性能版

func SendSSE

func SendSSE(ch <-chan EventMessage, c *gin.Context)

func SetRelease

func SetRelease()

func SetTraceID

func SetTraceID(ctx *gin.Context, id string)

func SetupMutexProfile

func SetupMutexProfile(rate int)

func SetupPProf

func SetupPProf(r *gin.Engine, ips *[]string)

func Success

func Success(c HTTPContext, bean any)

Success 通用成功返回

func TraceID

func TraceID(ctx context.Context) (string, bool)

func WarpH

func WarpH[I any, O any](fn func(*gin.Context, *I) (O, error)) gin.HandlerFunc

WarpH 让函数更专注于业务,一般入参和出参应该是指针类型 没有入参时,应该使用 struct{}

Types

type Chunk

type Chunk struct {
	Total   int    `json:"total"`
	Current int    `json:"current"`
	Success int    `json:"success"`
	Failure int    `json:"failure"`
	Err     string `json:"err,omitempty"`
}

type Claims

type Claims struct {
	UID        int
	Username   string
	GroupID    int
	GroupLevel int8
	Role       string
	Level      int
	jwt.RegisteredClaims
}

Claims ...

func ParseToken

func ParseToken(tokenString string, secret string) (*Claims, error)

ParseToken 解析 token

type E

type E struct {
	Reason  string   `json:"reason"`
	Msg     string   `json:"msg"`
	Details []string `json:"details"`
}

E 可反序列化的 err

func Unmarshal

func Unmarshal(b []byte) (e E)

Unmarshal ...

func (E) String

func (e E) String() string

type Error

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

Error ...

func NewError

func NewError(reason, msg string) *Error

NewError 创建自定义错误

func (*Error) Details

func (e *Error) Details() []string

Details 错误

func (Error) Error

func (e Error) Error() string

func (*Error) HTTPCode

func (e *Error) HTTPCode() int

HTTPCode http status code 权限相关错误 401 程序错误 500 其它错误 400

func (*Error) Map

func (e *Error) Map() map[string]any

Map ..

func (*Error) Message

func (e *Error) Message() string

Message ..

func (*Error) Msg

func (e *Error) Msg(s string) *Error

Msg 提示内容

func (*Error) Reason

func (e *Error) Reason() string

Reason ..

func (*Error) With

func (e *Error) With(args ...string) *Error

With 错误详情

func (*Error) Withf

func (e *Error) Withf(format string, args ...any) *Error

Withf 错误详情格式化

type Errorer

type Errorer interface {
	Reason() string
	HTTPCode() int
	Message() string
	Details() []string
}

Errorer ...

type Event added in v1.0.2

type Event struct {
	ID    string
	Event string
	Data  []byte
}

type EventMessage

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

func NewEventMessage

func NewEventMessage(event string, data map[string]any) *EventMessage

type HTTPContext

type HTTPContext interface {
	JSON(int, any)
	Header(key, value string)
	context.Context
}

type PageOutput

type PageOutput struct {
	Total int64 `json:"total"`
	Items any   `json:"items"`
}

PageOutput 分页数据

type PagerFilter

type PagerFilter struct {
	Page         int      `form:"page"`
	Size         int      `form:"size"`
	Sort         string   `form:"sort"`
	SortSafelist []string `json:"-"`
}

PagerFilter 分页过滤

func (PagerFilter) Limit

func (f PagerFilter) Limit() int

Limit 每页 10~100 区间

func (PagerFilter) MustSortColumn

func (f PagerFilter) MustSortColumn() string

MustSortColumn 忽略安全问题

func (PagerFilter) Offset

func (f PagerFilter) Offset() int

Offset 计算偏离数值

func (PagerFilter) SortColumn

func (f PagerFilter) SortColumn() (string, error)

SortColumn 通过对 SortColumn 设置值,仅对允许的值做排序处理

func (PagerFilter) SortDirection

func (f PagerFilter) SortDirection() string

SortDirection 如果 sort 携带负号返回倒序,否则返回正序

type ResponseMsg

type ResponseMsg struct {
	Msg string `json:"msg"`
}

type ResponseWriter

type ResponseWriter interface {
	JSON(code int, obj interface{})
	File(filepath string)
	Set(string, any)
	context.Context
	AbortWithStatusJSON(code int, obj interface{})
}

ResponseWriter ...

type ResponseWriterWrapper

type ResponseWriterWrapper struct {
	gin.ResponseWriter
	Body *bytes.Buffer // 缓存
}

func (ResponseWriterWrapper) Write

func (w ResponseWriterWrapper) Write(b []byte) (int, error)

func (ResponseWriterWrapper) WriteString

func (w ResponseWriterWrapper) WriteString(s string) (int, error)

type SSE added in v1.0.2

type SSE struct {
	Headers map[string]string
	// contains filtered or unexported fields
}

SSE 发送事件

使用案例

http.HandleFunc("/stream", func(w http.ResponseWriter, r *http.Request) {
	sse := web.NewSSE(1024, time.Minute)

	go func(){
		for range 3 {
			sse.Publish(web.Event{
				ID:    uuid.New().String(),
				Event: "ping",
				Data: []byte("pong"),
			})
			time.Sleep(time.Second)
		}
		sse.Close()
	}()
	sse.ServeHTTP(w, r)
})

func NewSSE added in v1.0.2

func NewSSE(length int, timeout time.Duration) *SSE

func (*SSE) Close added in v1.0.2

func (s *SSE) Close()

func (*SSE) Publish added in v1.0.2

func (s *SSE) Publish(v Event)

func (*SSE) ServeHTTP added in v1.0.2

func (s *SSE) ServeHTTP(w http.ResponseWriter, _ *http.Request)

type ScrollPager

type ScrollPager[T any] struct {
	Items []T    `json:"items"`
	Next  string `json:"next"`
}

ScrollPager 滚动翻页

type TokenInput

type TokenInput struct {
	UID        int
	GroupID    int
	GroupLevel int8
	Username   string
	Secret     string
	Role       string
	Level      int
	Exires     time.Duration
}

type Validator

type Validator struct {
	Errors map[string]string
}

Validator 验证对象是否合法

func NewValidator

func NewValidator() *Validator

NewValidator ...

func (*Validator) AddError

func (v *Validator) AddError(key, message string) *Validator

AddError 添加错误

func (*Validator) Check

func (v *Validator) Check(ok bool, key, message string) *Validator

Check 如果 ok==false,则将 message 写入 errors

func (*Validator) List

func (v *Validator) List() []string

List 验证 !Valid() 后,可获取错误列表

func (*Validator) Result

func (v *Validator) Result() (bool, []string)

Result true 表示没有错误

func (*Validator) Valid

func (v *Validator) Valid() bool

Valid 如果没有错误,返回 true

type WithData

type WithData func(map[string]any)

Jump to

Keyboard shortcuts

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