Last active
April 20, 2017 17:40
-
-
Save wwwbruno/572ef639bab7664a2d6cdb6ccd083376 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" | |
"io" | |
"math/rand" | |
"net" | |
"net/http" | |
) | |
func sortVariation() string { | |
variations := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"} | |
n := rand.Int() % len(variations) | |
return variations[n] | |
} | |
func userVariation(w http.ResponseWriter, r *http.Request) string { | |
var variation string | |
cookie, _ := r.Cookie("variation") | |
if cookie != nil { | |
variation = fmt.Sprintf("%s", cookie.Value) | |
} else { | |
cleanHost, _, _ := net.SplitHostPort(r.Host) | |
path := r.URL.Path | |
variation = sortVariation() | |
cookie := http.Cookie{Name: "variation", Value: variation, Domain: cleanHost, Path: path} | |
http.SetCookie(w, &cookie) | |
} | |
return variation | |
} | |
func renderView(w http.ResponseWriter, r *http.Request) { | |
variation := userVariation(w, r) | |
io.WriteString(w, fmt.Sprintf("Hello world %s!", variation)) | |
} | |
func main() { | |
http.HandleFunc("/", renderView) | |
http.ListenAndServe(":8000", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment