Last active
April 24, 2017 12:05
-
-
Save saj1th/666cd86f366252921330645b48516f3d to your computer and use it in GitHub Desktop.
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
func (e Events) Track(w http.ResponseWriter, r *http.Request) { | |
start := time.Now() | |
var nuid, event string | |
// reads the cookie value from request - (function from go standard lib - no backend op here) | |
nuidCookie, err := r.Cookie(CookieName) | |
if err != nil { | |
//setting var | |
nuid = uuid.New() | |
} else { | |
//setting var | |
nuid = nuidCookie.Value | |
} | |
// reads the content from request - (function from go standard lib) | |
eventB, err := ioutil.ReadAll(r.Body) | |
if err != nil { | |
// edge case - writes error doesn't track metrics | |
e.log.Error("cant read request body", zap.String("message", err.Error())) | |
w.Header().Set("Content-Type", "application/json") | |
w.WriteHeader(http.StatusBadRequest) | |
_, err = w.Write([]byte(`{\n"error_status":"failed",\n"error_message":"Invalid json"\n}`)) | |
if nil != err { | |
e.log.Error("failed to write response", zap.String("message", err.Error())) | |
} | |
return | |
} | |
event = string(eventB) | |
//setting var | |
nuidC := http.Cookie{ | |
Name: CookieName, | |
Value: nuid, | |
Expires: time.Now().Add(time.Minute * time.Duration(e.conf.NIDExpiry)), | |
Domain: e.conf.DomainName, | |
} | |
// adds a Set-Cookie header - no back-end here | |
http.SetCookie(w, &nuidC) | |
tm := time.Now().UTC().Format(TIME_FORMAT) | |
// extracts ip from request | |
ip := getIP(r) | |
//stdlib op - no backend | |
data := fmt.Sprintf(EventStructure, KeyData, event, CookieName, nuid, KeyRecTime, tm, KeyIP, ip) | |
// puts data to kinesis | |
_, err = e.stream.PutRecord([]byte(data)) | |
if err != nil { | |
e.log.Error(err.Error()) | |
w.WriteHeader(http.StatusInternalServerError) | |
w.Header().Set("Access-Control-Allow-Origin", "*") | |
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") | |
w.Header().Set("Content-Type", "text/plain") | |
return | |
} | |
// writes response back ( stdlib op ) | |
w.WriteHeader(http.StatusOK) | |
w.Header().Set("Access-Control-Allow-Origin", "*") | |
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") | |
w.Header().Set("Content-Type", "text/plain") | |
io.WriteString(w, Out) | |
metrics.AddCounter("events") | |
metrics.UpdateTimerSince("events.latency", start) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment