Example #1
0
// InstantiateApp wraps HTTP handlers that return the base HTML page for the
// application named by app (e.g., "web" or "chrome-extension").
func InstantiateApp(app string, h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Set the ClientID cookie if it doesn't already exist.
		clientID, err := GetClientID(r)
		if err != nil {
			log.Printf("GetClientID failed: %s", err)
			deleteClientIDCookie(w)
			goto handle
		}
		if clientID == 0 {
			clientID, err = nextClientID()
			if err != nil {
				log.Printf("nextClientID failed: %s", err)
				goto handle
			}

			c, err := newClientIDCookie(clientID)
			if err != nil {
				log.Printf("newClientIDCookie failed: %s", err)
				goto handle
			}

			setClientID(r, clientID)
			http.SetCookie(w, (*http.Cookie)(c))
		}

		if getInstance(r, false) == 0 {
			// Create a new instance.
			instance := &Instance{
				ClientID:    clientID,
				App:         app,
				URL:         r.URL.String(),
				ReferrerURL: r.Referer(),
				ClientInfo:  ClientInfo{IPAddress: removePort(ClientIPAddress(r)), UserAgent: r.UserAgent()},
				Start:       time.Now(),
			}

			// Look up the current user, if any.
			if CurrentUser != nil {
				user, err := CurrentUser(r)
				if err != nil {
					log.Printf("CurrentUser failed: %s", err)
					goto handle
				}
				instance.User = nnz.String(user)
			}

			err = InsertInstance(instance)
			if err != nil {
				log.Printf("InsertInstance failed: %s", err)
				goto handle
			}
			setInstance(r, instance.ID)
		}

	handle:
		h.ServeHTTP(w, r)
	})
}
Example #2
0
func AfterAPICall(r *http.Request, bodyLength, code int, errStr string) {
	callID, ok := GetCallID(r)
	if !ok {
		log.Printf("AfterAPICall: no CallID")
		return
	}

	err := setCallStatus(callID, &CallStatus{
		End:            now(),
		BodyLength:     bodyLength,
		HTTPStatusCode: code,
		Err:            nnz.String(errStr),
	})
	if err != nil {
		log.Printf("setCallStatus failed for call ID %d: %s", callID, err)
	}
}