sinking_web

package module
v0.0.0-...-42d9676 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 23 Imported by: 8

README

Sinking-Web

🚀 轻量级高性能 Go Web 框架

Sinking-Web 是一个基于 Go 语言开发的轻量级、高性能 Web 框架,提供简洁易用的 API 和丰富的功能特性。框架设计简洁,性能优异,适合构建各种规模的 Web 应用和 API 服务。

✨ 主要特性

  • 🚀 高性能路由: 基于前缀树的高效路由匹配算法
  • 🛠️ 中间件支持: 灵活的中间件机制,支持请求拦截和处理
  • 📝 参数绑定: 支持 JSON、Form、Query、路径参数的自动绑定
  • 🔧 错误处理: 统一的错误处理机制和自定义错误处理器
  • 📁 静态文件: 内置静态文件服务支持
  • 🌐 代理支持: 支持 HTTP 和 WebSocket 代理
  • 📊 限流控制: 内置请求限流功能
  • 🔍 日志中间件: 详细的请求日志记录
  • 🛡️ 异常恢复: 自动捕获和处理 panic 异常
  • 🎯 路由分组: 支持路由分组和嵌套路由

🛠️ 技术规格

  • Go 版本: 1.11+
  • 依赖: 无第三方依赖,仅使用 Go 标准库
  • 架构: 轻量级,核心代码不到 2000 行
  • 性能: 高性能路由匹配,支持高并发请求

🚀 快速开始

安装
go get github.com/SinKingCloud/sinking-go/sinking-web
基本用法
package main

import "github.com/SinKingCloud/sinking-go/sinking-web"

func main() {
    // 创建引擎(包含日志和恢复中间件)
    r := sinking_web.Default()
    
    // 简单路由
    r.GET("/", func(c *sinking_web.Context) {
        c.String(200, "Hello, Sinking-Web!")
    })
    
    // JSON 响应
    r.GET("/json", func(c *sinking_web.Context) {
        c.JSON(200, sinking_web.H{
            "message": "Hello JSON",
            "status":  "success",
        })
    })
    
    // 启动服务器
    r.Run(":8080")
}
路由参数
// 路径参数
r.GET("/user/:id", func(c *sinking_web.Context) {
    id := c.Param("id")
    c.String(200, "User ID: %s", id)
})

// 通配符路由
r.GET("/assets/*filepath", func(c *sinking_web.Context) {
    filepath := c.Param("filepath")
    c.String(200, "File path: %s", filepath)
})
参数绑定
type User struct {
    Name  string `json:"name" form:"name"`
    Email string `json:"email" form:"email"`
}

r.POST("/user", func(c *sinking_web.Context) {
    var user User
    if err := c.BindJSON(&user); err != nil {
        c.JSON(400, sinking_web.H{"error": err.Error()})
        return
    }
    c.JSON(200, user)
})

📋 支持的 HTTP 方法

  • GET - 获取资源
  • POST - 创建资源
  • PUT - 更新资源
  • DELETE - 删除资源
  • PATCH - 部分更新
  • HEAD - 获取头信息
  • OPTIONS - 获取选项
  • ANY - 匹配所有方法

📖 文档

详细的使用文档和 API 说明请参考 doc.md

🤝 贡献

欢迎提交 Issue 和 Pull Request 来改进项目!

📄 许可证

本项目采用 MIT 许可证,详见 LICENSE 文件。

📞 联系方式


⭐ 如果这个项目对您有帮助,请给我们一个 Star!

Documentation

Index

Constants

View Source
const (
	FrameWorkVersion           = "1.0.0"                 //框架版本
	MessageNotFound            = "404 Not Found"         //默认资源不存在消息
	MessageInternalServerError = "Internal Server Error" //默认错误消息
)
View Source
const (
	ContentTypeJson = "application/json;charset=utf-8;" //返回json的头
	ContentTypeText = "text/plain;charset=utf-8;"       //返回字符的头
	ContentTypeHtml = "text/html;charset=utf-8;"        //返回html的头
	HeaderLocation  = "Location"                        //重定向跳转
)
View Source
const (
	BindFormTagName         = "json"    //表单绑定参数tag名称
	BindDefaultValueTagName = "default" //表单绑定默认值tag名称
)
View Source
const (
	ContentType = "Content-Type" //主体类型
)

Variables

This section is empty.

Functions

func Author

func Author(engine *Engine, addr string)

Author 输出框架信息

func Try

func Try(fun func(), handler func(interface{}))

Try 错误捕获实现

Types

type Context

type Context struct {
	Writer     http.ResponseWriter
	Request    *http.Request
	Path       string
	Method     string
	Params     map[string]string
	StatusCode int

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

Context 上下文结构体

func (*Context) Abort

func (c *Context) Abort()

Abort 阻止挂起函数

func (*Context) AllForm

func (c *Context) AllForm() map[string]string

AllForm 获取所有post参数

func (*Context) AllParam

func (c *Context) AllParam() map[string]string

AllParam 获取所有路径参数

func (*Context) AllQuery

func (c *Context) AllQuery() map[string]string

AllQuery 获取所有get参数

func (*Context) BindAll

func (c *Context) BindAll(obj interface{}) error

BindAll 绑定所有参数

func (*Context) BindForm

func (c *Context) BindForm(obj interface{}) error

BindForm 绑定post参数

func (*Context) BindJson

func (c *Context) BindJson(obj interface{}) error

BindJson 绑定json

func (*Context) BindParam

func (c *Context) BindParam(obj interface{}) error

BindParam 绑定路径参数

func (*Context) BindQuery

func (c *Context) BindQuery(obj interface{}) error

BindQuery 绑定get参数

func (*Context) Body

func (c *Context) Body() string

Body 获取请求体

func (*Context) ClientIP

func (c *Context) ClientIP(useProxy bool) string

ClientIP 获取用户ip(是否使用代理)

func (*Context) Data

func (c *Context) Data(code int, data []byte)

Data 返回字符内容

func (*Context) DefaultForm

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

DefaultForm 获取单个post参数,不存在则返回默认参数

func (*Context) DefaultParam

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

DefaultParam 获取路径参数,不存在返回默认参数

func (*Context) DefaultQuery

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

DefaultQuery 获取单个get参数,不存在则返回默认值

func (*Context) Fail

func (c *Context) Fail(code int, err string)

Fail 输出失败响应

func (*Context) Form

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

Form 获取单个post参数

func (*Context) FormFile

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

FormFile 获取上传文件

func (*Context) Get

func (c *Context) Get(key string) (value interface{}, exists bool)

Get 中间件获取传递内容

func (*Context) GetBool

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

func (*Context) GetDuration

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

func (*Context) GetFloat64

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

func (*Context) GetInt

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

func (*Context) GetInt64

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

func (*Context) GetString

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

func (*Context) GetStringMap

func (c *Context) GetStringMap(key string) (sm map[string]interface{})

func (*Context) GetStringMapString

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

func (*Context) GetStringMapStringSlice

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

func (*Context) GetStringSlice

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

func (*Context) GetTime

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

func (*Context) GetUint

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

func (*Context) GetUint64

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

func (*Context) HTML

func (c *Context) HTML(code int, name string, data interface{})

HTML 返回html内容

func (*Context) HttpProxy

func (c *Context) HttpProxy(uri string, logger *log.Logger, filter func(r *http.Request, w http.ResponseWriter, proxy *httputil.ReverseProxy), errorHandle func(http.ResponseWriter, *http.Request, error)) (err error)

HttpProxy http反向代理

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted 是否被挂起

func (*Context) JSON

func (c *Context) JSON(code int, obj interface{})

JSON 返回json内容

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm 多文件上传

func (*Context) Next

func (c *Context) Next()

Next 中间件执行

func (*Context) Param

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

Param 获取单个路径参数

func (*Context) Proxy

func (c *Context) Proxy(uri string, logger *log.Logger, filter func(r *http.Request, w http.ResponseWriter, proxy *httputil.ReverseProxy), errorHandle func(http.ResponseWriter, *http.Request, error)) error

Proxy 通用反向代理

func (*Context) Query

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

Query 获取单个get参数

func (*Context) Redirect

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

Redirect 重定向跳转

func (*Context) SaveUploadedFile

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

SaveUploadedFile 保存上传文件

func (*Context) Set

func (c *Context) Set(key string, value interface{})

Set 中间件设置传递内容

func (*Context) SetHeader

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

SetHeader 设置响应头

func (*Context) SetStatus

func (c *Context) SetStatus(code int)

SetStatus 设置http响应码

func (*Context) String

func (c *Context) String(code int, format string, values ...interface{})

String 返回字符串内容

func (*Context) WebSocketProxy

func (c *Context) WebSocketProxy(uri string, logger *log.Logger, filter func(r *http.Request, w http.ResponseWriter), errorHandle func(http.ResponseWriter, *http.Request, error)) (err error)

WebSocketProxy WebSocketProxy反向代理

type Engine

type Engine struct {
	*RouterGroup

	MaxMultipartMemory int64
	// contains filtered or unexported fields
}

func Default

func Default() *Engine

func New

func New() *Engine

func (*Engine) LoadHtmlGlob

func (engine *Engine) LoadHtmlGlob(pattern string) *Engine

func (*Engine) Run

func (engine *Engine) Run(addr string) (err error)

func (*Engine) RunTLS

func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error)

func (*Engine) ServeHTTP

func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Engine) SetDebugMode

func (engine *Engine) SetDebugMode(mode bool) *Engine

SetDebugMode 设置运行模式为debug

func (*Engine) SetFuncMap

func (engine *Engine) SetFuncMap(funcMap template.FuncMap) *Engine

func (*Engine) SetTimeOut

func (engine *Engine) SetTimeOut(read time.Duration, write time.Duration) *Engine

SetTimeOut 设置超时时间

type ErrorHandel

type ErrorHandel struct {
	NotFound func(*Context)
	Fail     func(c *Context, code int, message string)
}

type H

type H map[string]interface{}

type HandlerFunc

type HandlerFunc func(*Context)

func Logger

func Logger() HandlerFunc

Logger debug log

func Recovery

func Recovery() HandlerFunc

Recovery 捕获错误消息

type LimitRate

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

func GetLimitRateIns

func GetLimitRateIns(key string, limit int) *LimitRate

func NewLimitRate

func NewLimitRate(limit int, rate int) *LimitRate

func (*LimitRate) Check

func (tb *LimitRate) Check(n int) bool

func (*LimitRate) Wait

func (tb *LimitRate) Wait(n int)

type RouterGroup

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

func (*RouterGroup) ANY

func (group *RouterGroup) ANY(pattern string, handler HandlerFunc) *RouterGroup

func (*RouterGroup) DELETE

func (group *RouterGroup) DELETE(pattern string, handler HandlerFunc) *RouterGroup

func (*RouterGroup) GET

func (group *RouterGroup) GET(pattern string, handler HandlerFunc) *RouterGroup

func (*RouterGroup) Group

func (group *RouterGroup) Group(prefix string) *RouterGroup

func (*RouterGroup) HEAD

func (group *RouterGroup) HEAD(pattern string, handler HandlerFunc) *RouterGroup

func (*RouterGroup) OPTIONS

func (group *RouterGroup) OPTIONS(pattern string, handler HandlerFunc) *RouterGroup

func (*RouterGroup) PATCH

func (group *RouterGroup) PATCH(pattern string, handler HandlerFunc) *RouterGroup

func (*RouterGroup) POST

func (group *RouterGroup) POST(pattern string, handler HandlerFunc) *RouterGroup

func (*RouterGroup) PROXY

func (group *RouterGroup) PROXY(pattern string, uri string, logger *log.Logger, filter func(r *http.Request, w http.ResponseWriter, proxy *httputil.ReverseProxy), errorHandle func(http.ResponseWriter, *http.Request, error)) *RouterGroup

func (*RouterGroup) PUT

func (group *RouterGroup) PUT(pattern string, handler HandlerFunc) *RouterGroup

func (*RouterGroup) SetErrorHandle

func (group *RouterGroup) SetErrorHandle(handle *ErrorHandel) *RouterGroup

func (*RouterGroup) Static

func (group *RouterGroup) Static(relativePath string, root string) *RouterGroup

func (*RouterGroup) TRACE

func (group *RouterGroup) TRACE(pattern string, handler HandlerFunc) *RouterGroup

func (*RouterGroup) Use

func (group *RouterGroup) Use(middlewares ...HandlerFunc) *RouterGroup

Jump to

Keyboard shortcuts

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