github.com/wtfutil/wtf@v0.43.0/modules/opsgenie/client.go (about) 1 package opsgenie 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "net/http" 7 ) 8 9 type OnCallResponse struct { 10 OnCallData OnCallData `json:"data"` 11 Message string `json:"message"` 12 RequestID string `json:"requestId"` 13 Took float32 `json:"took"` 14 } 15 16 type OnCallData struct { 17 Recipients []string `json:"onCallRecipients"` 18 Parent Parent `json:"_parent"` 19 } 20 21 type Parent struct { 22 ID string `json:"id"` 23 Name string `json:"name"` 24 Enabled bool `json:"enabled"` 25 } 26 27 var opsGenieAPIUrl = map[string]string{ 28 "us": "https://api.opsgenie.com", 29 "eu": "https://api.eu.opsgenie.com", 30 } 31 32 /* -------------------- Exported Functions -------------------- */ 33 34 func (widget *Widget) Fetch(scheduleIdentifierType string, schedules []string) ([]*OnCallResponse, error) { 35 agregatedResponses := []*OnCallResponse{} 36 37 if regionURL, regionErr := opsGenieAPIUrl[widget.settings.region]; regionErr { 38 for _, sched := range schedules { 39 scheduleURL := fmt.Sprintf("%s/v2/schedules/%s/on-calls?scheduleIdentifierType=%s&flat=true", regionURL, sched, scheduleIdentifierType) 40 response, err := opsGenieRequest(scheduleURL, widget.settings.apiKey) 41 agregatedResponses = append(agregatedResponses, response) 42 if err != nil { 43 return nil, err 44 } 45 } 46 return agregatedResponses, nil 47 } else { 48 return nil, fmt.Errorf("you specified wrong region. Possible options are only 'us' and 'eu'") 49 } 50 } 51 52 /* -------------------- Unexported Functions -------------------- */ 53 54 func opsGenieRequest(url string, apiKey string) (*OnCallResponse, error) { 55 req, err := http.NewRequest("GET", url, http.NoBody) 56 if err != nil { 57 return nil, err 58 } 59 60 req.Header.Set("Authorization", fmt.Sprintf("GenieKey %s", apiKey)) 61 62 client := &http.Client{} 63 64 resp, err := client.Do(req) 65 if err != nil { 66 return nil, err 67 } 68 defer func() { _ = resp.Body.Close() }() 69 70 response := &OnCallResponse{} 71 if err := json.NewDecoder(resp.Body).Decode(response); err != nil { 72 return nil, err 73 } 74 75 return response, nil 76 }