Developers can customize some variables in the request, with custom variables having the highest priority, able to override the originally submitted client parameters.

    Request - Custom Parameters - 图1tip

    Custom variables can often be used for variable sharing throughout the request process, but it is important to note that these variables become part of the request parameters and are publicly exposed to the execution flow of the business.

    Method list:

    1. func (r *Request) SetParam(key string, value interface{})
    2. func (r *Request) GetParam(key string, def ...interface{}) interface{}
    3. func (r *Request) GetParamVar(key string, def ...interface{}) *gvar.Var

    Custom variables can be set using the SetParam method. Retrieving custom variables can be done through request parameter retrieval methods, such as Get/GetVar/GetMap, etc., or through specific custom variable methods GetParam/GetParamVar.

    Usage example:

    1. package main
    2. import (
    3. "github.com/gogf/gf/v2/frame/g"
    4. "github.com/gogf/gf/v2/net/ghttp"
    5. )
    6. // Pre-middleware 1
    7. func MiddlewareBefore1(r *ghttp.Request) {
    8. r.SetParam("name", "GoFrame")
    9. r.Response.Writeln("set name")
    10. r.Middleware.Next()
    11. }
    12. // Pre-middleware 2
    13. func MiddlewareBefore2(r *ghttp.Request) {
    14. r.SetParam("site", "https://goframe.org")
    15. r.Response.Writeln("set site")
    16. r.Middleware.Next()
    17. }
    18. func main() {
    19. s := g.Server()
    20. s.Group("/", func(group *ghttp.RouterGroup) {
    21. group.Middleware(MiddlewareBefore1, MiddlewareBefore2)
    22. group.ALL("/", func(r *ghttp.Request) {
    23. r.Response.Writefln(
    24. "%s: %s",
    25. r.GetParam("name").String(),
    26. r.GetParam("site").String(),
    27. )
    28. })
    29. })
    30. s.SetPort(8199)
    31. s.Run()
    32. }

    As you can see, we can use SetParam and GetParam to set and retrieve custom variables, with the variable’s lifecycle being limited to the current request process.

    After execution, visit http://127.0.0.1:8199/, and the page output content is:

    1. set name
    2. set site
    3. GoFrame: https://goframe.org