mux

package module
v0.0.0-...-a535484 Latest Latest
Warning

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

Go to latest
Published: May 21, 2026 License: MIT Imports: 26 Imported by: 0

README

Gnet-Mux

一个基于 gnet/v2 的高性能 Web 框架,提供类似 Gin 的 API 风格。

功能特性

  • 🚀 高性能: 基于 gnet/v2 的事件驱动架构
  • 🎯 Gin风格API: 熟悉的路由和中间件设计
  • 🛡️ 内置中间件: Logger、Recovery、CORS等
  • 📝 丰富的响应方法: JSON、HTML、String、Redirect等
  • 🔧 灵活的上下文: 支持参数获取、数据存储等
  • 🛣️ 路径参数: 支持动态路由参数(如 /user/:id
  • 🔄 自定义JSON: 支持第三方JSON序列化库(如 goccy/go-jsonjson-iterator
  • 🌐 WebSocket支持: 基于 gorilla/websocket 的 WebSocket 连接支持

快速开始

安装
go mod init your-project
go get -u codeberg.org/kazuradrop/gmux
基本用法
package main

import (
    "codeberg.org/kazuradrop/gmux"
)

func main() {
    // 创建默认引擎(包含日志和恢复中间件)
    r := mux.Default()

    // 定义路由
    r.GET("/", func(c *mux.Context) {
        c.JSON(map[string]string{
            "message": "Hello, World!",
        })
    })

    // 启动服务器
    r.Run(":8080")
}

API 文档

创建引擎
// 创建空引擎
r := mux.New()

// 创建带默认中间件的引擎
r := mux.Default() // 包含 Logger() 和 Recovery()
路由注册
// 基本路由
r.GET("/", func(c *mux.Context) {
    c.String("Hello, World!")
})

r.POST("/users", func(c *mux.Context) {
    c.JSON(map[string]string{"message": "User created"})
})

// 路径参数路由
r.GET("/user/:id", func(c *mux.Context) {
    id := c.Param("id")
    c.JSON(map[string]interface{}{
        "user_id": id,
        "message": "User found",
    })
})

// 多个路径参数
r.GET("/user/:id/post/:postId", func(c *mux.Context) {
    userID := c.Param("id")
    postID := c.Param("postId")
    c.JSON(map[string]interface{}{
        "user_id": userID,
        "post_id": postID,
        "message": "User post found",
    })
})

// 混合静态路径和参数
r.GET("/api/v1/user/:id/profile", func(c *mux.Context) {
    id := c.Param("id")
    c.JSON(map[string]interface{}{
        "user_id": id,
        "profile": map[string]string{
            "name":  "John Doe",
            "email": "john@example.com",
        },
    })
})

r.PUT("/users/:id", func(c *mux.Context) {
    id := c.Param("id")
    c.JSON(map[string]string{"id": id, "message": "User updated"})
})

r.DELETE("/users/:id", func(c *mux.Context) {
    id := c.Param("id")
    c.Status(204) // No Content
})
中间件
// 使用内置中间件
r.Use(mux.Logger())
r.Use(mux.Recovery())
r.Use(mux.CORS())

// 自定义中间件
r.Use(func(next mux.HandlerFunc) mux.HandlerFunc {
    return func(c *mux.Context) {
        // 前置处理
        next(c)
        // 后置处理
    }
})
自定义JSON配置

框架支持使用第三方JSON序列化库,提供更好的性能或特定功能:

import (
    mux "gnet-mux"
    "github.com/goccy/go-json"  // 高性能JSON库
    // 或者使用 json-iterator
    // jsoniter "github.com/json-iterator/go"
)

// 使用默认的 encoding/json
r1 := mux.New()

// 使用 goccy/go-json
r2 := mux.NewWithConfig(mux.Config{
    JSONEncoder: json.Marshal,
    JSONDecoder: json.Unmarshal,
})

// 使用 json-iterator
var jsonAPI = jsoniter.ConfigCompatibleWithStandardLibrary
r3 := mux.NewWithConfig(mux.Config{
    JSONEncoder: jsonAPI.Marshal,
    JSONDecoder: jsonAPI.Unmarshal,
})

配置选项:

  • JSONEncoder: 自定义JSON编码函数,用于 c.JSON() 响应
  • JSONDecoder: 自定义JSON解码函数,用于 c.ShouldBindJSON()c.BindJSON()
  • XMLEncoder: 自定义XML编码函数,用于 c.XML() 响应
  • YAMLEncoder: 自定义YAML编码函数,用于 c.YAML() 响应
  • ProtoBufEncoder: 自定义ProtoBuf编码函数,用于 c.ProtoBuf() 响应
  • 如果不设置,将使用对应的标准库
自定义编码器配置

框架支持自定义各种格式的编码器:

import (
    mux "gnet-mux"
    "encoding/xml"
    "gopkg.in/yaml.v3"
    "google.golang.org/protobuf/proto"
)

// 使用自定义编码器
r := mux.NewWithConfig(mux.Config{
    // 自定义JSON编码器
    JSONEncoder: customJSONEncoder,

    // 自定义XML编码器
    XMLEncoder: xml.Marshal,

    // 自定义YAML编码器
    YAMLEncoder: yaml.Marshal,

    // 自定义ProtoBuf编码器
    ProtoBufEncoder: proto.Marshal,
})

// 示例:自定义JSON编码器,添加额外字段
func customJSONEncoder(v interface{}) ([]byte, error) {
    wrapper := map[string]interface{}{
        "data": v,
        "timestamp": time.Now().Unix(),
        "version": "1.0",
    }
    return json.Marshal(wrapper)
}
路径参数

框架支持动态路由参数,使用 : 前缀定义参数:

// 单个参数
r.GET("/user/:id", func(c *mux.Context) {
    id := c.Param("id")  // 获取路径参数
    c.JSON(map[string]string{"user_id": id})
})

// 多个参数
r.GET("/user/:userId/post/:postId", func(c *mux.Context) {
    userID := c.Param("userId")
    postID := c.Param("postId")
    c.JSON(map[string]string{
        "user_id": userID,
        "post_id": postID,
    })
})

// 混合静态路径和参数
r.GET("/api/v1/user/:id/profile", func(c *mux.Context) {
    id := c.Param("id")
    // 处理用户资料请求
})

路由匹配规则:

  • 静态路由优先于参数路由
  • 参数名区分大小写
  • 支持多级路径参数
  • 路径参数不能为空
路由分组

框架支持路由分组,可以为一组路由设置共同的前缀和中间件:

// 基本分组
{
    v1 := router.Group("/v1")
    v1.POST("/login", loginEndpoint)
    v1.POST("/submit", submitEndpoint)
    v1.POST("/read", readEndpoint)
}

// 带中间件的分组
{
    v2 := router.Group("/v2")
    v2.Use(AuthMiddleware())
    v2.POST("/login", loginEndpoint)
    v2.POST("/submit", submitEndpoint)
    v2.POST("/read", readEndpoint)
}

// 嵌套分组
api := router.Group("/api")
api.Use(APIMiddleware())
{
    v1 := api.Group("/v1")
    v1.Use(V1Middleware())
    v1.GET("/users/:id", getUserHandler)
    v1.POST("/users", createUserHandler)
}

// 分组中间件链式调用
admin := router.Group("/admin")
admin.Use(AuthMiddleware()).Use(AdminMiddleware())
admin.GET("/stats", adminStatsHandler)

分组特性:

  • 支持路径前缀自动拼接
  • 支持分组级别的中间件
  • 支持嵌套分组
  • 支持中间件链式调用
  • 与 Gin 框架 API 完全兼容
模糊路由(通配符路由)

框架支持模糊路由(通配符路由),与 Gin 框架 API 完全兼容:

func InitRouter() *mux.Engine {
    r := mux.New()
    r.Use(mux.Logger())
    r.Use(mux.Recovery())

    r.GET("/foo/*any", someHandler)

    return r
}
基本用法
// 通配符路由示例
router.GET("/foo/*any", func(c *mux.Context) {
    any := c.Param("any")
    c.JSON(mux.H{"any": any})
})

// API 通配符
router.GET("/api/*path", func(c *mux.Context) {
    path := c.Param("path")
    c.JSON(mux.H{"path": path})
})

// 静态文件服务
router.GET("/static/*filepath", func(c *mux.Context) {
    filepath := c.Param("filepath")
    // 处理静态文件请求
})
匹配示例
// 路由: /foo/*any
"/foo/bar"           → any="bar"
"/foo/bar/baz"       → any="bar/baz"
"/foo/bar/baz/qux"   → any="bar/baz/qux"
"/foo/"              → any=""
"/foo"               → 不匹配(需要 /foo/ 或 /foo/something)

// 路由: /api/*path
"/api/users"         → path="users"
"/api/users/123"     → path="users/123"
"/api/posts/456/comments" → path="posts/456/comments"
路由优先级

通配符路由具有最低优先级,具体路由和参数路由优先匹配:

// 注册路由
router.GET("/api/*path", wildcardHandler)    // 通配符路由
router.GET("/api/health", healthHandler)     // 具体路由
router.GET("/api/users/:id", userHandler)    // 参数路由

// 匹配结果
"/api/health"    → 匹配 healthHandler(具体路由优先)
"/api/users/123" → 匹配 userHandler(参数路由优先)
"/api/other"     → 匹配 wildcardHandler(通配符兜底)

模糊路由特性:

  • 支持任意深度的路径匹配
  • 自动处理空路径(trailing slash)
  • 具体路由优先于通配符路由
  • 参数路由优先于通配符路由
  • 与 Gin 框架行为完全一致
  • 适用于静态文件服务、API 兜底等场景

框架提供了完整的 Cookie 管理功能,与 Gin 框架 API 完全兼容:

// 获取 Cookie
cookie, err := c.Cookie("session_id")
if err != nil {
    // Cookie 不存在
    cookie = "default_value"
}

// 设置 Cookie
c.SetCookie(
    "session_id",    // name: Cookie 名称
    "abc123",        // value: Cookie 值
    3600,            // maxAge: 过期时间(秒)
    "/",             // path: 路径
    "localhost",     // domain: 域名
    false,           // secure: 是否仅 HTTPS
    true,            // httpOnly: 是否仅 HTTP(防止 XSS)
)

// Cookie 会话示例
router.GET("/login", func(c *mux.Context) {
    username := c.Query("username")
    c.SetCookie("user", username, 3600, "/", "", false, true)
    c.JSON(mux.H{"message": "登录成功"})
})

router.GET("/profile", func(c *mux.Context) {
    user, err := c.Cookie("user")
    if err != nil {
        c.JSON(mux.H{"error": "未登录"})
        return
    }
    c.JSON(mux.H{"user": user})
})

// 删除 Cookie(设置过期时间为 -1)
c.SetCookie("session_id", "", -1, "/", "", false, true)

Cookie 特性:

  • 支持获取和设置 Cookie
  • 支持所有标准 Cookie 属性
  • 自动处理路径默认值
  • 与 Gin 框架 API 完全兼容
  • 支持安全 Cookie 设置
静态文件服务

框架提供了完整的静态文件服务功能,与 Gin 框架 API 完全兼容:

// 静态目录服务
router.Static("/assets", "./assets")

// 自定义文件系统服务
router.StaticFS("/more_static", http.Dir("my_file_system"))

// 单个文件服务
router.StaticFile("/favicon.ico", "./resources/favicon.ico")

// 在处理器中发送文件
router.GET("/download", func(c *mux.Context) {
    c.File("./files/document.pdf")
})

静态文件特性:

  • 支持目录和单文件服务
  • 自动 MIME 类型检测
  • 安全路径检查(防止目录遍历攻击)
  • 自动缓存头设置
  • 支持自定义文件系统
  • 目录索引文件支持(index.html)
  • 与 Gin 框架 API 完全兼容

使用示例:

func main() {
    router := mux.Default()

    // 静态文件服务(完全遵循 Gin 示例)
    router.Static("/assets", "./assets")
    router.StaticFS("/more_static", http.Dir("my_file_system"))
    router.StaticFile("/favicon.ico", "./resources/favicon.ico")

    router.Run(":8080")
}
文件上传

框架提供了完整的文件上传功能,与 Gin 框架 API 完全兼容:

单文件上传
func main() {
    router := mux.Default()
    // 设置多部分表单的内存限制(默认为 32 MiB)
    router.MaxMultipartMemory = 8 << 20  // 8 MiB

    router.POST("/upload", func(c *mux.Context) {
        // 单文件
        file, _ := c.FormFile("file")
        log.Println(file.Filename)

        // 上传文件到指定目录
        c.SaveUploadedFile(file, "./files/" + file.Filename)

        c.Status(http.StatusOK).String(fmt.Sprintf("'%s' uploaded!", file.Filename))
    })

    router.Run(":8080")
}
多文件上传
router.POST("/upload/multiple", func(c *mux.Context) {
    // 多部分表单
    form, _ := c.MultipartForm()
    files := form.File["files"]

    for _, file := range files {
        log.Println(file.Filename)

        // 上传文件到指定目录
        c.SaveUploadedFile(file, "./files/" + file.Filename)
    }
    c.Status(http.StatusOK).String(fmt.Sprintf("%d files uploaded!", len(files)))
})

文件上传特性:

  • 支持单文件和多文件上传
  • 可配置内存限制(MaxMultipartMemory)
  • 自动创建目录结构
  • 安全的文件保存
  • 与 Gin 框架 API 完全兼容
  • 支持大文件上传(超过内存限制时自动使用临时文件)

重要提示: file.Filename 不应该被信任。参考 MDN Content-Disposition 文档

上下文方法
获取请求数据
// URL 参数
id := c.Param("id")

// 查询参数
name := c.Query("name")
age := c.DefaultQuery("age", "18")

// 表单数据
username := c.PostForm("username")
password := c.DefaultPostForm("password", "")

// 文件上传
file, err := c.FormFile("file")                    // 单文件上传
form, err := c.MultipartForm()                     // 多文件上传
err := c.SaveUploadedFile(file, "./uploads/file")  // 保存上传的文件

// 请求头
token := c.GetHeader("Authorization")
设置响应
// JSON 响应
c.JSON(map[string]interface{}{
    "status": "success",
    "data": data,
})

// XML 响应
c.XML(map[string]interface{}{
    "status": "success",
    "data": data,
})

// YAML 响应
c.YAML(map[string]interface{}{
    "status": "success",
    "data": data,
})

// Protocol Buffer 响应
c.ProtoBuf(protoMessage)

// 字符串响应
c.String("Hello, %s!", name)

// HTML 响应
c.HTML("<h1>Welcome</h1>")

// 原始数据响应
c.Data("application/octet-stream", []byte("binary data"))

// 从 Reader 读取数据响应
c.DataFromReader(http.StatusOK, contentLength, "text/plain", reader, extraHeaders)

// 重定向
c.Redirect(302, "/login")

// 设置状态码
c.Status(404).String("Not Found")

// 设置响应头
c.Header("X-Custom-Header", "value")

// Cookie 操作
cookie, err := c.Cookie("session_id")  // 获取 Cookie
c.SetCookie("session_id", "abc123", 3600, "/", "localhost", false, true)  // 设置 Cookie
JSON数据绑定
// JSON数据绑定
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

var user User
// 绑定JSON数据(使用配置的JSON解码器)
if err := c.ShouldBindJSON(&user); err != nil {
    c.Status(400).JSON(map[string]string{"error": err.Error()})
    return
}

// 绑定JSON数据并自动处理错误
if err := c.BindJSON(&user); err != nil {
    return // 自动返回400错误
}
上下文存储
// 存储值
c.Set("user", user)

// 获取值
user, exists := c.Get("user")
user := c.MustGet("user") // 不存在时会 panic
中间件控制
// 执行下一个处理器
c.Next()

// 中止执行
c.Abort()
c.AbortWithStatus(403)
c.AbortWithStatusJSON(400, map[string]string{"error": "Bad Request"})

示例

完整示例
package main

import (
    "net/http"
    "codeberg.org/kazuradrop/gmux"
)

func main() {
    r := mux.Default()

    // 添加 CORS 中间件
    r.Use(mux.CORS())

    // 基本路由
    r.GET("/", func(c *mux.Context) {
        c.JSON(map[string]string{"message": "Hello, World!"})
    })

    // 带参数的路由
    r.GET("/user/:id", func(c *mux.Context) {
        id := c.Param("id")
        c.JSON(map[string]string{"user_id": id})
    })

    // 查询参数
    r.GET("/search", func(c *mux.Context) {
        query := c.DefaultQuery("q", "")
        page := c.DefaultQuery("page", "1")
        c.JSON(map[string]string{
            "query": query,
            "page":  page,
        })
    })

    // POST 请求
    r.POST("/user", func(c *mux.Context) {
        name := c.PostForm("name")
        email := c.PostForm("email")

        if name == "" {
            c.AbortWithStatusJSON(http.StatusBadRequest,
                map[string]string{"error": "Name is required"})
            return
        }

        c.JSON(map[string]interface{}{
            "message": "User created",
            "user": map[string]string{
                "name":  name,
                "email": email,
            },
        })
    })

    // 启动服务器
    r.Run(":8080")
}
自定义中间件示例
// 认证中间件
func AuthMiddleware() mux.Middleware {
    return func(next mux.HandlerFunc) mux.HandlerFunc {
        return func(c *mux.Context) {
            token := c.GetHeader("Authorization")
            if token == "" {
                c.AbortWithStatusJSON(401, map[string]string{
                    "error": "Authorization header required",
                })
                return
            }

            // 验证 token 逻辑...

            c.Set("user_id", "123")
            next(c)
        }
    }
}

// 使用中间件
r.Use(AuthMiddleware())

性能

基于 gnet/v2 的高性能网络引擎,相比传统的 net/http 具有更好的性能表现:

  • 更低的内存占用
  • 更高的并发处理能力
  • 更少的 GC 压力
  • 支持多核并行处理

与 Gin 的对比

特性 Gnet-Mux Gin
网络引擎 gnet/v2 net/http
性能 更高 标准
API 风格 类似 Gin 原生
中间件 支持 支持
生态系统 新兴 成熟
WebSocket 支持

框架支持 WebSocket 连接,使用 gorilla/websocket 库:

import (
    "github.com/gorilla/websocket"
    mux "codeberg.org/kazuradrop/gmux"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

func handleWebSocket(c *mux.Context) {
    // 升级 HTTP 连接为 WebSocket 连接
    conn, err := c.UpgradeWebSocket(&upgrader)
    if err != nil {
        return
    }
    defer conn.Close()

    // 处理 WebSocket 消息
    for {
        messageType, message, err := conn.ReadMessage()
        if err != nil {
            break
        }
        // 回显消息
        err = conn.WriteMessage(messageType, message)
        if err != nil {
            break
        }
    }
}

// 注册 WebSocket 路由
r.GET("/ws", handleWebSocket)

WebSocket 特性:

  • 支持 gorilla/websocket
  • 提供 c.Writer()c.Request() 方法用于 WebSocket 升级
  • 提供 c.UpgradeWebSocket() 便捷方法
  • 与 Gin 框架 API 完全兼容
  • 支持自定义 WebSocket 升级器配置

注意事项

  1. 这是一个基于 gnet/v2 的实验性框架
  2. API 可能会在后续版本中发生变化
  3. 建议在生产环境使用前进行充分测试

贡献

欢迎提交 Issue 和 Pull Request!

许可证

MIT License

Documentation

Index

Constants

View Source
const (
	PlatformGoogleAppEngine = "X-Appengine-Remote-Addr"
	PlatformCloudflare      = "CF-Connecting-IP"
	PlatformFlyIO           = "Fly-Client-IP"
)

Trusted platform constants for common CDN/proxy providers

Variables

View Source
var (
	JSON          = jsonBinding{}
	XML           = xmlBinding{}
	Form          = formBinding{}
	Query         = queryBinding{}
	FormPost      = formPostBinding{}
	FormMultipart = formMultipartBinding{}
)

Binding instances

View Source
var (
	CRLF = []byte("\r\n\r\n")
)
View Source
var Validator = validator.New()

Validator instance

Functions

This section is empty.

Types

type Binding

type Binding interface {
	Name() string
	Bind(*http.Request, interface{}) error
}

Binding interface defines the binding behavior

func DefaultBinding

func DefaultBinding(method, contentType string) Binding

DefaultBinding returns the appropriate binding based on method and content type

type BindingBody

type BindingBody interface {
	Binding
	BindBody([]byte, interface{}) error
}

BindingBody interface extends Binding for body-based bindings

type Config

type Config struct {
	// Multicore indicates whether the server should be started in multi-core mode
	Multicore bool
	// JSONEncoder is the function used to encode JSON responses
	// If not set, encoding/json.Marshal will be used
	JSONEncoder func(v interface{}) ([]byte, error)

	// JSONDecoder is the function used to decode JSON requests
	// If not set, encoding/json.Unmarshal will be used
	JSONDecoder func(data []byte, v interface{}) error

	// XMLEncoder is the function used to encode XML responses
	// If not set, encoding/xml.Marshal will be used
	XMLEncoder func(v interface{}) ([]byte, error)

	// YAMLEncoder is the function used to encode YAML responses
	// If not set, gopkg.in/yaml.v3.Marshal will be used
	YAMLEncoder func(v interface{}) ([]byte, error)

	// ProtoBufEncoder is the function used to encode ProtoBuf responses
	// If not set, google.golang.org/protobuf/proto.Marshal will be used
	ProtoBufEncoder func(v proto.Message) ([]byte, error)
}

Config represents the configuration for the Engine

type Context

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

Context represents the context of the current HTTP request

func (*Context) Abort

func (c *Context) Abort()

Abort prevents pending handlers from being called

func (*Context) AbortWithError

func (c *Context) AbortWithError(code int, err error)

AbortWithError aborts with error

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(code int)

AbortWithStatus aborts with a status code

func (*Context) AbortWithStatusJSON

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

AbortWithStatusJSON aborts with a JSON response

func (*Context) Bind

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

Bind binds the request and aborts with 400 on error

func (*Context) BindJSON

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

BindJSON binds JSON and aborts with 400 on error

func (*Context) BindQuery

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

BindQuery binds query parameters and aborts with 400 on error

func (*Context) BindXML

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

BindXML binds XML and aborts with 400 on error

func (*Context) BindYAML

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

BindYAML is not implemented yet

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP implements a best effort algorithm to return the real client IP. It checks, in order:

  1. TrustedPlatform header (e.g., CF-Connecting-IP for Cloudflare)
  2. RemoteIPHeaders (X-Forwarded-For, X-Real-Ip) if the remote IP is a trusted proxy
  3. Falls back to Request.RemoteAddr

Use engine.SetTrustedProxies() to configure which proxies are trusted.

func (*Context) Cookie

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

Cookie returns the named cookie provided in the request

func (*Context) Data

func (c *Context) Data(contentType string, data []byte)

Data sends raw data response

func (*Context) DataFromReader

func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string)

DataFromReader sends data from a reader with optional extra headers

func (*Context) DefaultPostForm

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

DefaultPostForm returns the form parameter value or default value

func (*Context) DefaultQuery

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

DefaultQuery returns the query parameter value or default value

func (*Context) File

func (c *Context) File(filepath string)

File sends a file response

func (*Context) FormFile

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

FormFile returns the first file for the provided form key

func (*Context) Get

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

Get retrieves a value from the context

func (*Context) GetHeader

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

GetHeader returns the request header value

func (*Context) GetPostForm

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

GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded form or multipart form when it exists `(value, true)` (even when the value is an empty string), otherwise it returns ("", false). For example, during a PATCH request to update the user's email:

    email=mail@example.com  -->  ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
	   email=                  -->  ("", true) := GetPostForm("email") // set email to ""
                            -->  ("", false) := GetPostForm("email") // do nothing with email

func (*Context) GetPostFormArray

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

GetPostFormArray returns a slice of strings for a given form key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetPostFormMap

func (c *Context) GetPostFormMap(key string) (map[string]string, bool)

GetPostFormMap returns a map for a given form key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetQuery

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

GetQuery is like Query(), it returns the keyed url query value if it exists `(value, true)` (even when the value is an empty string), otherwise it returns `("", false)`. It is shortcut for `c.Request().URL.Query().Get(key)`

GET /?name=Manu&lastname=
("Manu", true) == c.GetQuery("name")
("", false) == c.GetQuery("id")
("", true) == c.GetQuery("lastname")

func (*Context) GetQueryArray

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

GetQueryArray returns a slice of strings for a given query key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetQueryMap

func (c *Context) GetQueryMap(key string) (map[string]string, bool)

GetQueryMap returns a map for a given query key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetRawData

func (c *Context) GetRawData() ([]byte, error)

GetRawData returns stream data.

func (*Context) HTML

func (c *Context) HTML(html string)

HTML sends an HTML response

func (*Context) Header

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

Header sets the response header

func (*Context) JSON

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

JSON sends a JSON response

func (*Context) MultipartForm

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

MultipartForm returns the parsed multipart form, including file uploads

func (*Context) MustBindWith

func (c *Context) MustBindWith(obj interface{}, b Binding) error

MustBindWith binds using the specified binding and aborts on error

func (*Context) MustGet

func (c *Context) MustGet(key string) interface{}

MustGet retrieves a value from the context or panics

func (*Context) Next

func (c *Context) Next()

Next executes the next handler in the chain

func (*Context) Param

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

Param returns the value of the URL parameter

func (*Context) PostForm

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

PostForm returns the form parameter value

func (*Context) PostFormArray

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

PostFormArray returns a slice of strings for a given form key. The length of the slice depends on the number of params with the given key.

func (*Context) PostFormMap

func (c *Context) PostFormMap(key string) (dicts map[string]string)

PostFormMap returns a map for a given form key.

func (*Context) ProtoBuf

func (c *Context) ProtoBuf(code int, obj proto.Message)

ProtoBuf sends a Protocol Buffer response

func (*Context) Query

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

Query returns the query parameter value

func (*Context) QueryArray

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

QueryArray returns a slice of strings for a given query key. The length of the slice depends on the number of params with the given key.

func (*Context) QueryMap

func (c *Context) QueryMap(key string) (dicts map[string]string)

QueryMap returns a map for a given query key.

func (*Context) Redirect

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

Redirect sends a redirect response

func (*Context) RemoteIP

func (c *Context) RemoteIP() string

RemoteIP parses the IP from Request.RemoteAddr, stripping the port

func (*Context) Request

func (c *Context) Request() *http.Request

Request returns the underlying http.Request

func (*Context) SaveUploadedFile

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

SaveUploadedFile uploads the form file to specific dst

func (*Context) Set

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

Set stores a key-value pair in the context

func (*Context) SetCookie

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

SetCookie adds a Set-Cookie header to the ResponseWriter's headers

func (*Context) ShouldBind

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

ShouldBind binds the request to obj based on content type

func (*Context) ShouldBindBodyWith

func (c *Context) ShouldBindBodyWith(obj interface{}, bb BindingBody) error

ShouldBindBodyWith binds the request body and stores it in context for reuse

func (*Context) ShouldBindJSON

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

ShouldBindJSON binds the request body as JSON

func (*Context) ShouldBindQuery

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

ShouldBindQuery binds the query parameters

func (*Context) ShouldBindWith

func (c *Context) ShouldBindWith(obj interface{}, b Binding) error

ShouldBindWith binds the request using the specified binding

func (*Context) ShouldBindXML

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

ShouldBindXML binds the request body as XML

func (*Context) ShouldBindYAML

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

ShouldBindYAML is not implemented yet

func (*Context) Status

func (c *Context) Status(code int) *Context

Status sets the response status code

func (*Context) Stream

func (c *Context) Stream(step func(w io.Writer) bool)

Stream sends a streaming response using chunked transfer encoding The step function receives an io.Writer and should return true to continue streaming, false to stop

func (*Context) String

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

String sends a string response

func (*Context) UpgradeWebSocket

func (c *Context) UpgradeWebSocket(upgrader *websocket.Upgrader) (*websocket.Conn, error)

UpgradeWebSocket upgrades the HTTP connection to a WebSocket connection using the provided upgrader This method follows the Gin framework pattern for WebSocket upgrades

func (*Context) Writer

func (c *Context) Writer() http.ResponseWriter

Writer returns an http.ResponseWriter compatible interface for websocket upgrading

func (*Context) XML

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

XML sends an XML response

func (*Context) YAML

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

YAML sends a YAML response

type Engine

type Engine struct {
	gnet.BuiltinEventEngine

	MaxMultipartMemory int64 // Maximum memory for multipart forms (default 32 MiB)

	// ForwardedByClientIP if enabled, client IP will be parsed from the request's headers
	// that match those stored at `RemoteIPHeaders`. If no IP was fetched, it falls back
	// to the IP obtained from `Request.RemoteAddr`.
	ForwardedByClientIP bool

	// TrustedPlatform if set to a constant of value gin.Platform*, trusts the headers set by
	// that platform, for example to determine the client IP
	TrustedPlatform string

	// RemoteIPHeaders list of headers used to obtain the client IP when
	// `ForwardedByClientIP` is `true` and `Request.RemoteAddr` is matched by at least one of the
	// network origins of list defined by `SetTrustedProxies`.
	RemoteIPHeaders []string
	// contains filtered or unexported fields
}

Engine is the main router engine

func Default

func Default() *Engine

Default creates a new Engine with default middleware

func New

func New() *Engine

New creates a new Engine instance with default configuration

func NewWithConfig

func NewWithConfig(config Config) *Engine

NewWithConfig creates a new Engine instance with custom configuration

func (*Engine) DELETE

func (e *Engine) DELETE(path string, handler HandlerFunc)

DELETE registers a DELETE route

func (*Engine) GET

func (e *Engine) GET(path string, handler HandlerFunc)

GET registers a GET route

func (*Engine) Group

func (e *Engine) Group(prefix string) *RouterGroup

Group creates a new router group with the given path prefix

func (*Engine) HEAD

func (e *Engine) HEAD(path string, handler HandlerFunc)

HEAD registers a HEAD route

func (*Engine) OPTIONS

func (e *Engine) OPTIONS(path string, handler HandlerFunc)

OPTIONS registers an OPTIONS route

func (*Engine) OnBoot

func (e *Engine) OnBoot(eng gnet.Engine) gnet.Action

OnBoot is called when the server starts

func (*Engine) OnClose

func (e *Engine) OnClose(c gnet.Conn, err error) gnet.Action

OnClose is called when a connection is closed

func (*Engine) OnOpen

func (e *Engine) OnOpen(c gnet.Conn) ([]byte, gnet.Action)

OnOpen is called when a new connection is opened

func (*Engine) OnTraffic

func (e *Engine) OnTraffic(c gnet.Conn) gnet.Action

OnTraffic handles incoming HTTP requests

func (*Engine) PATCH

func (e *Engine) PATCH(path string, handler HandlerFunc)

PATCH registers a PATCH route

func (*Engine) POST

func (e *Engine) POST(path string, handler HandlerFunc)

POST registers a POST route

func (*Engine) PUT

func (e *Engine) PUT(path string, handler HandlerFunc)

PUT registers a PUT route

func (*Engine) Run

func (e *Engine) Run(addr ...string) error

Run starts the HTTP server

func (*Engine) SetTrustedProxies

func (e *Engine) SetTrustedProxies(trustedProxies []string) error

SetTrustedProxies set a list of network origins (IPv4 addresses, IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs) from which to trust request's headers that contain alternative client IP when `ForwardedByClientIP` is enabled. `SetTrustedProxies(nil)` can disable the feature, client IP will be obtained directly from `Request.RemoteAddr`.

func (*Engine) Static

func (e *Engine) Static(relativePath, root string)

Static serves files from the given file system root

func (*Engine) StaticFS

func (e *Engine) StaticFS(relativePath string, fs http.FileSystem)

StaticFS serves files from the given file system

func (*Engine) StaticFile

func (e *Engine) StaticFile(relativePath, filepath string)

StaticFile serves a single file

func (*Engine) Use

func (e *Engine) Use(middleware ...Middleware)

Use adds middleware to the engine

type H

type H map[string]interface{}

H is a shortcut for map[string]interface{}

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc defines the handler function type

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

Middleware defines the middleware function type

func CORS

func CORS() Middleware

CORS returns a CORS middleware

func Logger

func Logger() Middleware

Logger returns a logger middleware

func Recovery

func Recovery() Middleware

Recovery returns a recovery middleware

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params

type Params []Param

Params is a Params-slice, returned by the router. The slice is ordered, first URL parameter is also the first slice value.

func (Params) ByName

func (ps Params) ByName(name string) string

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

func (Params) Get

func (ps Params) Get(name string) (string, bool)

Get returns the value of the first Param which key matches the given name and a boolean true. If no matching Param is found, an empty string is returned and a boolean false.

type Response

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

Response represents the HTTP response

type RouteInfo

type RouteInfo struct {
	Method  string
	Path    string
	Handler HandlerFunc
}

RouteInfo contains route information

type Router

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

Router handles route registration and matching

type RouterGroup

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

RouterGroup represents a group of routes with a common prefix and middleware

func (*RouterGroup) DELETE

func (rg *RouterGroup) DELETE(path string, handler HandlerFunc)

DELETE registers a DELETE route in the router group

func (*RouterGroup) GET

func (rg *RouterGroup) GET(path string, handler HandlerFunc)

GET registers a GET route in the router group

func (*RouterGroup) Group

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

Group creates a new nested router group with the given path prefix

func (*RouterGroup) HEAD

func (rg *RouterGroup) HEAD(path string, handler HandlerFunc)

HEAD registers a HEAD route in the router group

func (*RouterGroup) OPTIONS

func (rg *RouterGroup) OPTIONS(path string, handler HandlerFunc)

OPTIONS registers an OPTIONS route in the router group

func (*RouterGroup) PATCH

func (rg *RouterGroup) PATCH(path string, handler HandlerFunc)

PATCH registers a PATCH route in the router group

func (*RouterGroup) POST

func (rg *RouterGroup) POST(path string, handler HandlerFunc)

POST registers a POST route in the router group

func (*RouterGroup) PUT

func (rg *RouterGroup) PUT(path string, handler HandlerFunc)

PUT registers a PUT route in the router group

func (*RouterGroup) Use

func (rg *RouterGroup) Use(middleware ...Middleware) *RouterGroup

Use adds middleware to the router group

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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