bind.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package bind
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "time"
  10. )
  11. // Client contains an API client for a Bind DNS server wrapped
  12. // with a lightweight API
  13. type Client struct {
  14. apiKey string
  15. serverURL string
  16. httpClient *http.Client
  17. }
  18. // NewClient creates a new bind API client
  19. func NewClient(serverURL, apiKey string) *Client {
  20. httpClient := &http.Client{
  21. Timeout: time.Minute,
  22. }
  23. return &Client{apiKey, serverURL, httpClient}
  24. }
  25. // CNAMEData represents the data required to create or delete a CNAME record
  26. // for the nameserver
  27. type CNAMEData struct {
  28. Host string `json:"host"`
  29. Hostname string `json:"hostname"`
  30. }
  31. // CreateCNAMERecord creates a new CNAME record for the nameserver
  32. func (c *Client) CreateCNAMERecord(data *CNAMEData) error {
  33. return c.sendRequest("POST", data)
  34. }
  35. // DeleteCNAMERecord deletes a new CNAME record for the nameserver
  36. func (c *Client) DeleteCNAMERecord(data *CNAMEData) error {
  37. return c.sendRequest("DELETE", data)
  38. }
  39. func (c *Client) sendRequest(method string, data *CNAMEData) error {
  40. reqURL, err := url.Parse(c.serverURL)
  41. if err != nil {
  42. return nil
  43. }
  44. reqURL.Path = "/dns"
  45. strData, err := json.Marshal(data)
  46. if err != nil {
  47. return err
  48. }
  49. req, err := http.NewRequest(
  50. method,
  51. reqURL.String(),
  52. strings.NewReader(string(strData)),
  53. )
  54. if err != nil {
  55. return err
  56. }
  57. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  58. req.Header.Set("Accept", "application/json; charset=utf-8")
  59. req.Header.Set("X-Api-Key", c.apiKey)
  60. res, err := c.httpClient.Do(req)
  61. if err != nil {
  62. return err
  63. }
  64. defer res.Body.Close()
  65. if res.StatusCode != http.StatusOK {
  66. resBytes, err := ioutil.ReadAll(res.Body)
  67. if err != nil {
  68. return fmt.Errorf("request failed with status code %d, but could not read body (%s)\n", res.StatusCode, err.Error())
  69. }
  70. return fmt.Errorf("request failed with status code %d: %s\n", res.StatusCode, string(resBytes))
  71. }
  72. return nil
  73. }