go-openlibrary/client/client.go

129 lines
3.5 KiB
Go

// A simple Go wrapper around the OpenLibrary.org Books API
package client
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
var (
defaultAPI = "https://openlibrary.org/api/books"
)
var (
// FormatError marks errors with provided book identifers
FormatError = fmt.Errorf("identifier in wrong format")
// NetworkError marks errors with the connection to the OpenLibrary API
NetworkError = fmt.Errorf("network error")
// NotFoundError marks an empty response from the OpenLibrary API
NotFoundError = fmt.Errorf("book not found")
)
// Client provides OpenLibrary Books API query methods
type Client struct {
httpClient http.Client
apipath string
}
// SetHTTPClient updates the httpClient on the client with a manually-configured one.
// If unset, the client will fall back to using http.DefaultClient.
func (c *Client) SetHTTPClient(h http.Client) {
c.httpClient = h
}
// SetAPIPath updates the hostname and path to the API; the default is "https://openlibrary.org/api/books".
// If APIPath is set to an empty string, the client will fall back to the default option.
func (c *Client) SetAPIPath(p string) {
c.apipath = p
}
// GetByISBN fetches details for a book based on its ISBN10 or ISBN13.
func (c *Client) GetByISBN(k string) (*BookDetails, error) {
if k == "" {
return nil, fmt.Errorf("%w: ISBN cannot be empty", FormatError)
} else if len(k) != 10 && len(k) != 13 {
return nil, fmt.Errorf("%w: ISBN must be either 10 or 13 digits", FormatError)
}
key := "ISBN:" + k
return c.fetch(key)
}
// GetByOCLC fetches details for a book based on its WorldCat OCLC number.
func (c *Client) GetByOCLC(k string) (*BookDetails, error) {
if k == "" {
return nil, fmt.Errorf("%w: OCLC cannot be empty", FormatError)
}
key := "OCLC:" + k
return c.fetch(key)
}
// GetByLCCN fetches details for a book based on its Library of Congress Control Number.
func (c *Client) GetByLCCN(k string) (*BookDetails, error) {
if k == "" {
return nil, fmt.Errorf("%w: LCCN cannot be empty", FormatError)
}
key := "LCCN:" + k
return c.fetch(key)
}
// GetByOLID fetches details for a book based on its OpenLibrary ID number.
func (c *Client) GetByOLID(k string) (*BookDetails, error) {
if k == "" {
return nil, fmt.Errorf("%w: OLID cannot be empty", FormatError)
}
key := "OLID:" + k
return c.fetch(key)
}
// GetByRawKey fetches details for a book based on an arbitrary key; this method is provided
// as a future-proof fallback in case the OpenLibrary API adds more "bibkey" request types in the future.
// Most users should use one of the other lookup functions.
func (c *Client) GetByRawKey(k string) (*BookDetails, error) {
return c.fetch(k)
}
func (c *Client) fetch(key string) (*BookDetails, error) {
h := c.apipath
if h == "" {
h = defaultAPI
}
u, err := url.Parse(h)
if err != nil {
return nil, fmt.Errorf("%w: %v", NetworkError, err)
}
u.RawQuery = url.Values{
"bibkeys": []string{key},
"jscmd": []string{"data"},
"format": []string{"json"},
}.Encode()
resp, err := c.httpClient.Get(u.String())
if err != nil {
return nil, fmt.Errorf("%w: %v", NetworkError, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%w: received non-200 status code: %d", NetworkError, resp.StatusCode)
}
var result response
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("%w: %v", NetworkError, err)
}
if err = json.Unmarshal(b, &result); err != nil {
return nil, fmt.Errorf("%w: %v", NetworkError, err)
}
details, ok := result[key]
if !ok {
return nil, NotFoundError
}
return &details, nil
}