Documentation
¶
Overview ¶
Package cpanel provides a complete Go client for the cPanel & WHM APIs:
- cPanel UAPI (https://api.docs.cpanel.net/specifications/cpanel.openapi); 642 functions across 97 modules, fully generated with typed arguments and typed responses (see the sub-package uapi).
- WHM API 1 (https://api.docs.cpanel.net/specifications/whm.openapi); 625 functions across 49 categories, fully generated with typed arguments and typed responses (see the sub-package whm).
- cPanel API 2 (deprecated); a generic executor is provided via Client.API2 and Client.WHMAPI2, both directly on a cPanel server and through the WHM proxy.
The generated code is derived from the official OpenAPI 3 documents that power cPanel's own developer portal (they apply to cPanel & WHM version 138).
Quick start ¶
import (
"context"
"github.com/fmotalleb/go-cpanel"
"github.com/fmotalleb/go-cpanel/uapi"
"github.com/fmotalleb/go-cpanel/whm"
)
// cPanel (port 2083), authenticated with an API token:
c, _ := cpanel.NewClient("https://cpanel.example.com:2083",
cpanel.CPanelTokenAuth("user", "CPANELAPITOKEN"))
pops, err := uapi.New(c).Email().ListPops(context.Background(), nil)
// WHM (port 2087), authenticated as root with an API token:
server, _ := cpanel.NewClient("https://whm.example.com:2087",
cpanel.WHMTokenAuth("root", "WHMAPITOKEN"))
accts, err := whm.New(server).ListAccts(context.Background(), nil)
Authentication ¶
The package supports every credential scheme accepted by cPanel & WHM: username+password (BasicAuth), cPanel API tokens (CPanelTokenAuth), WHM API tokens (WHMTokenAuth) and the legacy WHM access hash (AccessHashAuth).
Everything in this package uses only the Go standard library.
Index ¶
- Constants
- func Bool[T ~bool](v T) *T
- func EncodeArgs(v any) (url.Values, error)
- func Float[T ~float32 | ~float64](v T) *T
- func Int[T ~int | ~int64](v T) *T
- func String[T ~string](v T) *T
- type API2Event
- type API2Inner
- type API2Result
- type Args
- type Authenticator
- type AuthenticatorFunc
- type Client
- type Error
- type LooseString
- type Option
- type UAPIResult
- type WHMMetadata
- type WHMOutput
- type WHMResult
Constants ¶
const DefaultUserAgent = "go-cpanel (+https://github.com/fmotalleb/go-cpanel)"
DefaultUserAgent is sent with every request unless overridden by WithUserAgent.
Variables ¶
This section is empty.
Functions ¶
func Bool ¶
func Bool[T ~bool](v T) *T
Bool returns a pointer to v. It is a convenience for populating the optional (pointer) fields of the generated argument structs.
func EncodeArgs ¶
EncodeArgs converts an argument value into URL query values.
The value may be one of:
- nil,
- an Args map,
- a *Args map,
- a struct (or pointer to struct) whose exported fields carry `cpanel:"name"` tags.
For structs:
- required fields are tagged `cpanel:"name"` and are always encoded,
- optional fields are tagged `cpanel:"name,omitempty"`; optional scalar fields are pointers so that a nil pointer means "do not send",
- a field tagged `cpanel:"-"` is skipped; a field of type Args with that tag is used as the catch-all Extra bag and merged into the output,
- slices are encoded as repeated query parameters (OpenAPI form style), except []byte which is sent as a single string,
- any value implementing fmt.Stringer is encoded via its String method.
func Float ¶
Float returns a pointer to v. It is a convenience for populating the optional (pointer) fields of the generated argument structs.
Types ¶
type API2Event ¶
type API2Event struct {
Result int `json:"result"`
}
API2Event wraps the "event" style result flags of cPanel API 2.
type API2Inner ¶
type API2Inner struct {
// Data is the raw payload. cPanel API 2 modules usually return an array
// of hashes here, but some return a hash or scalar; use DecodeData to
// extract it into the shape you need.
Data json.RawMessage `json:"data"`
// Error is the module's error string ("" / "NULL" when no error is
// reported by some very old modules).
Error string `json:"error"`
// Event, PreEvent and PostEvent report the hook execution results.
Event API2Event `json:"event"`
PreEvent API2Event `json:"preevent"`
PostEvent API2Event `json:"postevent"`
// Func and Module repeat the executed target.
Func string `json:"func"`
Module string `json:"module"`
// Extra preserves any other keys of the cpanelresult block.
Extra map[string]json.RawMessage `json:"-"`
}
API2Inner is the cpanelresult block of a cPanel API 2 response.
func (*API2Inner) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler so unknown keys are preserved.
type API2Result ¶
type API2Result struct {
// APIVersion is always 2 for cPanel API 2.
APIVersion int `json:"apiversion"`
// Func is the executed function.
Func string `json:"func"`
// Module is the module the function belongs to.
Module string `json:"module"`
// Result is the cpanelresult block.
Result API2Inner `json:"cpanelresult"`
// Error carries a top-level error string (rare).
Error string `json:"error"`
}
API2Result is the parsed (deprecated) cPanel API 2 JSON envelope.
The wire format is:
{"apiversion":2, "func":..., "module":...,
"cpanelresult": {"apiversion":2, "data":[{"foo":"bar"}], "error":"",
"event":{"result":1}, "func":..., "module":...,
"preevent":{"result":1}, "postevent":{"result":1}}}
cPanel API 2 is deprecated; consider the UAPI equivalent of the function first (see the uapi sub-package).
func (*API2Result) DecodeData ¶
func (r *API2Result) DecodeData(v any) error
DecodeData decodes the cpanelresult.data block into v.
type Args ¶
Args is a free-form set of API arguments.
Every generated argument struct contains an Extra field of this type, so callers can always supply parameters that are not modelled by the struct (for example UAPI/WHM meta arguments such as api.filter.*, api.sort.* and api.paginate.*).
func CombineArgs ¶
CombineArgs merges several Args maps into one (later maps win on key conflicts). It is used by the generated wrappers for functions without documented parameters, and is handy for building calls by hand.
type Authenticator ¶
type Authenticator interface {
// Authenticate sets the authentication credentials on req.
Authenticate(req *http.Request)
}
Authenticator applies authentication to an outgoing HTTP request.
Implementations must be safe for concurrent use by multiple goroutines.
func AccessHashAuth ¶
func AccessHashAuth(user, accessHash string) Authenticator
AccessHashAuth authenticates against WHM (port 2087) with a legacy WHM access hash (remote access key). New integrations should use WHMTokenAuth instead, as access hashes are deprecated.
func BasicAuth ¶
func BasicAuth(user, password string) Authenticator
BasicAuth authenticates with a username and password.
It is accepted by both the cPanel (2083) and WHM (2087) APIs and is the least secure of the supported mechanisms; prefer an API token when possible. See: https://api.docs.cpanel.net/whm/introduction/#authentication
func CPanelTokenAuth ¶
func CPanelTokenAuth(user, token string) Authenticator
CPanelTokenAuth authenticates against cPanel (port 2083) with a cPanel API token, as issued by UAPI's Tokens::create_full_access / Tokens::create or the "Manage API Tokens" cPanel interface.
The Authorization header takes the form:
Authorization: cpanel <user>:<token>
func WHMTokenAuth ¶
func WHMTokenAuth(user, token string) Authenticator
WHMTokenAuth authenticates against WHM (port 2087) with a WHM API token, as issued by WHM's "Manage API Tokens" interface (or the api_token_create function).
The Authorization header takes the form:
Authorization: whm <user>:<token>
type AuthenticatorFunc ¶
AuthenticatorFunc adapts a plain function to the Authenticator interface.
func (AuthenticatorFunc) Authenticate ¶
func (f AuthenticatorFunc) Authenticate(req *http.Request)
Authenticate implements Authenticator.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to a single cPanel or WHM server.
Create one with NewClient. A Client is safe for concurrent use by multiple goroutines.
func NewClient ¶
func NewClient(rawBaseURL string, auth Authenticator, opts ...Option) (*Client, error)
NewClient creates a client for the cPanel or WHM server at rawBaseURL.
rawBaseURL must include the scheme, host and port, and may optionally include a session path (for example "https://cpanel.example.com:2083/cpsess1234567890" for session-based authentication). Auth may be nil when the base URL itself authenticates the request (session URLs); for server-to-server integrations pass one of the authenticators from this package.
c, err := cpanel.NewClient("https://cpanel.example.com:2083",
cpanel.CPanelTokenAuth(user, token),
)
func (*Client) API2 ¶
func (c *Client) API2(ctx context.Context, user, module, function string, args Args) (*API2Result, error)
API2 executes a (deprecated) cPanel API 2 function directly against a cPanel server (port 2083 /json-api/cpanel).
user is the cPanel account to act on; pass "" to use the authenticated account. module and function select the function, args its parameters.
func (*Client) WHMAPI2 ¶
func (c *Client) WHMAPI2(ctx context.Context, user, module, function string, args Args) (*API2Result, error)
WHMAPI2 executes a (deprecated) cPanel API 2 function through the WHM proxy (port 2087 /json-api/cpanel), which requires WHM-level credentials and the user argument naming the account to act on.
type Error ¶
type Error struct {
// Op is the logical API operation that failed, for example
// "uapi Email::add_pop" or "whm createacct". It may be empty for
// transport-level failures.
Op string
// StatusCode is the HTTP status code of the response, if any.
StatusCode int
// Reason is the WHM metadata.reason value, when available.
Reason string
// Errors are the error list from the API envelope, when available.
Errors []string
// Warnings are the warning list from the API envelope, when available.
Warnings []string
// Body is the raw response body (truncated to 4 KiB) when it did not
// parse as an API envelope. It is useful for debugging misconfigured
// proxies and similar situations.
Body string
}
Error describes a failed API request.
It is returned in two situations:
- the server answered with HTTP status >= 400 (Auth failures, missing function, ...). In that case StatusCode is set and any parseable API error payload is preserved in Errors/Reason.
- the API envelope reported failure (UAPI status=0, WHM metadata.result=0). In that case StatusCode is 200 (or 0) and Errors and/or Reason describe the failure.
Inspect it with errors.As:
var apiErr *cpanel.Error
if errors.As(err, &apiErr) {
log.Printf("call failed: %s (%v)", apiErr.Reason, apiErr.Errors)
}
type LooseString ¶
type LooseString string
LooseString is a string with tolerant JSON decoding: cPanel's envelopes usually carry plain strings in their errors/messages/warnings lists, but some functions embed structured objects. LooseString accepts both; objects are preserved as their raw JSON representation.
func (LooseString) MarshalJSON ¶
func (s LooseString) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
func (LooseString) String ¶
func (s LooseString) String() string
String returns the underlying string.
func (*LooseString) UnmarshalJSON ¶
func (s *LooseString) UnmarshalJSON(b []byte) error
UnmarshalJSON implements json.Unmarshaler.
type Option ¶
type Option func(*Client)
Option customises a Client. See the With* functions.
func WithHTTPClient ¶
WithHTTPClient sets the *http.Client used for requests.
Use this to configure timeouts, TLS settings (for example InsecureSkipVerify for servers with self-signed certificates), proxies, transports and so on.
func WithHeader ¶
WithHeader sets an extra header on every outgoing request.
func WithInsecureSkipVerify ¶
func WithTimeout ¶
WithTimeout sets a simple per-request timeout.
For finer-grained control build your own *http.Client and pass it via WithHTTPClient.
func WithUserAgent ¶
WithUserAgent overrides the User-Agent header.
type UAPIResult ¶
type UAPIResult[T any] struct { // Data is the function's payload. Data T `json:"data"` // Status is the envelope's success flag: 1 on success, 0 on failure. Status int `json:"status"` // Errors lists fatal errors reported by the function. Errors []LooseString `json:"errors"` // Messages lists informational messages reported by the function. Messages []LooseString `json:"messages"` // Warnings lists non-fatal problems reported by the function. Warnings []LooseString `json:"warnings"` // Metadata carries the envelope metadata (transformed, paginate // information, ...). Keys not understood by the client are preserved. Metadata map[string]json.RawMessage `json:"metadata"` // APIVersion, Module and Func are populated for the legacy // /json-api/cpanel wire format. APIVersion int `json:"apiversion"` Module string `json:"module"` Func string `json:"func"` // Raw is the raw function payload (the "data" member) as returned by // the server, kept for forward compatibility. Raw json.RawMessage `json:"-"` }
UAPIResult is the parsed envelope of a UAPI (cPanel API v3) response.
UAPI has two wire formats, both of which are normalised into this type:
- the /execute/<Module>/<function> format: {"data":..., "errors":[...], "messages":[...], "metadata":{...}, "status":1, "warnings":[...]}
- the legacy /json-api/cpanel format wraps the above in {"apiversion":3, "module":..., "func":..., "result":{...}}.
Data is unmarshalled into the type parameter of the call. When a function has no meaningful documented payload the generated code uses json.RawMessage for it; use DecodeData to re-interpret it when needed.
func UAPI ¶
func UAPI[T any](ctx context.Context, c *Client, module, function string, args any) (*UAPIResult[T], error)
UAPI is a convenience entry point matching UAPICall without an explicit method; it uses GET, which most UAPI functions employ.
func UAPICall ¶
func UAPICall[T any](ctx context.Context, c *Client, method, module, function string, args any) (*UAPIResult[T], error)
UAPICall executes a UAPI function against a cPanel server.
module and function select the function (for example "Email", "add_pop"); method must be the HTTP method documented for the function (the generated wrappers supply it automatically). args may be nil, an Args value or a struct carrying `cpanel` tags.
The returned result is always non-nil when the server returned a parseable envelope; when the envelope reports failure the *Error is non-nil too, so both messages and failure details stay accessible:
res, err := cpanel.UAPICall[any](ctx, c, http.MethodGet, "Email", "list_pops", nil)
if err != nil {
logs := res.ErrorStrings() // still usable
}
func (*UAPIResult[T]) DecodeData ¶
func (r *UAPIResult[T]) DecodeData(v any) error
DecodeData re-decodes the raw payload into v. It is mainly useful for functions whose payload type is json.RawMessage.
func (*UAPIResult[T]) ErrorStrings ¶
func (r *UAPIResult[T]) ErrorStrings() []string
ErrorStrings returns the envelope's errors as plain strings.
func (*UAPIResult[T]) MessageStrings ¶
func (r *UAPIResult[T]) MessageStrings() []string
MessageStrings returns the envelope's messages as plain strings.
func (*UAPIResult[T]) OK ¶
func (r *UAPIResult[T]) OK() bool
OK reports whether the call succeeded (status == 1).
func (*UAPIResult[T]) WarningStrings ¶
func (r *UAPIResult[T]) WarningStrings() []string
WarningStrings returns the envelope's warnings as plain strings.
type WHMMetadata ¶
type WHMMetadata struct {
// Command is the executed WHM API 1 function name.
Command string `json:"command"`
// Reason is "OK" on success, or the reason of the failure.
Reason string `json:"reason"`
// Result is 1 on success and 0 on failure.
Result int `json:"result"`
// Version is the WHM API version (always 1 here).
Version int `json:"version"`
// Messages, Errors and Warnings are emitted by some functions.
Messages []LooseString `json:"messages"`
Errors []LooseString `json:"errors"`
Warnings []LooseString `json:"warnings"`
// Output carries the detailed output block some functions return
// (metadata.output.errors / metadata.output.messages).
Output *WHMOutput `json:"output"`
// Extra preserves every other metadata key the server returned.
Extra map[string]json.RawMessage `json:"-"`
}
WHMMetadata is the metadata section of a WHM API 1 response.
func (*WHMMetadata) UnmarshalJSON ¶
func (m *WHMMetadata) UnmarshalJSON(b []byte) error
UnmarshalJSON implements json.Unmarshaler so that unknown metadata keys are preserved in Extra.
type WHMOutput ¶
type WHMOutput struct {
Messages []LooseString `json:"messages"`
Errors []LooseString `json:"errors"`
Warnings []LooseString `json:"warnings"`
}
WHMOutput is the structured output block nested in some functions' metadata.
type WHMResult ¶
type WHMResult[T any] struct { // Data is the function's payload. Data T `json:"data"` // Metadata carries the call metadata. Metadata WHMMetadata `json:"metadata"` // Raw is the raw function payload (the "data" member) as returned by // the server, kept for forward compatibility. Raw json.RawMessage `json:"-"` }
WHMResult is the parsed envelope of a WHM API 1 JSON response.
The wire format is:
{"data": {...}, "metadata": {"command": "...", "reason": "OK",
"result": 1, "version": 1}}
func WHM ¶
WHM is a convenience entry point matching WHMCall without an explicit method; it uses GET, which most WHM API 1 functions employ.
func WHMCall ¶
func WHMCall[T any](ctx context.Context, c *Client, method, function string, args any) (*WHMResult[T], error)
WHMCall executes a WHM API 1 function against a WHM server.
function is the function name (for example "createacct"); method must be the HTTP method documented for the function (the generated wrappers supply it automatically). args may be nil, an Args value or a struct carrying `cpanel` tags. "api.version=1" is always added for you.
func (*WHMResult[T]) DecodeData ¶
DecodeData re-decodes the raw payload into v. It is mainly useful for functions whose payload type is json.RawMessage.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
api2
command
Command api2-demo demonstrates calling the deprecated cPanel API 2, including calls proxied through WHM (acting as a specific cPanel user).
|
Command api2-demo demonstrates calling the deprecated cPanel API 2, including calls proxied through WHM (acting as a specific cPanel user). |
|
uapi
command
Command uapi-demo demonstrates calling cPanel UAPI functions with the generated typed wrappers.
|
Command uapi-demo demonstrates calling cPanel UAPI functions with the generated typed wrappers. |
|
whm
command
Command whm-demo demonstrates calling WHM API 1 functions with the generated typed wrappers.
|
Command whm-demo demonstrates calling WHM API 1 functions with the generated typed wrappers. |
|
Package uapi contains typed wrappers for every cPanel UAPI function.
|
Package uapi contains typed wrappers for every cPanel UAPI function. |
|
Package whm contains typed wrappers for every WHM API 1 function.
|
Package whm contains typed wrappers for every WHM API 1 function. |