gocraft / web

Go Router + Middleware. Your Contexts.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Accessing the Main Context From Subroute

samphomsopha opened this issue · comments

Hi,
How do I access the root context from my subroute? For example, if I have a Session defined in Context, how do I access from /admin/index?
Accessing "Session" causes a "runtime error: invalid memory address or nil pointer dereference"
See code below.

Context

type Context struct {
    Session map[string]string
}

type AdminContext struct {
    *Context
    CurrentAdmin *User
}

Route Handler

func (ac *AdminContext) Index(rw web.ResponseWriter, req *web.Request) {
    fmt.Println(ac.Session["key"]); //runtime error: invalid memory address or nil pointer dereference
}

Server.go

rootRouter := web.New(Context{})
adminRouter := rootRouter.Subrouter(AdminContext{}, "/admin")
adminRouter.Get("/reports", (*AdminContext).Index)
commented

My guess is that you are not initializing your Context object fully. gocraft/web should allocate an instance of AdminContext and assign the embedded pointer to reference an instance of Context if I recall correctly.

Try changing your route handler to something like

func (ac *AdminContext) Index(rw web.ResponseWriter, req *web.Request) {
    ac.Session = make(map[string]string)
    fmt.Println(ac.Session["key"]); //runtime error: invalid memory address or nil pointer dereference
}

Correct, you are accessing your root context just fine. The problem is you're not creating the map.