cpanel

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 12 Imported by: 0

README

go-cpanel

A complete Go client for cPanel & WHM API function, generated directly from cPanel's own API documentation (the official OpenAPI 3 documents for cPanel & WHM version 138).

API Coverage Package
cPanel UAPI 642 / 642 functions across 97 modules uapi
WHM API 1 625 / 625 functions across 49 categories whm
cPanel API 2 (deprecated) generic executor (direct + via WHM proxy) cpanel

1 267 typed functions — every single function from the official spec — with typed arguments, typed responses, doc comments and links back to the upstream documentation. Pure standard library, no runtime dependencies.

Install

go get github.com/fmotalleb/go-cpanel
import (
    cpanel "github.com/fmotalleb/go-cpanel"
    "github.com/fmotalleb/go-cpanel/uapi"
    "github.com/fmotalleb/go-cpanel/whm"
)

Quick start

cPanel UAPI (port 2083)
package main

import (
    "context"
    "log"

    cpanel "github.com/fmotalleb/go-cpanel"
    "github.com/fmotalleb/go-cpanel/uapi"
)

func main() {
    c, err := cpanel.NewClient("https://cpanel.example.com:2083",
        cpanel.CPanelTokenAuth("username", "CPANEL-API-TOKEN"),
    )
    if err != nil {
        log.Fatal(err)
    }
    uc := uapi.New(c)
    ctx := context.Background()

    // Create an email account.
    res, err := uc.Email().AddPop(ctx, &uapi.EmailAddPopArgs{
        Email:    "bob",
        Domain:   cpanel.String("example.com"), // optional fields are pointers
        Password: "s3cur3-p@ssw0rd",
        Quota:    cpanel.Int(int64(250)),
    })
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("created: %s", res.Data)

    // List email accounts.
    pops, err := uc.Email().ListPops(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    for _, acct := range pops.Data {
        log.Printf("%s", acct.Email)
    }
}
WHM API 1 (port 2087)
    wh, _ := cpanel.NewClient("https://whm.example.com:2087",
        cpanel.WHMTokenAuth("root", "WHM-API-TOKEN"),
    )
    server := whm.New(wh)
    ctx := context.Background()

    // Create a hosting account.
    res, err := server.CreateAcct(ctx, &whm.CreateAcctArgs{
        Username: "bob",
        Domain:   cpanel.String("bob.example.com"),
        Password: cpanel.String("s3cur3-p@ssw0rd"),
        Plan:     cpanel.String("basic"),
    })
    ...

    // List accounts.
    accts, err := server.ListAccts(ctx, nil)
    for _, a := range accts.Data.Acct {
        log.Printf("%s — %s (%s)", a.User, a.Domain, a.Plan)
    }
cPanel API 2 (deprecated)
    // On a cPanel server (port 2083), or through WHM on behalf of a user:
    res, err := client.WHMAPI2(ctx, "bob", "Email", "listpops", nil)
    var accounts []struct{ Email string `json:"email"` }
    _ = res.DecodeData(&accounts)

cPanel API 2 is deprecated; prefer the UAPI equivalent whenever one exists. The generic executor covers all modules (Email, AddonDomain, MysqlFE, Fileman, ...).

Authentication

One Authenticator per credential scheme — pass whichever you use to cpanel.NewClient:

Constructor Scheme Typical use
cpanel.BasicAuth(user, password) HTTP Basic username + password
cpanel.CPanelTokenAuth(user, token) Authorization: cpanel … cPanel API tokens (recommended for UAPI)
cpanel.WHMTokenAuth(user, token) Authorization: whm … WHM API tokens (recommended for WHM)
cpanel.AccessHashAuth(user, hash) Authorization: whm … legacy WHM access hash (deprecated)

Session URLs (…/cpsess########) are also supported: they need no authenticator because the session path itself authenticates the request:

c, _ := cpanel.NewClient("https://host:2083/cpsess1234567890", nil)

Custom transport, TLS, timeouts and headers:

c, _ := cpanel.NewClient("https://host:2087",
    cpanel.WHMTokenAuth("root", "TOKEN"),
    cpanel.WithTimeout(30*time.Second),
    cpanel.WithInsecureSkipVerify(true),          // self-signed certs
    cpanel.WithHTTPClient(myHTTPClient),
    cpanel.WithHeader("X-Env", "staging"),
)

Arguments

  • Functions with documented parameters take a typed …Args struct. Required parameters are plain fields; optional scalars are pointers so that nil means "do not send" — helpers cpanel.String, cpanel.Int, cpanel.Float, cpanel.Bool make them easy to build.
  • Every …Args struct ends with an Extra cpanel.Args field for anything not modeled, notably the UAPI/WHM meta arguments (filter, sort, paginate, columns, ...):
accts, _ := server.ListAccts(ctx, &whm.ListAcctsArgs{
    Search: cpanel.String("example.com"),
    Searchtype: cpanel.String("domain"),
    Extra: cpanel.Args{}.
        Set("api.paginate", "1").
        Set("api.paginate.size", "50").
        Set("api.sort.column", "user"),
})
  • Functions with no documented parameters take a variadic extra ...cpanel.Args instead: uc.ServerInformation().GetServerConfig(ctx) or with extras uc.Email().ListPops(ctx, cpanel.Args{}.Set("api.paginate.size","100")).
  • Parameters whose documented type is a union (e.g. 0 or "unlimited") are any; assign plain Go values (250, "unlimited").
  • Functions documented as POST automatically send their arguments URL-encoded in the request body; everything else uses the query string.

Results & errors

Every call returns a typed envelope result plus an idiomatic error:

res, err := uc.Email().GetEmailQuotaAndType(ctx, args)
if err != nil {
    var apiErr *cpanel.Error
    if errors.As(err, &apiErr) {
        log.Print(apiErr.Op, apiErr.Reason, apiErr.Errors)
    }
}
// res is still usable on API-level failures (messages, warnings, status):
_ = res.OK()                // envelope success flag
_ = res.ErrorStrings()      // collapsed envelope errors
_ = res.MessageStrings()
_ = res.WarningStrings()
  • cpanel.UAPIResult[T] — Data T, Status, Errors, Messages, Warnings, Metadata, and both UAPI wire formats (/execute/... and the legacy /json-api/cpanel wrapper) are normalized automatically.
  • cpanel.WHMResult[T] — Data T plus typed Metadata (command/reason/result/version).
  • Functions with schemaless or union payloads return json.RawMessage as their data; the raw bytes are also always on result.Raw, and result.DecodeData(&v) re-decodes them into your own shape.

Package layout

github.com/fmotalleb/go-cpanel   core client, auth, envelopes, API 2
github.com/fmotalleb/go-cpanel/uapi   642 typed UAPI functions (97 modules)
github.com/fmotalleb/go-cpanel/whm    625 typed WHM API 1 functions (49 categories)
github.com/fmotalleb/go-cpanel/examples/{uapi,whm,api2}   runnable demos
github.com/fmotalleb/go-cpanel/tools/gen   spec fetcher + code generator

All generated files (zz_*_gen.go, and the uapi/whm client.go) are machine-written from the official specs by tools/gen/generate.py — see tools/gen/README.md for regeneration instructions.

Documentation

The generated code targets cPanel & WHM v138; functions annotated with Available since … in their doc comments do not exist on older servers. This project is not affiliated with or endorsed by WebPros/cPanel, LLC.

License

MIT

Documentation

Overview

Package cpanel provides a complete Go client for the cPanel & WHM APIs:

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

View Source
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

func EncodeArgs(v any) (url.Values, error)

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

func Float[T ~float32 | ~float64](v T) *T

Float returns a pointer to v. It is a convenience for populating the optional (pointer) fields of the generated argument structs.

func Int

func Int[T ~int | ~int64](v T) *T

Int returns a pointer to v. It is a convenience for populating the optional (pointer) fields of the generated argument structs.

func String

func String[T ~string](v T) *T

String 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

func (r *API2Inner) UnmarshalJSON(b []byte) error

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.

func (*API2Result) OK

func (r *API2Result) OK() bool

OK reports whether the call succeeded.

type Args

type Args map[string]string

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

func CombineArgs(list ...Args) Args

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.

func (Args) Clone

func (a Args) Clone() Args

Clone returns a shallow copy of the map.

func (Args) Set

func (a Args) Set(key, value string) Args

Set sets a single argument and returns the receiver, allowing calls to be chained.

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>

See: https://api.docs.cpanel.net/cpanel/tokens/

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>

See: https://api.docs.cpanel.net/whm/tokens/

type AuthenticatorFunc

type AuthenticatorFunc func(req *http.Request)

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) BaseURL

func (c *Client) BaseURL() *url.URL

BaseURL returns the server's base URL.

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)
}

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

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

func WithHTTPClient(hc *http.Client) Option

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

func WithHeader(key, value string) Option

WithHeader sets an extra header on every outgoing request.

func WithInsecureSkipVerify

func WithInsecureSkipVerify(skip bool) Option

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets a simple per-request timeout.

For finer-grained control build your own *http.Client and pass it via WithHTTPClient.

func WithUserAgent

func WithUserAgent(ua string) Option

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

func WHM[T any](ctx context.Context, c *Client, function string, args any) (*WHMResult[T], error)

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

func (r *WHMResult[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 (*WHMResult[T]) OK

func (r *WHMResult[T]) OK() bool

OK reports whether the call succeeded (metadata.result == 1).

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.

Jump to

Keyboard shortcuts

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