The idea is simple: pass the session cookie from the old domain to the new one.
$ go run server.go
Go to http://session
and http://nosession
.
You will need to update your hosts (/etc/hosts
):
$ 127.0.0.1 session nosession
<!doctype html> | |
<html> | |
<head> | |
<title>This site has no session</title> | |
</head> | |
<body> | |
<p>Site without session (no cookies on this domain).</p> | |
<iframe id="session-keeper" src="http://session?query=string" seamless></iframe> | |
<script> | |
window.addEventListener('message', function(event) { | |
if (event.origin === 'http://session') { | |
console.log('Cookies: ', event.data); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
package main | |
import ( | |
"fmt" | |
"io" | |
"log" | |
"mime" | |
"net/http" | |
"os" | |
"strings" | |
) | |
func main() { | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", handler) | |
log.Fatal(http.ListenAndServe(":80", mux)) | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
host := strings.SplitN(r.Host, ":", 2)[0] | |
file := host + ".html" | |
if host == "session" { | |
cookie := http.Cookie{ | |
Name: "session", | |
Value: "MySession", | |
} | |
http.SetCookie(w, &cookie) | |
} | |
f, err := os.Open(file) | |
if err != nil { | |
w.WriteHeader(404) | |
fmt.Fprintf(w, "Not Found: %q", file) | |
return | |
} | |
defer f.Close() | |
w.Header().Add("Content-Type", mime.TypeByExtension("html")) | |
io.Copy(w, f) | |
} |
<!doctype html> | |
<html> | |
<head> | |
<title>This site has a session</title> | |
</head> | |
<body> | |
<p>Site with a session.</p> | |
<script> | |
function isInIframe() { | |
try { | |
return window.self !== window.top; | |
} catch (e) { | |
return true; | |
} | |
} | |
if (isInIframe()) { | |
window.parent.postMessage(document.cookie, 'http://nosession'); | |
} | |
</script> | |
</body> | |
</html> |