Created
May 3, 2012 15:07
-
-
Save jaybill/2586334 to your computer and use it in GitHub Desktop.
Type assertions on session values.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/gob" | |
"net/http" | |
"code.google.com/p/gorilla/sessions" | |
"log" | |
) | |
var store = sessions.NewCookieStore([]byte("something-very-secret")) | |
type IUser interface{ | |
GetUsername() string | |
} | |
type User struct{ | |
Id int64 | |
Username string | |
} | |
func (u *User) GetUsername() string{ | |
return u.Username | |
} | |
func FirstHandler(w http.ResponseWriter, r *http.Request) { | |
// Get a session. We're ignoring the error resulted from decoding an | |
// existing session: Get() always returns a session, even if empty. | |
session, _ := store.Get(r, "session-name") | |
// Set some session values. | |
user := User{Id: 3, Username: "someguy"} | |
session.Values["user"] = user | |
session.Values["foo"] = "bar" | |
session.Save(r, w) | |
} | |
func AnotherHandler(w http.ResponseWriter, r *http.Request) { | |
session, err := store.Get(r, "session-name") | |
if err != nil{ | |
log.Println(err) | |
} | |
su := session.Values["user"] | |
user := su.(IUser) | |
username := user.GetUsername() | |
log.Printf("Username is %v",username) | |
} | |
// Hitting localhost:8080/part1 sets the session values | |
// Hitting localhost:8080/part2 panics: | |
// "interface conversion: main.User is not main.IUser: missing method GetUsername" | |
func main(){ | |
gob.Register(User{}) | |
http.HandleFunc("/part1",FirstHandler) | |
http.HandleFunc("/part2",AnotherHandler) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment