gctx

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2025 License: MIT Imports: 17 Imported by: 4

README

GMC Ctx 模块

简介

GMC Ctx(Context)模块提供 HTTP 请求上下文,封装了请求和响应操作,是 Web 和 API 开发的核心组件。

功能特性

  • 请求处理:获取请求参数、headers、cookies 等
  • 响应输出:支持 JSON、XML、HTML、文件等多种响应格式
  • 会话管理:集成会话支持
  • 模板渲染:集成模板引擎
  • 文件上传:处理文件上传
  • 国际化:集成 i18n 支持
  • 元数据存储:存储请求级别的临时数据
  • 分页支持:内置分页工具

快速开始

获取请求参数
func Handler(ctx gcore.Ctx) {
    // GET 参数
    name := ctx.Query("name", "default")
    
    // POST 参数
    email := ctx.POST("email", "")
    
    // 路由参数
    id := ctx.Param("id")
    
    // 所有参数(优先级:POST > GET > 路由)
    value := ctx.GetParam("key")
}
输出响应
func Handler(ctx gcore.Ctx) {
    // JSON 响应
    ctx.WriteJSON(gcore.M{
        "status": "success",
        "data":   []string{"item1", "item2"},
    })
    
    // 文本响应
    ctx.Write("Hello World")
    
    // HTML 响应
    ctx.WriteHTML("<h1>Title</h1>")
    
    // XML 响应
    ctx.WriteXML(data)
    
    // 文件下载
    ctx.WriteFile("path/to/file.pdf", "downloaded.pdf")
}
模板渲染
func Handler(ctx gcore.Ctx) {
    data := gcore.M{
        "title": "My Page",
        "user":  "John",
    }
    
    // 渲染模板
    ctx.View("template.html", data)
    
    // 或
    ctx.Template().Display("template.html", data)
}
获取请求信息
func Handler(ctx gcore.Ctx) {
    // 请求方法
    method := ctx.Method()
    
    // 请求路径
    path := ctx.Request().URL.Path
    
    // Headers
    userAgent := ctx.GetHeader("User-Agent")
    
    // Cookies
    value, _ := ctx.GetCookie("session_id")
    
    // 客户端 IP
    ip := ctx.ClientIP()
    
    // 请求体
    body, _ := ctx.Body()
}
文件上传
func Handler(ctx gcore.Ctx) {
    // 获取上传的文件
    file, header, err := ctx.GetPostFile("upload")
    if err != nil {
        ctx.WriteE(err)
        return
    }
    defer file.Close()
    
    // 保存文件
    err = ctx.SaveFile(header, "./uploads/"+header.Filename)
    if err != nil {
        ctx.WriteE(err)
        return
    }
    
    ctx.WriteJSON(gcore.M{
        "status":   "success",
        "filename": header.Filename,
    })
}
会话操作
func Handler(ctx gcore.Ctx) {
    sess := ctx.Session()
    
    // 设置会话
    sess.Set("user_id", 123)
    
    // 获取会话
    userID := sess.Get("user_id")
    
    // 删除会话
    sess.Delete("temp_key")
    
    // 销毁会话
    sess.Destroy()
}

API 参考

请求方法
  • Request() *http.Request:获取原始请求
  • Response() http.ResponseWriter:获取原始响应
  • Method() string:获取请求方法
  • Query(key, defaultValue) string:获取 GET 参数
  • POST(key, defaultValue) string:获取 POST 参数
  • Param(key) string:获取路由参数
  • GetParam(key) string:获取参数(POST > GET > 路由)
  • Body() ([]byte, error):获取请求体
  • BodyJSON(v interface{}) error:解析 JSON 请求体
  • GetHeader(key) string:获取 Header
  • GetCookie(name) (string, error):获取 Cookie
  • ClientIP() string:获取客户端 IP
响应方法
  • Write(data ...interface{}):输出文本
  • WriteE(err error):输出错误
  • WriteJSON(data interface{}):输出 JSON
  • WriteJSONP(callback string, data interface{}):输出 JSONP
  • WriteXML(data interface{}):输出 XML
  • WriteHTML(html string):输出 HTML
  • WriteFile(filepath, downloadName):下载文件
  • SetHeader(key, value string):设置响应 Header
  • SetCookie(cookie *http.Cookie):设置 Cookie
  • Redirect(url string, code int):重定向
  • StatusCode(code int):设置状态码
模板和国际化
  • View(tpl string, data):渲染模板
  • Template() gcore.Template:获取模板引擎
  • I18n() gcore.I18n:获取国际化工具
  • Tr(lang, key, defaultMsg):翻译文本
文件上传
  • GetPostFile(name) (multipart.File, *multipart.FileHeader, error)
  • SaveFile(header, dst) error
其他
  • Session() gcore.Session:获取会话
  • NewPager(count, perPage) *gutil.Pager:创建分页器
  • Logger() gcore.Logger:获取日志记录器
  • Config() gcore.Config:获取配置
  • App() gcore.App:获取应用实例
  • Metadata() *gmap.Map:获取元数据存储

使用场景

  1. Web 应用:处理 HTTP 请求和响应
  2. RESTful API:构建 API 接口
  3. 文件上传:处理文件上传功能
  4. 用户认证:基于会话的用户认证
  5. 多语言支持:国际化应用

最佳实践

1. 参数验证
func Handler(ctx gcore.Ctx) {
    email := ctx.POST("email", "")
    if email == "" {
        ctx.WriteJSON(gcore.M{
            "error": "email is required",
        })
        return
    }
    
    // 处理业务逻辑
}
2. 统一错误处理
func Handler(ctx gcore.Ctx) {
    data, err := doSomething()
    if err != nil {
        ctx.WriteE(err)
        return
    }
    
    ctx.WriteJSON(data)
}
3. 使用元数据传递数据
// 在中间件中设置
func AuthMiddleware(ctx gcore.Ctx, next func()) {
    user := authenticate(ctx)
    ctx.Metadata().Store("user", user)
    next()
}

// 在处理器中使用
func Handler(ctx gcore.Ctx) {
    user, _ := ctx.Metadata().Load("user")
    // 使用 user
}

相关链接

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CloudFlareIPS

type CloudFlareIPS struct {
	Result struct {
		Ipv4Cidrs []string `json:"ipv4_cidrs"`
		Ipv6Cidrs []string `json:"ipv6_cidrs"`
		Etag      string   `json:"etag"`
	} `json:"result"`
	Success  bool          `json:"success"`
	Errors   []interface{} `json:"errors"`
	Messages []interface{} `json:"messages"`
}

type Ctx

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

func NewCtx

func NewCtx() *Ctx

func NewCtxFromConfig

func NewCtxFromConfig(c gcore.Config) *Ctx

func NewCtxFromConfigFile

func NewCtxFromConfigFile(file string) (ctx *Ctx, err error)

func NewCtxWithHTTP

func NewCtxWithHTTP(w http.ResponseWriter, r *http.Request) *Ctx

func (*Ctx) APIServer

func (this *Ctx) APIServer() gcore.APIServer

func (*Ctx) App

func (this *Ctx) App() gcore.App

func (*Ctx) ClientIP

func (this *Ctx) ClientIP() (ip string)

ClientIP acquires the real client ip, search in X-Forwarded-For, X-Real-IP, request.RemoteAddr.

func (*Ctx) Clone

func (this *Ctx) Clone() gcore.Ctx

func (*Ctx) CloneWithHTTP

func (this *Ctx) CloneWithHTTP(w http.ResponseWriter, r *http.Request, ps ...gcore.Params) gcore.Ctx

func (*Ctx) Config

func (this *Ctx) Config() gcore.Config

func (*Ctx) Conn

func (this *Ctx) Conn() net.Conn

func (*Ctx) Controller

func (this *Ctx) Controller() gcore.Controller

func (*Ctx) ControllerMethod

func (this *Ctx) ControllerMethod() string

func (*Ctx) Cookie

func (this *Ctx) Cookie(name string) string

Cookie returns the named cookie provided in the request or ErrNoCookie if not found. And return the named cookie is unescaped. If multiple cookies match the given name, only one cookie will be returned.

func (*Ctx) FormFile

func (this *Ctx) FormFile(name string, maxMultipartMemory int64) (*multipart.FileHeader, error)

FormFile returns the first file for the provided form key. maxMultipartMemory limits the request form parser using memory byte size.

func (*Ctx) FullPath

func (this *Ctx) FullPath() string

FullPath returns a matched route full path. For not found routes returns an empty string.

router.GET("/user/:id", func(c gcore.Ctx) {
    c.FullPath() == "/user/:id" // true
})

func (*Ctx) GET

func (this *Ctx) GET(key string, Default ...string) (val string)

GET gets the first value associated with the given key in url query.

func (*Ctx) GETArray

func (this *Ctx) GETArray(key string, Default ...string) (val []string)

GETArray returns a slice of strings for a given query key.

func (*Ctx) GETData

func (this *Ctx) GETData() (data map[string]string)

GETData gets full k,v query data from request url.

func (*Ctx) Get

func (this *Ctx) Get(key interface{}) (value interface{}, exists bool)

Get returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)

func (*Ctx) GetParam

func (this *Ctx) GetParam(key string) string

GetParam returns the value of the URL param. It is a shortcut for c.Param().ByName(key)

router.GET("/user/:id", func(c *gcore.Ctx) {
    // a GET request to /user/john
    id := c.Param("id") // id == "john"
})

func (*Ctx) GetPost

func (this *Ctx) GetPost(key string, Default ...string) (val string)

GetPost gets the first value associated with the given key in GET or POST.

func (*Ctx) Header

func (this *Ctx) Header(key string) string

Header returns value from request headers.

func (*Ctx) Host

func (this *Ctx) Host() (host string)

Host returns the HOST in requested HTTP HEADER.

func (*Ctx) I18n

func (this *Ctx) I18n() gcore.I18n

func (*Ctx) IsAJAX

func (this *Ctx) IsAJAX() bool

IsAJAX returns true if the request is jquery AJAX request.

func (*Ctx) IsDELETE

func (this *Ctx) IsDELETE() bool

IsDELETE returns true if the request is DELETE request.

func (*Ctx) IsGET

func (this *Ctx) IsGET() bool

IsGET returns true if the request is GET request.

func (*Ctx) IsHEAD

func (this *Ctx) IsHEAD() bool

IsHEAD returns true if the request is HEAD request.

func (*Ctx) IsOPTIONS

func (this *Ctx) IsOPTIONS() bool

IsOPTIONS returns true if the request is OPTIONS request.

func (*Ctx) IsPATCH

func (this *Ctx) IsPATCH() bool

IsPATCH returns true if the request is PATCH request.

func (*Ctx) IsPOST

func (this *Ctx) IsPOST() bool

IsPOST returns true if the request is POST request.

func (*Ctx) IsPUT

func (this *Ctx) IsPUT() bool

IsPUT returns true if the request is PUT request.

func (*Ctx) IsTLSRequest

func (this *Ctx) IsTLSRequest() bool

func (*Ctx) IsWebsocket

func (this *Ctx) IsWebsocket() bool

IsWebsocket returns true if the request headers indicate that a websocket handshake is being initiated by the client.

func (*Ctx) JSON

func (this *Ctx) JSON(code int, data interface{}) (err error)

JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".

func (*Ctx) JSONP

func (this *Ctx) JSONP(code int, data interface{}) (err error)

JSONP serializes the given struct as JSON into the response body. It sets the Content-Type as "application/javascript".

func (*Ctx) JSONPTo

func (this *Ctx) JSONPTo(w io.Writer, code int, data interface{}) (err error)

JSONPTo serializes the given struct as JSON into the io.Writer body. It sets the Content-Type as "application/javascript".

func (*Ctx) JSONTo

func (this *Ctx) JSONTo(w io.Writer, code int, data interface{}) (err error)

JSONTo serializes the given struct as JSON into the io.Writer. It also sets the Content-Type as "application/json".

func (*Ctx) LocalAddr

func (this *Ctx) LocalAddr() string

func (*Ctx) Logger

func (this *Ctx) Logger() gcore.Logger

func (*Ctx) MultipartForm

func (this *Ctx) MultipartForm(maxMultipartMemory int64) (*multipart.Form, error)

MultipartForm is the parsed multipart form, including file uploads. maxMultipartMemory limits the request form parser using memory byte size.

func (*Ctx) MustGet

func (this *Ctx) MustGet(key interface{}) (v interface{})

MustGet returns the value for the given key if it exists, otherwise it panics.

func (*Ctx) NewPager

func (this *Ctx) NewPager(perPage int, total int64) gcore.Paginator

NewPager create a new paginator used for template

func (*Ctx) POST

func (this *Ctx) POST(key string, Default ...string) (val string)

POST gets the first value associated with the given key in post body.

func (*Ctx) POSTArray

func (this *Ctx) POSTArray(key string, Default ...string) (val []string)

POSTArray 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 (*Ctx) POSTData

func (this *Ctx) POSTData() (data map[string]string)

POSTData gets full k,v query data from request FORM.

func (*Ctx) Param

func (this *Ctx) Param() gcore.Params

func (*Ctx) PrettyJSON

func (this *Ctx) PrettyJSON(code int, data interface{}) (err error)

PrettyJSON serializes the given struct as pretty JSON (indented) into the response body. It also sets the Content-Type as "application/json". WARNING: we recommend to use this only for development purposes since printing pretty JSON is more CPU and bandwidth consuming. Use Ctx.JSON() instead.

func (*Ctx) PrettyJSONTo

func (this *Ctx) PrettyJSONTo(w io.Writer, code int, data interface{}) (err error)

PrettyJSONTo serializes the given struct as pretty JSON (indented) into the io.Writers. It also sets the Content-Type as "application/json". WARNING: we recommend to use this only for development purposes since printing pretty JSON is more CPU and bandwidth consuming. Use Ctx.JSON() instead.

func (*Ctx) Redirect

func (this *Ctx) Redirect(url string) (val string)

Redirect redirects to the url, using http location header, and sets http code 302

func (*Ctx) RemoteAddr

func (this *Ctx) RemoteAddr() string

func (*Ctx) Request

func (this *Ctx) Request() *http.Request

func (*Ctx) RequestBody

func (this *Ctx) RequestBody() ([]byte, error)

RequestBody returns raw request body data.

func (*Ctx) Response

func (this *Ctx) Response() http.ResponseWriter

func (*Ctx) SaveUploadedFile

func (this *Ctx) SaveUploadedFile(file *multipart.FileHeader, dst string) error

SaveUploadedFile uploads the form file to specific dst.

func (*Ctx) Set

func (this *Ctx) Set(key interface{}, value interface{})

Set is used to store a new key/value pair exclusively for this context. It also lazy initializes c.Keys if it was not used previously.

func (*Ctx) SetAPIServer

func (this *Ctx) SetAPIServer(apiServer gcore.APIServer)

func (*Ctx) SetApp

func (this *Ctx) SetApp(app gcore.App)

func (*Ctx) SetConfig

func (this *Ctx) SetConfig(config gcore.Config)

func (*Ctx) SetConn

func (this *Ctx) SetConn(conn net.Conn)

func (*Ctx) SetController

func (this *Ctx) SetController(controller gcore.Controller)

func (*Ctx) SetControllerMethod

func (this *Ctx) SetControllerMethod(controllerMethod string)

func (*Ctx) SetCookie

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

SetCookie adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Ctx) SetHeader

func (this *Ctx) SetHeader(key, value string)

SetHeader is a intelligent shortcut for ctx.Response().Header().Set(key, value). It writes a header in the response. If value == "", this method removes the header `ctx.Response().Header().Del(key)`

func (*Ctx) SetI18n

func (this *Ctx) SetI18n(i18n gcore.I18n)

func (*Ctx) SetLocalAddr

func (this *Ctx) SetLocalAddr(localAddr string)

func (*Ctx) SetLogger

func (this *Ctx) SetLogger(logger gcore.Logger)

func (*Ctx) SetParam

func (this *Ctx) SetParam(param gcore.Params)

func (*Ctx) SetRemoteAddr

func (this *Ctx) SetRemoteAddr(remoteAddr string)

func (*Ctx) SetRequest

func (this *Ctx) SetRequest(request *http.Request)

func (*Ctx) SetResponse

func (this *Ctx) SetResponse(response http.ResponseWriter)

func (*Ctx) SetTemplate

func (this *Ctx) SetTemplate(template gcore.Template)

func (*Ctx) SetTimeUsed

func (this *Ctx) SetTimeUsed(t time.Duration)

SetTimeUsed sets the method cost time, only for middleware2 and middleware3, do not call this.

func (*Ctx) SetWebServer

func (this *Ctx) SetWebServer(webServer gcore.HTTPServer)

func (*Ctx) Status

func (this *Ctx) Status(code int)

Status sets the HTTP response code.

func (*Ctx) StatusCode

func (this *Ctx) StatusCode() int

StatusCode returns http code in response, if not set, default is 200.

func (*Ctx) Stop

func (this *Ctx) Stop(msg ...interface{})

Stop will exit controller method or api handle function at once.

func (*Ctx) StopJSON

func (this *Ctx) StopJSON(code int, msg interface{})

StopJSON will exit controller method or api handle function at once. And writes the status code and a JSON body. It also sets the Content-Type as "application/json".

func (*Ctx) Template

func (this *Ctx) Template() gcore.Template

func (*Ctx) TimeUsed

func (this *Ctx) TimeUsed() time.Duration

TimeUsed acquires the method cost time, only for middleware2 and middleware3.

func (*Ctx) WebServer

func (this *Ctx) WebServer() gcore.HTTPServer

func (*Ctx) Write

func (this *Ctx) Write(data ...interface{}) (n int, err error)

Write output data to response

func (*Ctx) WriteCount

func (this *Ctx) WriteCount() int64

WriteCount acquires outgoing bytes count by writer

func (*Ctx) WriteE

func (this *Ctx) WriteE(data ...interface{}) (n int, err error)

WriteE outputs data to response and sets http status code 500

func (*Ctx) WriteFile

func (this *Ctx) WriteFile(filepath string)

WriteFile writes the specified file into the body stream in an efficient way.

func (*Ctx) WriteFileAttachment

func (this *Ctx) WriteFileAttachment(filepath, filename string)

WriteFileAttachment writes the specified file into the body stream in an efficient way On the client side, the file will typically be downloaded with the given filename

func (*Ctx) WriteFileFromFS

func (this *Ctx) WriteFileFromFS(filepath string, fs http.FileSystem)

WriteFileFromFS writes the specified file from http.FileSystem into the body stream in an efficient way.

func (*Ctx) WriteHeader

func (this *Ctx) WriteHeader(statusCode int)

WriteHeader sets http code in response

func (*Ctx) WriteTo

func (this *Ctx) WriteTo(w io.Writer, data ...interface{}) (n int, err error)

WriteTo output data to io.writer

Jump to

Keyboard shortcuts

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