Created
December 15, 2019 08:28
-
-
Save thirdwheel/0b6cb216b1249facd87c39e43572fa89 to your computer and use it in GitHub Desktop.
GWT Sessions Package - new session for each request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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{"[email protected]", "[email protected]"} | |
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