loopia

package module
v0.0.0-...-c7e6186 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

loopia-go

Go Reference

Go client for LoopiaAPI, the XML-RPC API for the Loopia Customer Zone and Reseller Zone.

go get github.com/Sajfer/loopia-go

Usage

Create an API user in the Loopia Customer Zone under Account Settings → LoopiaAPI, then:

client := loopia.New("user@loopiaapi", "password")

records, err := client.GetZoneRecords(ctx, "example.com", "@")
if err != nil {
	log.Fatal(err)
}

record := loopia.Record{Type: "A", TTL: 3600, Value: "192.0.2.10"}
err = client.AddZoneRecord(ctx, "example.com", "www", &record) // fills record.ID

Resellers can act on a customer's account:

domains, err := client.ForCustomer("C12345").GetDomains(ctx)
Errors

When LoopiaAPI answers with a status other than OK, methods return a *loopia.StatusError. XML-RPC faults are returned as *loopia.FaultError. Both work with errors.Is:

switch {
case errors.Is(err, loopia.ErrAuth):
	// wrong username or password
case errors.Is(err, loopia.ErrRateLimited):
	// more than 60 calls per minute
case errors.Is(err, &loopia.FaultError{Code: loopia.FaultDomainNotAvailable}):
	// a specific fault code
}

Loopia reports some problems either as a status or as a fault (invalid credentials come back as fault 401, not AUTH_ERROR), so ErrAuth, ErrRateLimited and ErrInsufficientFunds match both forms.

Options
loopia.New(user, pass,
	loopia.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}),
	loopia.WithEndpoint("https://api.loopia.rs/RPCSERV"),
)

Supported methods

LoopiaAPI Go
addDomain AddDomain
addSubdomain AddSubdomain
addZoneRecord AddZoneRecord
domainIsFree DomainIsFree
getCreditsAmount GetCreditsAmount
getDomain GetDomain
getDomains GetDomains
getInvoice GetInvoice
getSubdomains GetSubdomains
getUnpaidInvoices GetUnpaidInvoices
getZoneRecords GetZoneRecords, GetZoneRecord
orderDomain OrderDomain
payInvoiceUsingCredits PayInvoiceUsingCredits
removeDomain RemoveDomain
removeSubdomain RemoveSubdomain
removeZoneRecord RemoveZoneRecord
transferDomain TransferDomain
updateDNSServers UpdateDNSServers
updateZoneRecord UpdateZoneRecord
createNewAccount (reseller) CreateNewAccount
getCustomers (reseller) GetCustomers
getOrderStatus (reseller) GetOrderStatus
transferCreditsByCurrency (reseller) TransferCreditsByCurrency

Upgrading from the pre-module version

  • Import path is github.com/Sajfer/loopia-go; API is now Client and New no longer returns an error.
  • Every method takes a context.Context first.
  • Status methods return error instead of (*Status, error). A non-OK status is now always an error (previously some were silently dropped).
  • GetSubdomains returns []string; Subdomain and GetSubdomain are gone (use slices.Contains).
  • RemoveSubDomain is renamed RemoveSubdomain.
  • AddZoneRecord returns ErrRecordIDUnknown if the record was created but its ID could not be found.

License

MIT

Documentation

Overview

Package loopia is a client for LoopiaAPI, the XML-RPC API for the Loopia Customer Zone and Loopia Reseller Zone.

See https://support.loopia.com/wiki/loopiaapi/ for the upstream documentation. Every documented method is available on Client; methods that resellers can run against a customer's account honour the customer number set with Client.ForCustomer.

LoopiaAPI allows at most 60 calls per minute (15 of which may be domain searches). Exceeding the limit results in a StatusError wrapping StatusRateLimited or a FaultError with code FaultRateLimited.

Example
package main

import (
	"context"
	"fmt"
	"log"

	loopia "github.com/Sajfer/loopia-go"
)

func main() {
	ctx := context.Background()
	client := loopia.New("user@loopiaapi", "password")

	record := loopia.Record{Type: "A", TTL: 3600, Value: "192.0.2.10"}
	if err := client.AddZoneRecord(ctx, "example.com", "www", &record); err != nil {
		log.Fatal(err)
	}
	fmt.Println("created record", record.ID)

	record.Value = "192.0.2.20"
	if err := client.UpdateZoneRecord(ctx, "example.com", "www", record); err != nil {
		log.Fatal(err)
	}
}

Index

Examples

Constants

View Source
const (
	FaultUnknown                  = 404
	FaultUnauthorized             = 401
	FaultRateLimited              = 429
	FaultMethodNotFound           = 620
	FaultBadSignature             = 623
	FaultParseError               = 631
	FaultNoMethod                 = 632
	FaultMissingValue             = 633
	FaultInvalidMethod            = 634
	FaultInvalidParameter         = 637
	FaultMethodNotAllowed         = 639
	FaultDomainNotAvailable       = 40001
	FaultDomainInvalid            = 40004
	FaultDomainConfigInvalid      = 40011
	FaultAccountTypeInvalid       = 40014
	FaultDomainConfigNotAvailable = 40015
	FaultCustomerNotConnected     = 40401
	FaultAccountParametersInvalid = 50001
	FaultInsufficientFunds        = 60001
)

Fault codes returned by LoopiaAPI in XML-RPC fault responses.

View Source
const DefaultEndpoint = "https://api.loopia.se/RPCSERV"

DefaultEndpoint is the URL of the LoopiaAPI XML-RPC service.

Variables

Sentinel errors for each non-OK status, for use with errors.Is.

View Source
var ErrRecordIDUnknown = errors.New("loopia: record created but its ID could not be determined")

ErrRecordIDUnknown is returned by Client.AddZoneRecord when the record was created but its ID could not be determined.

View Source
var ErrRecordNotFound = errors.New("loopia: zone record not found")

ErrRecordNotFound is returned by Client.GetZoneRecord when no record has the requested ID.

Functions

This section is empty.

Types

type AccountType

type AccountType string

AccountType identifies the type of a Loopia account.

const (
	AccountLoopiaDomain        AccountType = "LOOPIADOMAIN"
	AccountLoopiaDNS           AccountType = "LOOPIADNS"
	AccountEmailPrivate        AccountType = "EMAIL_PRIVATE"
	AccountStarter             AccountType = "STARTER"
	AccountHostingPrivate      AccountType = "HOSTING_PRIVATE"
	AccountHostingBusiness     AccountType = "HOSTING_BUSINESS"
	AccountHostingBusinessPlus AccountType = "HOSTING_BUSINESS_PLUS"
)

Account types.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client talks to LoopiaAPI. It is safe for concurrent use.

func New

func New(username, password string, opts ...Option) *Client

New returns a client authenticating with the given LoopiaAPI credentials. API users are created in the Loopia Customer Zone under Account Settings → LoopiaAPI.

func (*Client) AddDomain

func (c *Client) AddDomain(ctx context.Context, domain string) error

AddDomain adds an existing domain name to the account.

func (*Client) AddSubdomain

func (c *Client) AddSubdomain(ctx context.Context, domain, subdomain string) error

AddSubdomain connects a subdomain to a domain name.

func (*Client) AddZoneRecord

func (c *Client) AddZoneRecord(ctx context.Context, domain, subdomain string, record *Record) error

AddZoneRecord adds a DNS record to a subdomain. record.ID is ignored.

LoopiaAPI does not return the ID of the new record, so AddZoneRecord looks it up afterwards and stores it in record.ID, picking the newest record with the same values. If no such record is found, it returns ErrRecordIDUnknown; the record has still been created.

func (*Client) CreateNewAccount

func (c *Client) CreateNewAccount(ctx context.Context, a NewAccount) (string, error)

CreateNewAccount creates a new Loopia account, and registers its domain if requested. It returns the order reference, which can be passed to Client.GetOrderStatus. Reseller only.

func (*Client) CustomerNumber

func (c *Client) CustomerNumber() string

CustomerNumber returns the customer number set with Client.ForCustomer.

func (*Client) DomainIsFree

func (c *Client) DomainIsFree(ctx context.Context, domain string) (bool, error)

DomainIsFree reports whether a domain name is available for registration. The domain must be ACE-coded if it is an IDN domain.

func (*Client) ForCustomer

func (c *Client) ForCustomer(customerNumber string) *Client

ForCustomer returns a copy of the client that acts on the account with the given customer number. Only resellers can act on other accounts; an empty customer number means the API user's own account.

Example
package main

import (
	"context"
	"fmt"
	"log"

	loopia "github.com/Sajfer/loopia-go"
)

func main() {
	reseller := loopia.New("reseller@loopiaapi", "password")

	domains, err := reseller.ForCustomer("C12345").GetDomains(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	for _, d := range domains {
		fmt.Println(d.Name, d.ExpirationDate)
	}
}

func (*Client) GetCreditsAmount

func (c *Client) GetCreditsAmount(ctx context.Context) (float64, error)

GetCreditsAmount returns the current LoopiaPrePAID balance, in the account's currency, for amounts deposited after 2015-12-04.

func (*Client) GetCustomers

func (c *Client) GetCustomers(ctx context.Context) ([]Customer, error)

GetCustomers returns all customers connected to the reseller.

func (*Client) GetDomain

func (c *Client) GetDomain(ctx context.Context, domain string) (*Domain, error)

GetDomain returns information about a domain name in the account, including the billing information needed to pay for it.

func (*Client) GetDomains

func (c *Client) GetDomains(ctx context.Context) ([]Domain, error)

GetDomains returns all domain names in the account.

func (*Client) GetInvoice

func (c *Client) GetInvoice(ctx context.Context, referenceNo string, withVAT bool) (*Invoice, error)

GetInvoice returns the invoice with the given reference number. withVAT selects whether amounts include VAT.

func (*Client) GetOrderStatus

func (c *Client) GetOrderStatus(ctx context.Context, orderReference string) (*Order, error)

GetOrderStatus returns the status of an order created by Client.CreateNewAccount. Reseller only.

func (*Client) GetSubdomains

func (c *Client) GetSubdomains(ctx context.Context, domain string) ([]string, error)

GetSubdomains returns the names of all subdomains of a domain, such as "@", "*" and "www".

func (*Client) GetUnpaidInvoices

func (c *Client) GetUnpaidInvoices(ctx context.Context, withVAT bool) ([]Invoice, error)

GetUnpaidInvoices returns all unpaid invoices of the account. withVAT selects whether amounts include VAT.

func (*Client) GetZoneRecord

func (c *Client) GetZoneRecord(ctx context.Context, domain, subdomain string, id int64) (*Record, error)

GetZoneRecord returns the DNS record of a subdomain with the given ID, or ErrRecordNotFound. LoopiaAPI has no method for fetching a single record, so this fetches all records of the subdomain.

func (*Client) GetZoneRecords

func (c *Client) GetZoneRecords(ctx context.Context, domain, subdomain string) ([]Record, error)

GetZoneRecords returns all DNS records of a subdomain.

func (*Client) OrderDomain

func (c *Client) OrderDomain(ctx context.Context, domain string, acceptedTerms bool) error

OrderDomain adds a new domain name to the account and registers it. acceptedTerms must reflect whether the account owner has agreed to Loopia's terms and conditions for registration.

func (*Client) PayInvoiceUsingCredits

func (c *Client) PayInvoiceUsingCredits(ctx context.Context, referenceNo string) error

PayInvoiceUsingCredits pays an invoice using LoopiaPrePAID credits, provided the account has enough credits.

func (*Client) RemoveDomain

func (c *Client) RemoveDomain(ctx context.Context, domain string, deactivate bool) error

RemoveDomain removes a domain name from the account, after which Loopia no longer renews it. If deactivate is true the domain is deactivated now and removed on its due date; otherwise it is removed immediately.

func (*Client) RemoveSubdomain

func (c *Client) RemoveSubdomain(ctx context.Context, domain, subdomain string) error

RemoveSubdomain removes a subdomain from a domain name.

func (*Client) RemoveZoneRecord

func (c *Client) RemoveZoneRecord(ctx context.Context, domain, subdomain string, id int64) error

RemoveZoneRecord removes the DNS record with the given ID from a subdomain.

func (*Client) TransferCreditsByCurrency

func (c *Client) TransferCreditsByCurrency(ctx context.Context, senderNumber, recipientNumber string, amount float64, currency string) error

TransferCreditsByCurrency transfers LoopiaPrePAID credits deposited after 2015-12-04 from one account to another. currency is a three-letter ISO 4217 code; LoopiaAPI currently supports SEK and NOK. Reseller only.

func (*Client) TransferDomain

func (c *Client) TransferDomain(ctx context.Context, domain, authCode string) error

TransferDomain starts a transfer of a domain name to the account, using the auth code from the previous registrar. Some TLDs charge a transfer fee.

func (*Client) UpdateDNSServers

func (c *Client) UpdateDNSServers(ctx context.Context, domain string, nameservers []string) error

UpdateDNSServers changes the name servers for a domain name. At least two name servers must be given.

func (*Client) UpdateZoneRecord

func (c *Client) UpdateZoneRecord(ctx context.Context, domain, subdomain string, record Record) error

UpdateZoneRecord updates the DNS record with ID record.ID.

type Contact

type Contact struct {
	FirstName string `xmlrpc:"firstname"`
	LastName  string `xmlrpc:"lastname"`
	// Company is empty for a private individual.
	Company string `xmlrpc:"company"`
	Street  string `xmlrpc:"street"`
	Street2 string `xmlrpc:"street2"`
	Zip     string `xmlrpc:"zip"`
	City    string `xmlrpc:"city"`
	// CountryISO2 is a two-letter ISO 3166-1 country code, e.g. "se".
	CountryISO2 string `xmlrpc:"country_iso2"`
	// OrgNo is the organisation number, formatted like 556633-9304.
	OrgNo string `xmlrpc:"orgno"`
	// NoridPID is required for .NO domains ordered by private individuals.
	NoridPID string `xmlrpc:"norid_pid,omitempty"`
	// Phone, Cell and Fax are formatted like 021-128222.
	Phone string `xmlrpc:"phone"`
	Cell  string `xmlrpc:"cell"`
	Fax   string `xmlrpc:"fax"`
	Email string `xmlrpc:"email"`
}

Contact is a domain owner, administrative or billing contact (contact).

type Customer

type Customer struct {
	// Company is empty for a private individual.
	Company string `xmlrpc:"company"`
	// Name is the name of the contact or account owner.
	Name           string      `xmlrpc:"name"`
	CustomerNumber string      `xmlrpc:"customer_number"`
	AccountType    AccountType `xmlrpc:"account_type"`
}

Customer is a customer connected to a reseller (customer_obj).

type Domain

type Domain struct {
	// Name is the domain name, ACE-coded if it is an IDN domain.
	Name string
	// Paid reports whether the domain is marked as paid.
	Paid bool
	// Registered reports whether the domain is registered and ready to use.
	Registered bool
	// RenewalStatus is the renewal status of the domain at Loopia.
	RenewalStatus string
	// ExpirationDate is the expiry date, or "UNKNOWN" if the domain is not
	// renewed by Loopia.
	ExpirationDate string
	// ReferenceNo is the reference number of the invoice that must be paid to
	// activate the domain when Paid is false. It can be passed to
	// [Client.PayInvoiceUsingCredits].
	ReferenceNo string
}

Domain describes a domain name in an account (domain_obj).

type DomainConfiguration

type DomainConfiguration string

DomainConfiguration is the configuration applied to a new domain name.

const (
	DomainNoConfig        DomainConfiguration = "NO_CONFIG"
	DomainParking         DomainConfiguration = "PARKING"
	DomainHostingUnix     DomainConfiguration = "HOSTING_UNIX"
	DomainHostingAutobahn DomainConfiguration = "HOSTING_AUTOBAHN"
	DomainHostingWindows  DomainConfiguration = "HOSTING_WINDOWS"
)

Domain configurations.

type FaultError

type FaultError struct {
	Code    int
	Message string
}

FaultError is an XML-RPC fault returned by LoopiaAPI. Code is one of the Fault* constants.

func (*FaultError) Error

func (e *FaultError) Error() string

func (*FaultError) Is

func (e *FaultError) Is(target error) bool

Is reports whether target is a *FaultError with the same code, or a *StatusError with the same meaning, so that errors.Is(err, ErrAuth) also matches fault 401.

type Invoice

type Invoice struct {
	// ReferenceNo is the reference and invoice number.
	ReferenceNo string
	// Total is the invoice total.
	Total float64
	// Credits is the amount deducted using LoopiaPrePAID credits.
	Credits float64
	// VAT is the VAT amount.
	VAT float64
	// ToPay is the amount to pay, including tax where applicable.
	ToPay float64
	// Currency is the invoice currency.
	Currency string
	// Expires is the due date.
	Expires string
	// Items are the invoice line items.
	Items []InvoiceItem
}

Invoice describes an invoice (invoice_obj).

type InvoiceItem

type InvoiceItem struct {
	// Product is the product description.
	Product string
	// Until is the period covered by the item, if applicable.
	Until string
	// Fee is the unit price.
	Fee float64
	// Discount is the discount deduction.
	Discount float64
	// Items is the quantity.
	Items float64
	// Subtotal is the total amount for the item.
	Subtotal float64
}

InvoiceItem is a single invoice line item (invoice_item_obj).

type NewAccount

type NewAccount struct {
	// Domain is the username of the new account, and the domain registered
	// when BuyDomain is set. ACE-coded if it is an IDN domain.
	Domain string
	// Owner owns the account and domain.
	Owner Contact
	// BillingContactReseller makes the reseller the billing contact instead
	// of sending invoices directly to the customer.
	BillingContactReseller bool
	// TechContactReseller makes the reseller the technical contact instead of
	// sending technical information directly to the customer.
	TechContactReseller bool
	// BuyDomain registers Domain.
	BuyDomain           bool
	DomainConfiguration DomainConfiguration
	AccountType         AccountType
	// EndUserHasAcceptedTerms must be true: the end customer must have
	// accepted any relevant agreement.
	EndUserHasAcceptedTerms bool
}

NewAccount holds the parameters of Client.CreateNewAccount.

type Option

type Option func(*Client)

Option configures a Client.

func WithEndpoint

func WithEndpoint(url string) Option

WithEndpoint overrides the XML-RPC endpoint, for example to use one of Loopia's regional APIs or a test server.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets the HTTP client used for requests. The default is http.DefaultClient.

type Order

type Order struct {
	Status OrderStatus `xmlrpc:"order_status"`
	// CustomerNumber is empty until the account has been created.
	CustomerNumber string `xmlrpc:"customer_number"`
}

Order is the status of an order created by Client.CreateNewAccount (order_status_obj).

type OrderStatus

type OrderStatus string

OrderStatus is the status of an order created by Client.CreateNewAccount.

const (
	OrderDeleted   OrderStatus = "DELETED"
	OrderPending   OrderStatus = "PENDING"
	OrderProcessed OrderStatus = "PROCESSED"
)

Order statuses.

type Record

type Record struct {
	// ID identifies the record when updating or removing it.
	ID int64 `xmlrpc:"record_id"`
	// TTL is the record's time to live in seconds. LoopiaDNS defaults to 3600.
	TTL int `xmlrpc:"ttl"`
	// Type is the record type, for instance A or CNAME.
	Type string `xmlrpc:"type"`
	// Value is the record data (rdata), e.g. the IPv4 address of an A record.
	Value string `xmlrpc:"rdata"`
	// Priority is the priority of MX records; lower values are used first.
	Priority int `xmlrpc:"priority"`
}

Record is a DNS record in the zone of a domain name (record_obj).

type Status

type Status string

Status is the status code returned by methods that do not return data.

const (
	StatusOK                Status = "OK"
	StatusAuthError         Status = "AUTH_ERROR"
	StatusDomainOccupied    Status = "DOMAIN_OCCUPIED"
	StatusRateLimited       Status = "RATE_LIMITED"
	StatusBadIndata         Status = "BAD_INDATA"
	StatusUnknownError      Status = "UNKNOWN_ERROR"
	StatusInsufficientFunds Status = "INSUFFICIENT_FUNDS"
)

Status codes returned by LoopiaAPI.

type StatusError

type StatusError struct {
	Status Status
}

StatusError is returned when LoopiaAPI answers with a status other than OK. Use errors.Is with the Err* variables to check for a specific status; ErrAuth, ErrRateLimited and ErrInsufficientFunds also match the equivalent FaultError.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	loopia "github.com/Sajfer/loopia-go"
)

func main() {
	client := loopia.New("user@loopiaapi", "wrong password")

	err := client.AddSubdomain(context.Background(), "example.com", "www")
	switch {
	case errors.Is(err, loopia.ErrAuth):
		fmt.Println("check your LoopiaAPI credentials")
	case errors.Is(err, loopia.ErrRateLimited):
		fmt.Println("slow down: at most 60 calls per minute")
	case err != nil:
		log.Fatal(err)
	}
}

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) Is

func (e *StatusError) Is(target error) bool

Is reports whether target is a *StatusError with the same status.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址