Last active
July 10, 2017 15:47
-
-
Save scrogson/d582111d6a20b137e59a247a6f33bb3d to your computer and use it in GitHub Desktop.
Fetch current on call users from Pager Duty for a given schedule_id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
"net/url" | |
"time" | |
"github.com/kelseyhightower/envconfig" | |
) | |
type AppConfig struct { | |
ApiKey string `envconfig:"API_KEY" required:"true"` | |
ScheduleId string `envconfig:"SCHEDULE_ID" required:"true"` | |
} | |
type OncallDecoder struct { | |
Oncalls []Oncall `json:"oncalls"` | |
} | |
type Oncall struct { | |
User struct { | |
Name string `json:"summary"` | |
} `json:"user,omitempty"` | |
} | |
func main() { | |
var ( | |
config AppConfig | |
decoder OncallDecoder | |
endpoint string | |
) | |
if err := envconfig.Process("oncall", &config); err != nil { | |
log.Fatal(err.Error()) | |
} | |
if err := buildEndpoint(&endpoint, config); err != nil { | |
log.Fatal(err) | |
} | |
client := &http.Client{} | |
req, _ := http.NewRequest(http.MethodGet, endpoint, nil) | |
req.Header.Add("authorization", "Token token="+config.ApiKey) | |
req.Header.Add("accept", "application/vnd.pagerduty+json;version=2") | |
resp, err := client.Do(req) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer resp.Body.Close() | |
if err := json.NewDecoder(resp.Body).Decode(&decoder); err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println("Users currently on call:") | |
for _, oncall := range decoder.Oncalls { | |
fmt.Println(oncall.User.Name) | |
} | |
} | |
func buildEndpoint(endpoint *string, config AppConfig) error { | |
uri, err := url.Parse("https://api.pagerduty.com/oncalls") | |
if err != nil { | |
return err | |
} | |
since := date() | |
until := since | |
query := uri.Query() | |
query.Set("time_zone", "UTC") | |
query.Set("since", since) | |
query.Set("until", until) | |
query.Set("schedule_ids[]", config.ScheduleId) | |
uri.RawQuery = query.Encode() | |
*endpoint = uri.String() | |
return nil | |
} | |
func date() string { | |
date := time.Now() | |
date.AddDate(0, 0, 1) | |
return date.Format("2006-01-02") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment