Skip to content

Instantly share code, notes, and snippets.

@thirdwheel
Created December 15, 2019 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thirdwheel/0b6cb216b1249facd87c39e43572fa89 to your computer and use it in GitHub Desktop.
Save thirdwheel/0b6cb216b1249facd87c39e43572fa89 to your computer and use it in GitHub Desktop.
GWT Sessions Package - new session for each request
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))
func indexofstring(slice []string, value string) int {
for p, v := range slice {
if v == value {
return p
}
}
return -1
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, "gosession")
if err != nil {
fmt.Fprintf(w, "{\"error\":-1,\"errorString\":\"%s\"}", err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
userid := []int{1000, 1001}
username := []string{"timblack@hisemail.com", "matildasurname85@hotmail.com"}
password := []string{"iC0Gods!", "password"}
userClass := []int{0, 1} // 0 = consultant, 1 = client
if indexofstring(username, r.FormValue("email")) == -1 {
fmt.Fprintf(w, "{\"error\":1}")
} else {
unameIndex := indexofstring(username, r.FormValue("email"))
session.Values["userid"] = userid[unameIndex]
if password[unameIndex] == r.FormValue("password") {
fmt.Fprintf(w, "{\"userclass\": %d,\"userid\": %d,\"isnew\":%t}",
userClass[unameIndex], session.Values["userid"], session.IsNew)
} else {
fmt.Fprintf(w, "{\"error\":1}")
}
}
err = session.Save(r, w)
if err != nil {
fmt.Fprintf(w, "{\"error\":-1,\"errorString\":\"%s\"}", err.Error())
return
}
}
func main() {
http.HandleFunc("/login", loginHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment