cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Wrapper function in golang for custom event solution

vivekdesai13
Newcomer

package main

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)

// Define the structure of your custom event
type CustomEvent struct {
SpecVersion string `json:"specversion"`
ID string `json:"id"`
Source string `json:"source"`
Type string `json:"type"`
DataContentType string `json:"datacontenttype"`
Data map[string]string `json:"data"`
}

func main() {
// Retrieve environment variables
environmentID := os.Getenv("DT_TENANT")
apiToken := os.Getenv("DT_API_TOKEN")

if environmentID == "" || apiToken == "" {
fmt.Println("DT_TENANT or DT_API_TOKEN environment variable not set")
return
}

// Define the URL
url := fmt.Sprintf("https://{environmentid}.live.dynatrace.com/api/v2/bizevents/ingest", environmentID)

// Create the event data
event := CustomEvent{
SpecVersion: "1.0",
ID: "unique-event-id", // Replace with a unique ID for each event
Source: "your-source",
Type: "your-event-type",
DataContentType: "application/json",
Data: map[string]string{
"key1": "value1",
"key2": "value2",
},
}

// Convert the event to JSON
jsonData, err := json.Marshal(event)
if err != nil {
fmt.Println("Error marshalling JSON:", err)
return
}

// Create the HTTP request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Println("Error creating HTTP request:", err)
return
}

// Set the headers
req.Header.Set("Content-Type", "application/cloudevent+json")
req.Header.Set("Authorization", "Api-Token "+apiToken)

// Send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()

// Check the response
if resp.StatusCode == http.StatusAccepted {
fmt.Println("Event sent successfully")
} else {
fmt.Printf("Failed to send event. Status code: %d\n", resp.StatusCode)
}
}

0 REPLIES 0

Featured Posts