Mirror

Volodymyr Tkach 50cdd1fbc8 Update LICENSE 2 years ago
.github b633027fa2 Create go.yml 2 years ago
session 90ba9f233b Move time to constant, code comments 2 years ago
tmp ff59f89f6a Initial commit 6 years ago
.gitignore ff59f89f6a Initial commit 6 years ago
LICENSE 50cdd1fbc8 Update LICENSE 2 years ago
Makefile d2649d56f3 Update Makefile 2 years ago
README.md 348de02780 Return error on init 2 years ago
go.mod a67c1cdf25 go 1.18 2 years ago
main.go 348de02780 Return error on init 2 years ago

README.md

golang-server-sessions

Sessions for http server based on files and cookies

How to use

go get github.com/vladimirok5959/golang-server-sessions
package main

import (
	"fmt"
	"net/http"

	"github.com/vladimirok5959/golang-server-sessions/session"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// Create new or load saved session
		var sess *session.Session
		var err error
		sess, err = session.New(w, r, "./tmp")
		if err != nil {
			fmt.Printf("%s\n", err.Error())
		}
		defer sess.Close()

		if r.URL.Path == "/" {
			var counter int

			// Get value or set default
			if sess.IsSetInt("counter") {
				counter = sess.GetInt("counter", 0)
			} else {
				counter = 0
			}

			// Increment value
			counter++

			// Update
			sess.SetInt("counter", counter)

			w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
			w.Header().Set("Content-Type", "text/html")
			if _, err := w.Write([]byte(`
				<div>Hello World!</div>
				<div>Counter: ` + fmt.Sprintf("%d", counter) + `</div>
			`)); err != nil {
				fmt.Printf("%s\n", err.Error())
			}
		} else {
			w.WriteHeader(http.StatusNotFound)
			if _, err := w.Write([]byte(`<div>Error 404!</div>`)); err != nil {
				fmt.Printf("%s\n", err.Error())
			}
		}
	})

	// Delete expired session files
	if err := session.Clean("./tmp"); err != nil {
		fmt.Printf("%s\n", err.Error())
	}

	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Printf("%s\n", err.Error())
	}
}