在学着用golang开发一个简单的 MVC 结构时,IndexCtrl 继承了 Controller 之后,可以读取它的 Request 和 ResponseWriter 属性值,可是当有另一个请求的时候,上一个请求如果没处理完,这两个属性值也变成新的了。
请问下面这段代码要怎么改才可以在 IndexCtrl 的 GET() 执行时,得到的 Controller 的那两个属性值都是独立的?
func main() {
var app App
app.GET("/", new(IndexCtrl))
app.Run(":8100")
}
//自定义控制器
type IndexCtrl struct {
Controller
}
func (c *IndexCtrl) GET() {
fmt.Println("index")
}
var Routers []Router
type App struct{}
type Router struct {
path string
ctrl ControllerInterface
}
func (app *App) GET(path string, ctrl ControllerInterface) {
r := Router{
path: path,
ctrl: ctrl,
}
Routers = append(Routers, r)
}
func (app *App) Run(addr string) {
fmt.Println("Listen at " + addr)
http.ListenAndServe(addr, app)
}
func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Println("假设匹配到第1条路由规则")
Routers[0].ctrl.Init(w, r)
Routers[0].ctrl.GET()
//c.Init(w, r)
for {
fmt.Println(Routers[0].ctrl)
//就在这个地方出了问题,Routers[0].ctrl 中的w和r值总是会被最新请求的w,r值给替换
time.Sleep(time.Second * 2)
}
}
type Controller struct {
ResponseWriter http.ResponseWriter
Request *http.Request
}
type ControllerInterface interface {
GET()
Init(w http.ResponseWriter, r *http.Request)
}
func (c *Controller) Init(w http.ResponseWriter, r *http.Request) {
fmt.Println(c)
c.ResponseWriter = w
c.Request = r
}
func (c *Controller) GET() {
fmt.Println("基类的GET")
}