Created
May 19, 2018 16:13
-
-
Save aeneasr/a25ac48c7283dad0b598adef437ca902 to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"net/http/cookiejar" | |
"os" | |
"time" | |
"github.com/gorilla/mux" | |
"github.com/gorilla/sessions" | |
) | |
func setCookie(rw http.ResponseWriter, r *http.Request) { | |
cs := sessions.NewCookieStore([]byte("asdf")) | |
cook, _ := cs.Get(r, "foocookie") | |
cook.Values["foo"] = "bar" | |
if err := cook.Save(r, rw); err != nil { | |
http.Error(rw, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
http.Redirect(rw, r, "http://127.0.0.1:9431/redirect", 302) | |
} | |
func checkCookie(rw http.ResponseWriter, r *http.Request) { | |
cs := sessions.NewCookieStore([]byte("asdf")) | |
cook, err := cs.Get(r, "foocookie") | |
if err != nil { | |
http.Error(rw, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
if cook.Values["foo"] != "bar" { | |
http.Error(rw, "foo is not bar", http.StatusInternalServerError) | |
return | |
} | |
rw.Write([]byte("ok")) | |
} | |
func main() { | |
go func() { | |
time.Sleep(time.Second * 5) | |
fmt.Println("all good pal 1") | |
cj, err := cookiejar.New(&cookiejar.Options{}) | |
if err != nil { | |
log.Fatal(err.Error()) | |
} | |
client := http.Client{ | |
Jar: cj, | |
} | |
fmt.Println("all good pal 2") | |
resp, err := client.Get("http://127.0.0.1:9430/set") | |
if err != nil { | |
log.Fatal(err.Error()) | |
} | |
if resp.StatusCode != 200 { | |
log.Fatal("not 200 ok") | |
} | |
fmt.Println("all good pal") | |
os.Exit(0) | |
}() | |
go func() { | |
log.Fatal(http.ListenAndServe(":9431", http.HandlerFunc( | |
func(rw http.ResponseWriter, r *http.Request) { | |
http.Redirect(rw, r, "http://localhost:9430/check", 302) | |
}, | |
))) | |
}() | |
router := mux.NewRouter() | |
router.HandleFunc("/set", setCookie) | |
router.HandleFunc("/check", checkCookie) | |
log.Fatal(http.ListenAndServe(":9430", router)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment