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

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
主站蜘蛛池模板: 将乐县| 内黄县| 神农架林区| 卓尼县| 海晏县| 兴义市| 灵川县| 依兰县| 策勒县| 县级市| 咸宁市| 临猗县| 资阳市| 铁岭市| 万山特区| 鹤峰县| 子长县| 婺源县| 北安市| 宣恩县| 蓝田县| 当涂县| 确山县| 岳池县| 北川| 青冈县| 韶关市| 日喀则市| 齐齐哈尔市| 金寨县| 荔浦县| 项城市| 芦山县| 喀喇沁旗| 金湖县| 榆树市| 临猗县| 临城县| 七台河市| 时尚| 静海县|