K
K
Kagtaviy2016-04-25 19:02:24
go
Kagtaviy, 2016-04-25 19:02:24

How to properly declare a variable so that all functions have access to it?

hello there is a function

func checksession() {
  session, err := store.Get(r, "infoUs")
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
  }
}

Then I want to operate on session
func RenderMainAdmin(w http.ResponseWriter, r *http.Request) {
  id := session.Values["id"]
  if id == nil {
    fmt.Println("Nil")
    http.Redirect(w, r, "/, http.StatusSeeOther)
    return
  } else {
                 fmt.Println("Id", id)
         }
}

But it doesn't work the way you want to create a global variable.
The question is how to correctly declare a session so that all functions have access to it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2016-04-25
@Kagtaviy

var session *sessions.Session
/*-------------------------------------------------------*/
func checksession() {
    var err error
    session, err = store.Get(r, "infoUs")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question