Skip to content

[BUG]Iris v12.2.5 初始化实例在处理请求时都使用的不是同一个控制器实例? #2492

Description

@feikeq

我在使用go语言的 Iris v12.2.5 框架做项目,为什么当访问 192.168.172.88:8080/contact 时初始化变量UID被清空了?
我的main.go代码如下:

package main

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

func main() {
	app := iris.Default()
	userID := 123456

	contactController := NewContactController(int64(userID))
	mvc.New(app.Party("/contact")).Handle(contactController)
	println("main() UID:", contactController.UID)

	app.Run(iris.Addr(":8080"))
}

type ContactController struct {
	// 在 Iris 框架中,控制器的 iris.Context 字段会被自动注入为控制器方法的参数。
	// 如果在控制器结构体中定义了名为 CTX 的 iris.Context 字段,Iris 框架会自动将上下文对象赋值给该字段。
	CTX iris.Context // CTX iris.Context 是控制器中的一个字段,它不需要初始化。当您在处理请求时,Iris框架会自动将当前请求的上下文信息填充到这个字段中。
	// 访问控制器的字段 Context (不需要手动绑定)如 Ctx iris.Context 或者当作方法参数输入,如 func(ctx iris.Context, otherArguments...)。

	// context is auto-binded if struct depends on this(如果struct依赖于此,则上下文会自动绑定),
	// in this controller we don't we do everything with mvc-style(在这个控制器中,我们不是用mvc风格做所有事情),
	// and that's neither the 30% of its features.(这也不是它30%的功能)
	// Ctx iris.Context

	// the whole controller is request-scoped because we already depend on Session, so
	// this will be new for each new incoming request, BeginRequest sets that based on the session.
	UID int64
}

func NewContactController(userID int64) *ContactController {

	// 返回一个结构体指针
	return &ContactController{
		UID: userID,
	}
}

// 联系人列表 GET:/contact/
func (c *ContactController) Get() {

	println("get() UID:", c.UID)

	ctx := c.CTX //ctx iris.Context

	println("---------------------------------------------------------")
	println(ctx.GetCurrentRoute().MainHandlerName() + " [" + ctx.GetCurrentRoute().Path() + "] " + ctx.Method())
	println("---------------------------------------------------------")

	ctx.JSON(iris.Map{"data": c.UID, "code": 0, "msg": ""})
}


12.2.4 get() UID: 123456
12.2.5 get() UID: 0
请帮我找出问题到底在哪?为什么 Iris 12.2.4 就不会有问题UID都有值,而到 12.2.5 版本下 ContactController 的UID就空值了 ?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions