Documentation
¶
Overview ¶
Package printer writes the result of each command in the format --output names. A ResponseHandler has one method per kind of result, taking the SDK response type, and one implementation per format:
- json: the API's response body, unchanged (see package apiresponse), or the JSON of a result the CLI built itself
- table: bordered tables, for reading in a terminal
- plain: one "Label: value" line per field, leaving out missing values
- csv: a header row and one row per item, with RFC 3339 times
Table and plain output escape control characters, since results carry text from email senders and other users. The root command creates the handler and stores it in the command's context, where a command gets it:
response, err := client.ListDomains(requests.GetDomainsParams{})
if err != nil {
return err
}
return printer.GetResponseHandlerFromCommand(cmd).HandleDomainList(response, printer.ListConfig{
SuccessMessage: "Domains retrieved successfully",
EmptyMessage: "No domains found",
})
Index ¶
- Constants
- func DisplayTime(t time.Time) string
- func DisplayWriter(w io.Writer) io.Writer
- func ErrorHint(err error) string
- func EscapeControl(s string) string
- func EscapeDisplayText(s string) string
- func GetSupportedFormats() []string
- type APIResult
- type AuthResult
- type AuthStatus
- type CheckConfig
- type ListConfig
- type ResponseHandler
- type ResultConfig
- type SMTPSendResult
- type SingleConfig
- type StatsConfig
- type WaitNamer
Constants ¶
const NoProfilesMessage = "No authentication profiles found"
NoProfilesMessage is what the auth commands print when the configuration file holds no profile.
const ResponseHandlerKey = responseHandlerKeyType("responseHandler")
Context keys for printer instances
Variables ¶
This section is empty.
Functions ¶
func DisplayTime ¶ added in v0.3.0
DisplayTime formats t as table and plain output show times, in the local zone, for the commands that show a time outside a printer, such as in a prompt.
func DisplayWriter ¶ added in v0.3.0
DisplayWriter returns a writer that writes to w what is written to it, escaped with EscapeDisplayText, for text that comes from the API, a server or a file and is shown on the terminal. Each write must hold whole characters, as the fmt functions write. Text with color escape sequences must not go through it: escape its values instead.
func ErrorHint ¶ added in v0.3.0
ErrorHint returns what to do about err, to follow its text, or "": how long the API asked to wait, when its error answer had a Retry-After header, as a 429 or a 503 may, and what to check when the API could not be reached. An error whose text already names the wait, a WaitNamer, gets no hint.
func EscapeControl ¶ added in v0.3.0
EscapeControl returns s with each control character, C0, DEL and C1, and each character that hides or reorders text, written as a \uXXXX escape, so text from the API, a server or a file, such as a subject, cannot send escape sequences to the terminal or show other text than it holds. It is for text shown on one line: tabs and newlines are escaped too.
func EscapeDisplayText ¶ added in v0.3.0
EscapeDisplayText is EscapeControl for text shown on several lines: it keeps tabs, newlines and a carriage return that ends a line before a newline. Table and plain output, which are display formats, show every value with it; JSON and CSV output, which are data formats, print values exactly.
func GetSupportedFormats ¶
func GetSupportedFormats() []string
GetSupportedFormats returns the list of supported output formats
Types ¶
type APIResult ¶ added in v0.3.0
type APIResult struct {
Item string // what the call was for, such as a message ID or a batch label
Response any // decoded result on success
Err error // failure
Unknown bool // the call's outcome is unknown: Err says why the API had not decided it
Failures []string // parts of a successful call that failed, such as recipients the API did not accept
// Size is how many items the call is for, such as the recipients of a
// send request, each a part that Failures can name; 0 counts the call
// as one item.
Size int
}
APIResult is the outcome of one API call in a command that makes the same call for several items.
type AuthResult ¶ added in v0.3.0
type AuthResult struct {
Profile string // The profile the command acted on; empty for logout --all
Message string // What the command did, such as "Switched to profile 'production'"
}
AuthResult is the outcome of auth login, switch or logout.
type AuthStatus ¶
type AuthStatus struct {
Profile string // Currently active profile name
AccountID string // The profile's account ID
Account *responses.Account // Account information, nil when it could not be fetched
// Valid is whether the API accepted the credentials, or nil when the
// check could not tell, such as when the API could not be reached.
Valid *bool
// Error is why the check of the credentials failed, if it did.
Error string
// Note says why the account is missing from a check that passed, such
// as a key without the scope to read the account.
Note string
}
AuthStatus represents the current authentication status. It never holds the API key: like the logs, it identifies the credentials by account ID.
type CheckConfig ¶
type CheckConfig struct {
FoundMessage string // Message to show when item is found
NotFoundMessage string // Message to show when item is not found
}
CheckConfig configures how check/verification responses are displayed
type ListConfig ¶
type ListConfig struct {
SuccessMessage string // Message to show on successful retrieval
EmptyMessage string // Message to show when list is empty
// Detailed selects the detailed list view, for the items that have one
// (messages list --show-details).
Detailed bool
// ItemName names the items in the "Showing" line of a view that lists
// different items for different commands (memberships: "lists" or
// "members").
ItemName string
}
ListConfig configures how paginated list responses are displayed. The printer owns the fields of each view.
type ResponseHandler ¶
type ResponseHandler interface {
// Error handling
HandleError(err error) error
// Domain responses
HandleDomainList(response *responses.PaginatedDomainsResponse, config ListConfig) error
HandleSingleDomain(domain *responses.Domain, config SingleConfig) error
// Message responses
HandleMessageList(response *responses.PaginatedMessagesResponse, config ListConfig) error
HandleSingleMessage(message *responses.Message, config SingleConfig) error
HandleCreateMessage(response *responses.CreateMessageResponse, config ResultConfig) error
// Webhook responses
HandleWebhookList(response *responses.PaginatedWebhooksResponse, config ListConfig) error
HandleSingleWebhook(webhook *responses.Webhook, config SingleConfig) error
HandleCreateWebhook(webhook *responses.Webhook, config ResultConfig) error
HandleUpdateWebhook(webhook *responses.Webhook, config ResultConfig) error
// Route responses
HandleRouteList(response *responses.PaginatedRoutesResponse, config ListConfig) error
HandleSingleRoute(route *responses.Route, config SingleConfig) error
HandleCreateRoute(route *responses.Route, config ResultConfig) error
HandleUpdateRoute(route *responses.Route, config ResultConfig) error
// Suppression responses
HandleSuppressionList(response *responses.PaginatedSuppressionsResponse, config ListConfig) error
HandleCreateSuppression(response *responses.CreateSuppressionResponse, config ResultConfig) error
HandleCheckSuppression(response *responses.PaginatedSuppressionsResponse, config CheckConfig) error
// SMTP responses
HandleSMTPList(response *responses.PaginatedSMTPCredentialsResponse, config ListConfig) error
HandleSingleSMTP(credential *responses.SMTPCredential, config SingleConfig) error
HandleCreateSMTP(credential *responses.SMTPCredential, config ResultConfig) error
HandleSMTPSend(result *SMTPSendResult, config ResultConfig) error
// API Key responses
HandleAPIKeyList(response *responses.PaginatedAPIKeysResponse, config ListConfig) error
HandleSingleAPIKey(key *responses.APIKey, config SingleConfig) error
HandleCreateAPIKey(key *responses.APIKey, config ResultConfig) error
HandleUpdateAPIKey(key *responses.APIKey, config ResultConfig) error
// Sub-account responses
HandleSubAccountList(response *responses.PaginatedSubAccountsResponse, config ListConfig) error
HandleSingleSubAccount(subAccount *responses.SubAccount, config SingleConfig) error
HandleSubAccountUsage(response *responses.SubAccountUsageResponse, config SingleConfig) error
// Contact responses
HandleContactList(response *responses.PaginatedContactsResponse, config ListConfig) error
HandleSingleContact(contact *responses.Contact, config SingleConfig) error
HandleBatchContacts(response *responses.BatchUpsertContactsResponse, config SingleConfig) error
// List responses
HandleListsList(response *responses.PaginatedContactListsResponse, config ListConfig) error
HandleSingleList(list *responses.ContactList, config SingleConfig) error
// List member responses
HandleListMemberList(response *responses.PaginatedListContactsResponse, config ListConfig) error
HandleContactMembershipList(response *responses.PaginatedListContactsResponse, config ListConfig) error
HandleSingleListMember(member *responses.ListContact, config SingleConfig) error
HandleBatchListMembers(response *responses.BatchAddListContactsResponse, config SingleConfig) error
// Template responses
HandleTemplateList(response *responses.PaginatedTemplatesResponse, config ListConfig) error
HandleSingleTemplate(template *responses.Template, config SingleConfig) error
HandleTemplateDraft(draft *responses.TemplateDraft, config SingleConfig) error
HandleTemplateVersionList(response *responses.TemplateVersionsResponse, config ListConfig) error
HandleSingleTemplateVersion(version *responses.TemplateVersionDetail, config SingleConfig) error
// Campaign responses
HandleCampaignList(response *responses.PaginatedCampaignsResponse, config ListConfig) error
HandleSingleCampaign(campaign *responses.Campaign, config SingleConfig) error
HandleCampaignSend(send *responses.CampaignSend, config SingleConfig) error
HandleCampaignTest(test *responses.CampaignTest, config SingleConfig) error
HandleCampaignStats(stats *responses.CampaignStats, config SingleConfig) error
HandleCampaignRecipientList(response *responses.PaginatedCampaignRecipientsResponse, config ListConfig) error
// Campaign template responses
HandleCampaignTemplateList(response *responses.PaginatedCampaignTemplatesResponse, config ListConfig) error
HandleSingleCampaignTemplate(template *responses.CampaignTemplate, config SingleConfig) error
// Statistics responses
HandleDeliverabilityStats(response *responses.DeliverabilityStatisticsResponse, config StatsConfig) error
HandleBounceStats(response *responses.BounceStatisticsResponse, config StatsConfig) error
HandleDeliveryTimeStats(response *responses.DeliveryTimeStatisticsResponse, config StatsConfig) error
// Auth responses
HandleAuthResult(result AuthResult) error
HandleAuthStatus(status *AuthStatus) error
HandleAuthProfiles(profiles []string) error
// API success responses, such as deletes
HandleSuccessResponse(response *common.SuccessResponse, config ResultConfig) error
// Commands that make the same API call for several items
HandleAPIResults(results []APIResult, config ResultConfig) error
// Empty state
HandleEmpty(message string) error
// GetFormat returns the output format name
GetFormat() string
}
ResponseHandler defines the interface for type-safe output formatting with concrete types. Every method uses specific SDK response types instead of interface{} for complete type safety.
func GetResponseHandlerFromCommand ¶
func GetResponseHandlerFromCommand(cmd *cobra.Command) ResponseHandler
GetResponseHandlerFromCommand retrieves the response handler instance from the command context This is the main function commands should use to get their response handler
func NewResponseHandler ¶ added in v0.3.0
func NewResponseHandler(format string, writer, errWriter io.Writer) (ResponseHandler, error)
NewResponseHandler creates the response handler for format, in any case, or returns a validation error when the format is not supported. Results go to writer. Errors go to errWriter in table, plain and CSV formats; JSON output prints errors to writer, since they are the API's response or the CLI's error object.
type ResultConfig ¶ added in v0.3.0
type ResultConfig struct {
SuccessMessage string // Message to show on success
}
ResultConfig configures how the result of a create, update, delete or send is displayed.
type SMTPSendResult ¶
type SMTPSendResult struct {
Success bool // Whether the send or the test was successful
// MessageID is the Message-ID header of a sent message
MessageID string
Error string // The failure of a failed test
TestMode bool // Whether this was a test send
// Connected is whether a test connected to the server and read its
// greeting. A test that connected and failed failed the login, and
// Error says why.
Connected bool
// Authenticated is whether a test logged in, which it does only when
// credentials are given
Authenticated bool
}
SMTPSendResult represents the result of an SMTP send operation: a sent message, or a test that passed or failed. A send that fails returns its error without printing a result.
type SingleConfig ¶
type SingleConfig struct {
SuccessMessage string // Message to show on successful retrieval
EmptyMessage string // Message to show when item is nil
}
SingleConfig configures how single item responses are displayed
type StatsConfig ¶
type StatsConfig struct {
Title string // Title for the statistics display
}
StatsConfig configures how statistics responses are displayed
Source Files
¶
- api_results.go
- apikey.go
- auth.go
- campaign.go
- campaign_recipient.go
- campaign_stats.go
- campaign_template.go
- cmd_helper.go
- contact.go
- csv.go
- domain.go
- escape.go
- json.go
- list.go
- list_member.go
- list_page.go
- message.go
- pagination.go
- plain.go
- printer.go
- route.go
- smtp.go
- stats.go
- subaccount.go
- success_response.go
- suppression.go
- table.go
- template.go
- template_draft.go
- template_version.go
- utilities.go
- webhook.go