go-hibp/paste.go
Winni Neessen e42f8b3101
Fix missing HTTP response return in PastedAccount method.
Fixes #22

- In case of a HTTP error the PastedAccount method is supposed to return the HTTP response, since this can hold valuable information about the reason why the request failed. Instead, it was returning `nil`. This PR fixes this behaviour.
- Additionally, this PR introduces tests to catch such oversights
- Finally a proper `error.New()` error has been introduces, to that `error.Is()` can be used on common error that are detected by the module
2022-12-22 09:57:57 +01:00

60 lines
1.8 KiB
Go

package hibp
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
// ErrNoAccountID is returned if no account ID is given to the PastedAccount method
var ErrNoAccountID = errors.New("no account ID given")
// PasteAPI is a HIBP pastes API client
type PasteAPI struct {
hibp *Client // References back to the parent HIBP client
}
// Paste represents a JSON response structure of the pastes API
type Paste struct {
// Source is the paste service the record was retrieved from. Current values are: Pastebin,
// Pastie, Slexy, Ghostbin, QuickLeak, JustPaste, AdHocUrl, PermanentOptOut, OptOut
Source string `json:"Source"`
// ID of the paste as it was given at the source service. Combined with the "Source" attribute, this
// can be used to resolve the URL of the paste
ID string `json:"ID"`
// Title of the paste as observed on the source site. This may be null and if so will be omitted from
// the response
Title string `json:"Title"`
// Date is the date and time (precision to the second) that the paste was posted. This is taken directly
// from the paste site when this information is available but may be null if no date is published
Date time.Time `json:"Date"`
// EmailCount is number of emails that were found when processing the paste. Emails are extracted by
// using the regular expression \b[a-zA-Z0-9\.\-_\+]+@[a-zA-Z0-9\.\-_]+\.[a-zA-Z]+\b
EmailCount int `json:"EmailCount"`
}
// PastedAccount returns a single breached site based on its name
func (p *PasteAPI) PastedAccount(a string) ([]*Paste, *http.Response, error) {
if a == "" {
return nil, nil, ErrNoAccountID
}
au := fmt.Sprintf("%s/pasteaccount/%s", BaseURL, a)
hb, hr, err := p.hibp.HTTPResBody(http.MethodGet, au, nil)
if err != nil {
return nil, hr, err
}
var pd []*Paste
if err := json.Unmarshal(hb, &pd); err != nil {
return nil, hr, err
}
return pd, hr, nil
}