官术网_书友最值得收藏!

How to do it…

  1. Install  gopkg.in/boj/redistore.v1 and github.com/gorilla/sessions using the go get command, as follows:
$ go get gopkg.in/boj/redistore.v1
$ go get github.com/gorilla/sessions
  1. Create http-session-redis.go, where we will create a RedisStore to store and retrieve session variables, as follows:
package main
import
(
"fmt"
"log"
"net/http"
"github.com/gorilla/sessions"
redisStore "gopkg.in/boj/redistore.v1"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
var store *redisStore.RediStore
var err error
func init()
{
store, err = redisStore.NewRediStore(10, "tcp", ":6379", "",
[]byte("secret-key"))
if err != nil
{
log.Fatal("error getting redis store : ", err)
}
}
func home(w http.ResponseWriter, r *http.Request)
{
session, _ := store.Get(r, "session-name")
var authenticated interface{} = session.Values["authenticated"]
if authenticated != nil
{
isAuthenticated := session.Values["authenticated"].(bool)
if !isAuthenticated
{
http.Error(w, "You are unauthorized to view the page",
http.StatusForbidden)
return
}
fmt.Fprintln(w, "Home Page")
}
else
{
http.Error(w, "You are unauthorized to view the page",
http.StatusForbidden)
return
}
}
func login(w http.ResponseWriter, r *http.Request)
{
session, _ := store.Get(r, "session-name")
session.Values["authenticated"] = true
if err = sessions.Save(r, w); err != nil
{
log.Fatalf("Error saving session: %v", err)
}
fmt.Fprintln(w, "You have successfully logged in.")
}
func logout(w http.ResponseWriter, r *http.Request)
{
session, _ := store.Get(r, "session-name")
session.Values["authenticated"] = false
session.Save(r, w)
fmt.Fprintln(w, "You have successfully logged out.")
}
func main()
{
http.HandleFunc("/home", home)
http.HandleFunc("/login", login)
http.HandleFunc("/logout", logout)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
defer store.Close()
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}
  1. Run the program with the following command:
$ go run http-session-redis.go
主站蜘蛛池模板: 红安县| 武隆县| 彭山县| 五大连池市| 马关县| 林甸县| 湘阴县| 大邑县| 营口市| 志丹县| 鲁山县| 庄浪县| 修文县| 丰顺县| 绥棱县| 濮阳市| 北海市| 绥棱县| 大英县| 桓台县| 湖北省| 梅州市| 厦门市| 怀宁县| 海盐县| 临泉县| 大石桥市| 化德县| 盱眙县| 四平市| 隆化县| 和静县| 江安县| 沁源县| 铁岭县| 丰都县| 晋中市| 威海市| 巴马| 新龙县| 扶余县|