package msrcgo import ( "errors" "io" "io/ioutil" "net/http" ) const ( APIVersion = "?api-version=2016-08-01" UpdatesURI = "/Updates" CvrfURI = "/cvrf/" URL = "https://api.msrc.microsoft.com" APIKeyHeader = "api-key" AcceptHeader = "Accept" AcceptValue = "application/json" GET = "GET" ) // Client represents the API client type Client struct { key string allUpdates *http.Request } // NewClient returns a new Client instance func NewClient(key string) *Client { all, _ := http.NewRequest(GET, URL+UpdatesURI+APIVersion, nil) all.Header.Set(AcceptHeader, AcceptValue) all.Header.Set(APIKeyHeader, key) return &Client{key, all} } // GetAllUpdates returns the Update struct (a list of all bulletins) func (c *Client) GetAllUpdates() (*Update, error) { return c.getUpdate(c.allUpdates) } // GetUpdateID returns a Update struct of the given id // Example id: "2016-Sep" func (c *Client) GetUpdateID(id string) (*Update, error) { req, _ := http.NewRequest(GET, URL+UpdatesURI+"('"+id+"')"+APIVersion, nil) req.Header.Set(AcceptHeader, AcceptValue) req.Header.Set(APIKeyHeader, c.key) return c.getUpdate(req) } // GetCVRF returns the CVRF struct of the given id // Example id: "2016-Sep" func (c *Client) GetCVRF(id string) (*CVRF, error) { req, _ := http.NewRequest(GET, URL+CvrfURI+id+APIVersion, nil) req.Header.Set(AcceptHeader, AcceptValue) req.Header.Set(APIKeyHeader, c.key) return c.getCVRF(req) } func (c *Client) request(req *http.Request) (body io.ReadCloser, err error) { resp, err := (&http.Client{}).Do(req) if err != nil { return } if resp.StatusCode != http.StatusOK { b, e := ioutil.ReadAll(resp.Body) defer resp.Body.Close() if e == nil { err = errors.New(string(b)) } return } body = resp.Body return } func (c *Client) getUpdate(req *http.Request) (u *Update, err error) { body, err := c.request(req) if err != nil { return } defer body.Close() return DecodeUpdate(body) } func (c *Client) getCVRF(req *http.Request) (u *CVRF, err error) { body, err := c.request(req) if err != nil { return } defer body.Close() return DecodeCVRF(body) }