post image January 6, 2022 | 2 min Read

Go sessions

package main

import (
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"

	uuid "github.com/satori/go.uuid"
)

type user struct {
	UserName string
	First    string
	Last     string
}

type session map[string]string

var tpl *template.Template
var dbUsers = map[string]user{}
var dbSessions = map[string]session{}

func init() {
	tpl = template.Must(template.ParseFiles("index.gohtml"))
}

func main() {
	http.HandleFunc("/", index)
	// http.HandleFunc("/bar", bar)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	log.Fatalln(http.ListenAndServe(":8080", nil))

}

func index(w http.ResponseWriter, r *http.Request) {
	c, err := r.Cookie("session")
	if err != nil {
		sID, _ := uuid.NewV4()

		c := &http.Cookie{
			Name:  "session",
			Value: sID.String(),
		}
		http.SetCookie(w, c)
	}

	var u user

	if r.Method == http.MethodPost {
		un := r.FormValue("username")
		f := r.FormValue("firstname")
		l := r.FormValue("lastname")

		// {
		// 	"123": {
		// 		"jano": {},
		// 		"vilko": {},
		//       "sasa": {}
		// 	},
		// }

		if _, ok := dbSessions[c.Value]; !ok {
			dbSessions[c.Value] = session{}
		} 



		if _, ok := dbSessions[c.Value][un]; ok {
			io.WriteString(w, `<p>User: ` + un + ` already registered</p>`)
			u = dbUsers[un]

		} else {
			u = user{
				UserName: un,
				First:    f,
				Last:     l,
			}
			
			tmp := dbSessions[c.Value]
			tmp[un] = ""
			dbSessions[c.Value] = tmp

			dbUsers[un] = u
		}

	}

	tpl.ExecuteTemplate(w, "index.gohtml", u)

	fmt.Printf("db sessions: %v\n", dbSessions)
	fmt.Printf("db users: %v\n", dbUsers)

}

// cat index.gohtml 
// <!doctype html>
// <html lang="en">
// <head>
//     <meta charset="UTF-8">
//     <title>Document</title>
// </head>
// <body>

// <form method="post">

//     <input type="email" name="username" placeholder="email"><br>
//     <input type="text" name="firstname" placeholder="first name"><br>
//     <input type="text" name="lastname" placeholder="last name"><br>
//     <input type="submit">

// </form>


// {{if .First}}
// USER NAME {{.UserName}}<br>
// FIRST {{.First}}<br>
// LAST {{.Last}}<br>
// {{end}}

// <br>
// <h2>Go to <a href="/bar">the bar</a></h2>
// </body>
// </html>

author image

Jan Toth

I have been in DevOps related jobs for past 6 years dealing mainly with Kubernetes in AWS and on-premise as well. I spent quite a lot …

comments powered by Disqus