-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsendmoesif.go
94 lines (81 loc) · 2.56 KB
/
sendmoesif.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package moesifmiddleware
import (
"log"
"math/rand"
"net/http"
"strconv"
"time"
"github.com/moesif/moesifapi-go/models"
)
// Send Event to Moesif
func sendMoesifAsync(request *http.Request, reqTime time.Time, reqHeader map[string]interface{}, apiVersion *string, reqBody interface{}, reqEncoding *string, reqContentLength *int64,
rspTime time.Time, respStatus int, respHeader map[string]interface{}, respBody interface{}, respEncoding *string, respContentLength *int64,
userId string, companyId string, sessionToken *string, metadata map[string]interface{},
direction *string) {
// Get Client Ip
ip := getClientIp(request)
uri := request.URL.Scheme + "://" + request.Host + request.URL.Path
if request.URL.RawQuery != "" {
uri += "?" + request.URL.RawQuery
}
// Prepare request model
event_request := models.EventRequestModel{
Time: &reqTime,
Uri: uri,
Verb: request.Method,
ApiVersion: apiVersion,
IpAddress: &ip,
Headers: reqHeader,
Body: &reqBody,
TransferEncoding: reqEncoding,
ContentLength: reqContentLength,
}
// Prepare response model
event_response := models.EventResponseModel{
Time: &rspTime,
Status: respStatus,
IpAddress: nil,
Headers: respHeader,
Body: respBody,
TransferEncoding: respEncoding,
ContentLength: respContentLength,
}
// Generate random percentage
rand.Seed(time.Now().UnixNano())
randomPercentage := rand.Intn(100)
// Parse sampling percentage based on user/company
samplingPercentage := getSamplingPercentage(userId, companyId)
if samplingPercentage > randomPercentage {
// Add Weight to the Event Model
var eventWeight int
if samplingPercentage == 0 {
eventWeight = 1
} else {
eventWeight = 100 / samplingPercentage
}
// Prepare the event model
event := models.EventModel{
Request: event_request,
Response: event_response,
SessionToken: sessionToken,
Tags: nil,
UserId: &userId,
CompanyId: &companyId,
Metadata: metadata,
Direction: direction,
Weight: &eventWeight,
}
errSendEvent := apiClient.QueueEvent(&event)
if errSendEvent != nil {
log.Fatalf("Error while adding event to Moesif: %s.\n", errSendEvent.Error())
} else {
if debug {
log.Println("Event successfully added to the queue")
}
}
} else {
if debug {
log.Println("Skipped Event due to sampling percentage: " + strconv.Itoa(samplingPercentage) + " and random percentage: " + strconv.Itoa(randomPercentage))
}
}
}