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

How to do it…

  1. Install the github.com/gorilla/sessions package using the go get command, as follows:
$ go get github.com/gorilla/sessions
  1. Create http-session.go where we will create a Gorilla cookie store to save and retrieve session information defining three handlers—/login, /home, and /logout—where we will be creating a valid session cookie, writing a response to an HTTP response stream, and invalidating a session cookie respectively, as follows:
package main
import
(
"fmt"
"log"
"net/http"
"github.com/gorilla/sessions"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
var store *sessions.CookieStore
func init()
{
store = sessions.NewCookieStore([]byte("secret-key"))
}
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
session.Save(r, w)
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)
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}
  1. Run the program with the following command:
$ go run http-session.go
主站蜘蛛池模板: 亳州市| 武安市| 旌德县| 鄯善县| 陆良县| 正宁县| 新干县| 乌鲁木齐县| 寻乌县| 兴文县| 神木县| 若羌县| 都匀市| 巴中市| 介休市| 米泉市| 友谊县| 浦县| 方正县| 青龙| 得荣县| 平遥县| 逊克县| 蓝山县| 桂平市| 新平| 泸定县| 独山县| 会昌县| 社会| 曲靖市| 巴彦县| 日土县| 微博| 海林市| 朝阳区| 沾化县| 桦南县| 轮台县| 晋城| 温州市|