package main
import (
“net/http”
“github.com/satori/go.uuid”
“html/template”
“fmt”
)
type user struct{
Email string
First string
Last string
}
var tpl *template.Template
var dbSessions = map[string]string{} // dbSessions is associated with a session id and an Email
var dbUsers = map[string]user{} // dbUsers is associated with a Email and a user’s info
func init(){
tpl = template.Must(template.ParseGlob(“templates/*.gohtml”))
}
func main(){
http.HandleFunc("/", index)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.ListenAndServe(":8080", nil)
}
func index (w http.ResponseWriter, req *http.Request){
//LOOK FOR A COOKIE, IF THERE IS NOT ONE ALREADY THERE,
//CREATE A COOKIE
cookie, err := req.Cookie("session")
if err != nil{
id, _ := uuid.NewV4()
cookie := &http.Cookie{
Name: "session",
Value: id.String(),
HttpOnly: true,
Path: "/",
}
http.SetCookie(w, cookie)
}
//CREATE A USER VARIABLE
var u user
//CHECK IF THE SESSION ID (OUR COOKIE'S VALUE) IS ALREADY ASSOCIATED WITH AN EMAIL
//IF THE EMAIL DOES IN FACT ALREADY EXIST
//WE PULL OUT THE USER'S INFORMATION
if thisVariableCouldBeAnything, ok := dbSessions[cookie.Value]; ok{
u = dbUsers[thisVariableCouldBeAnything]
}
//PROCESS THE FORM SUBMISSION AND CREATE A USER WITH OUR FORM VARIABLES
//MAKE THE SESSION ID ASSOCIATED WITH THIS EMAIL
//MAKE THE EMAIL ASSOCIATED WITH THIS USER
if req.Method == http.MethodPost{
e := req.FormValue("email")
f := req.FormValue("first")
l := req.FormValue("last")
u = user{e, f, l }
dbSessions[cookie.Value] = e
dbUsers[e] = u
}
//EXECUTE OUR TEMPLATE WITH THE USER AS OUR DATA
tpl.ExecuteTemplate(w, "index.gohtml", u)
fmt.Println(u)
}