github.com/wtfutil/wtf@v0.43.0/modules/victorops/client.go (about) 1 package victorops 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "net/http" 7 "strings" 8 9 "github.com/wtfutil/wtf/logger" 10 ) 11 12 // Fetch gets the current oncall users 13 func Fetch(apiID, apiKey string) ([]OnCallTeam, error) { 14 scheduleURL := "https://api.victorops.com/api-public/v1/oncall/current" 15 response, err := victorOpsRequest(scheduleURL, apiID, apiKey) 16 17 return response, err 18 } 19 20 /* ---------------- Unexported Functions ---------------- */ 21 22 func victorOpsRequest(url string, apiID string, apiKey string) ([]OnCallTeam, error) { 23 req, err := http.NewRequest("GET", url, http.NoBody) 24 if err != nil { 25 logger.Log(fmt.Sprintf("Failed to initialize sessions to VictorOps. ERROR: %s", err)) 26 return nil, err 27 } 28 29 req.Header.Set("X-VO-Api-Id", apiID) 30 req.Header.Set("X-VO-Api-Key", apiKey) 31 client := &http.Client{} 32 33 resp, err := client.Do(req) 34 if err != nil { 35 logger.Log(fmt.Sprintf("Failed to make request to VictorOps. ERROR: %s", err)) 36 return nil, err 37 } 38 if resp.StatusCode != 200 { 39 return nil, fmt.Errorf("%s", resp.Status) 40 } 41 defer func() { _ = resp.Body.Close() }() 42 43 response := &OnCallResponse{} 44 if err := json.NewDecoder(resp.Body).Decode(response); err != nil { 45 logger.Log(fmt.Sprintf("Failed to decode JSON response. ERROR: %s", err)) 46 return nil, err 47 } 48 49 teams := parseTeams(response) 50 return teams, nil 51 } 52 53 func parseTeams(input *OnCallResponse) []OnCallTeam { 54 var teamResults []OnCallTeam 55 56 for _, data := range input.TeamsOnCall { 57 var team OnCallTeam 58 team.Name = data.Team.Name 59 team.Slug = data.Team.Slug 60 var userList []string 61 for _, userData := range data.OnCallNow { 62 escalationPolicy := userData.EscalationPolicy.Name 63 for _, user := range userData.Users { 64 userList = append(userList, user.OnCallUser.Username) 65 } 66 team.OnCall = append(team.OnCall, OnCall{escalationPolicy, strings.Join(userList, ", ")}) 67 } 68 teamResults = append(teamResults, team) 69 } 70 71 return teamResults 72 }