Saturday 31 October 2020

go web app 14 session cookies

 
log in as bob with chrome browser
user name is encrypted and stored in browser cookies

cookie is loaded and decrypted


open the same page with firefox browser, cookie is not found cause cookie is stored on chrome

//cmd - install session
C:\Users\bob\golang1>go get github.com/gorilla/sessions

//tutorial.go
package main

import (
"html/template"
"net/http"

"github.com/gorilla/mux"
"github.com/gorilla/sessions"
)

type car struct {
Color   string
Mileage int
Model   string
}

var templates *template.Template
var store = sessions.NewCookieStore([]byte("secret"))

var truck = car{
Color:   "black",
Mileage: 12345,
Model:   "F-150",
}

var sedan = car{
Color:   "white",
Mileage: 321,
Model:   "Corolla",
}

func indexGetHandler(w http.ResponseWriter, r *http.Request) {
templates.ExecuteTemplate(w, "index.html", []car{truck, sedan})
}

func loginGetHandler(w http.ResponseWriter, r *http.Request) {
templates.ExecuteTemplate(w, "login.html", nil)
}

func loginPostHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username := r.PostForm.Get("username")
session, _ := store.Get(r, "session")
session.Values["username"] = username
session.Save(r, w)
}

func testGetHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session")
untyped, ok := session.Values["username"]
if !ok {
return
}
cookie, ok := untyped.(string)
if !ok {
return
}
w.Write([]byte(cookie))
}

func main() {
templates = template.Must(template.ParseGlob("templates/*.html"))
r := mux.NewRouter()
r.HandleFunc("/", indexGetHandler).Methods("GET")
//r.HandleFunc("/", indexPostHandler).Methods("POST")
r.HandleFunc("/login", loginGetHandler).Methods("GET")
r.HandleFunc("/login", loginPostHandler).Methods("POST")
r.HandleFunc("/test", testGetHandler).Methods("GET")
fs := http.FileServer(http.Dir("./static/"))
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
http.Handle("/", r)
http.ListenAndServe(":8000", nil)
}

---------------------
//login.html
<html>

<head>
    <title>Login</title>
</head>

<body>
    <form method="POST">
        Username: <input name="username">
        <div>
            <button type="submit">Login</button>
        </div>
    </form>
</body>

</html>

reference:

No comments:

Post a Comment