Documentation
¶
Overview ¶
Package usps provides a lightweight, production-grade Go client library for the USPS Addresses 3.0 REST API and OAuth 2.0 API.
The package implements all three USPS Addresses 3.0 API endpoints:
- Address Standardization (GetAddress)
- City/State Lookup (GetCityState)
- ZIP Code Lookup (GetZIPCode)
And the USPS OAuth 2.0 API endpoints:
- Token Generation (PostToken) - supports Client Credentials, Refresh Token, and Authorization Code grants
- Token Revocation (PostRevoke)
Quick Start ¶
The easiest way to use the library is with the convenience function that creates a client with automatic OAuth token management:
client := usps.NewClientWithOAuth("client-id", "client-secret")
Alternatively, create the provider and client separately:
tokenProvider := usps.NewOAuthTokenProvider("client-id", "client-secret")
client := usps.NewClient(tokenProvider)
Standardize an address:
req := &models.AddressRequest{
StreetAddress: "123 Main St",
City: "New York",
State: "NY",
}
resp, err := client.GetAddress(context.Background(), req)
Look up city and state by ZIP code:
req := &models.CityStateRequest{ZIPCode: "10001"}
resp, err := client.GetCityState(context.Background(), req)
Look up ZIP code by address:
req := &models.ZIPCodeRequest{
StreetAddress: "123 Main St",
City: "New York",
State: "NY",
}
resp, err := client.GetZIPCode(context.Background(), req)
OAuth Authentication ¶
The simplest approach is to use the convenience functions:
client := usps.NewClientWithOAuth("client-id", "client-secret")
// Or for testing environment:
client := usps.NewTestClientWithOAuth("client-id", "client-secret")
The library also provides automatic OAuth token management via OAuthTokenProvider:
tokenProvider := usps.NewOAuthTokenProvider(
"your-client-id",
"your-client-secret",
usps.WithOAuthScopes("addresses tracking"),
usps.WithTokenRefreshBuffer(10 * time.Minute),
)
client := usps.NewClient(tokenProvider)
The OAuthTokenProvider automatically:
- Acquires tokens using client credentials flow
- Caches tokens to minimize API calls
- Refreshes tokens before expiration (default: 5 minutes before)
- Handles concurrent access safely
For manual token management, use OAuthClient:
oauthClient := usps.NewOAuthClient()
req := &models.ClientCredentials{
GrantType: "client_credentials",
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
Scope: "addresses tracking labels",
}
result, err := oauthClient.PostToken(context.Background(), req)
Access tokens expire after 8 hours. Refresh tokens can be used to obtain new access tokens:
req := &models.RefreshTokenCredentials{
GrantType: "refresh_token",
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
RefreshToken: "your-refresh-token",
}
result, err := oauthClient.PostToken(context.Background(), req)
Revoke a refresh token when no longer needed:
req := &models.TokenRevokeRequest{
Token: "refresh-token-to-revoke",
TokenTypeHint: "refresh_token",
}
err := oauthClient.PostRevoke(context.Background(), "client-id", "client-secret", req)
For static tokens (not recommended for production), use StaticTokenProvider:
tokenProvider := usps.NewStaticTokenProvider("your-oauth-token")
client := usps.NewClient(tokenProvider)
Configuration ¶
The client can be configured with various options:
client := usps.NewClient(
tokenProvider,
usps.WithTimeout(60 * time.Second),
usps.WithBaseURL("https://custom.url.com"),
)
For testing, use the test environment:
client := usps.NewTestClient(tokenProvider) oauthClient := usps.NewOAuthTestClient()
Error Handling ¶
API errors are returned as *APIError with detailed error information:
resp, err := client.GetAddress(ctx, req)
if err != nil {
if apiErr, ok := err.(*usps.APIError); ok {
fmt.Printf("API Error: %s\n", apiErr.ErrorMessage.Error.Message)
}
return
}
OAuth errors are returned as *OAuthError:
result, err := oauthClient.PostToken(ctx, req)
if err != nil {
if oauthErr, ok := err.(*usps.OAuthError); ok {
fmt.Printf("OAuth Error: %s\n", oauthErr.ErrorMessage.Error)
}
return
}
For more information, see:
- Addresses API: https://developers.usps.com/addressesv3
- OAuth API: https://developers.usps.com/oauth2v3
Index ¶
- Constants
- type APIError
- type AddressResult
- type BulkConfig
- type BulkProcessor
- func (bp *BulkProcessor) ProcessAddresses(ctx context.Context, requests []*models.AddressRequest) []*AddressResult
- func (bp *BulkProcessor) ProcessCityStates(ctx context.Context, requests []*models.CityStateRequest) []*CityStateResult
- func (bp *BulkProcessor) ProcessZIPCodes(ctx context.Context, requests []*models.ZIPCodeRequest) []*ZIPCodeResult
- type CityStateResult
- type Client
- func NewClient(tokenProvider TokenProvider, opts ...Option) *Client
- func NewClientWithOAuth(clientID, clientSecret string, opts ...OAuthTokenOption) *Client
- func NewTestClient(tokenProvider TokenProvider, opts ...Option) *Client
- func NewTestClientWithOAuth(clientID, clientSecret string, opts ...OAuthTokenOption) *Client
- func (c *Client) GetAddress(ctx context.Context, req *models.AddressRequest) (*models.AddressResponse, error)
- func (c *Client) GetCityState(ctx context.Context, req *models.CityStateRequest) (*models.CityStateResponse, error)
- func (c *Client) GetZIPCode(ctx context.Context, req *models.ZIPCodeRequest) (*models.ZIPCodeResponse, error)
- type OAuthClient
- type OAuthError
- type OAuthTokenOption
- type OAuthTokenProvider
- type Option
- type StaticTokenProvider
- type TokenProvider
- type ZIPCodeResult
Examples ¶
- BulkProcessor.ProcessAddresses
- BulkProcessor.ProcessCityStates
- BulkProcessor.ProcessZIPCodes
- Client.GetAddress
- Client.GetCityState
- Client.GetZIPCode
- DefaultBulkConfig
- NewClientWithOAuth
- NewOAuthTestClient
- NewOAuthTokenProvider
- NewOAuthTokenProvider (WithOptions)
- NewTestClient
- NewTestClientWithOAuth
- OAuthClient.PostRevoke
- OAuthClient.PostToken (ClientCredentials)
- OAuthClient.PostToken (RefreshToken)
Constants ¶
const ( // ProductionBaseURL is the base URL for the USPS production API ProductionBaseURL = "https://apis.usps.com/addresses/v3" // TestingBaseURL is the base URL for the USPS testing API TestingBaseURL = "https://apis-tem.usps.com/addresses/v3" // DefaultTimeout is the default timeout for HTTP requests DefaultTimeout = 30 * time.Second )
const ( // OAuthProductionBaseURL is the base URL for the USPS OAuth production API OAuthProductionBaseURL = "https://apis.usps.com/oauth2/v3" // OAuthTestingBaseURL is the base URL for the USPS OAuth testing API OAuthTestingBaseURL = "https://apis-tem.usps.com/oauth2/v3" )
const ( // DefaultTokenRefreshBuffer is the default time before token expiration to refresh. // Tokens are refreshed 5 minutes before they expire by default. DefaultTokenRefreshBuffer = 5 * time.Minute // MaxInvalidExpirationRetries is the maximum number of consecutive times // the provider will retry when receiving invalid token expiration (<=0). // After this limit is exceeded, GetToken will return an error. MaxInvalidExpirationRetries = 3 )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type APIError ¶
type APIError struct {
StatusCode int
ErrorMessage models.ErrorMessage
}
APIError represents an error returned by the USPS API
type AddressResult ¶
type AddressResult struct {
Index int
Request *models.AddressRequest
Response *models.AddressResponse
Error error
}
AddressResult represents the result of a bulk address validation
type BulkConfig ¶
type BulkConfig struct {
// MaxConcurrency is the maximum number of concurrent requests (default: 10)
MaxConcurrency int
// RequestsPerSecond is the rate limit for API requests (default: 10)
RequestsPerSecond int
// MaxRetries is the maximum number of retry attempts for failed requests (default: 3)
MaxRetries int
// RetryBackoff is the base duration for exponential backoff (default: 1 second)
RetryBackoff time.Duration
// ProgressCallback is called after each request completes (optional)
ProgressCallback func(completed, total int, err error)
}
BulkConfig contains configuration options for bulk operations
func DefaultBulkConfig ¶
func DefaultBulkConfig() *BulkConfig
DefaultBulkConfig returns a BulkConfig with sensible defaults
Example ¶
ExampleDefaultBulkConfig demonstrates using the default bulk configuration
client := usps.NewClientWithOAuth("client-id", "client-secret")
// Use default configuration
processor := usps.NewBulkProcessor(client, usps.DefaultBulkConfig())
requests := []*models.AddressRequest{
{StreetAddress: "475 L'Enfant Plaza SW", City: "Washington", State: "DC"},
}
results := processor.ProcessAddresses(context.Background(), requests)
fmt.Printf("Processed %d addresses\n", len(results))
Output: Processed 1 addresses
type BulkProcessor ¶
type BulkProcessor struct {
// contains filtered or unexported fields
}
BulkProcessor handles bulk operations with rate limiting and retries
func NewBulkProcessor ¶
func NewBulkProcessor(client *Client, config *BulkConfig) *BulkProcessor
NewBulkProcessor creates a new BulkProcessor with the given client and config
func (*BulkProcessor) ProcessAddresses ¶
func (bp *BulkProcessor) ProcessAddresses(ctx context.Context, requests []*models.AddressRequest) []*AddressResult
ProcessAddresses validates multiple addresses concurrently with rate limiting
Example ¶
ExampleBulkProcessor_ProcessAddresses demonstrates bulk address validation
// Create client (in production, use real credentials)
client := usps.NewClientWithOAuth("client-id", "client-secret")
// Configure bulk processor
config := &usps.BulkConfig{
MaxConcurrency: 10, // Process 10 addresses concurrently
RequestsPerSecond: 10, // Rate limit to 10 requests/second
MaxRetries: 3, // Retry failed requests up to 3 times
ProgressCallback: func(completed, total int, err error) {
fmt.Printf("Progress: %d/%d\n", completed, total)
},
}
processor := usps.NewBulkProcessor(client, config)
// Prepare requests
requests := []*models.AddressRequest{
{StreetAddress: "123 Main St", City: "New York", State: "NY"},
{StreetAddress: "456 Oak Ave", City: "Los Angeles", State: "CA"},
{StreetAddress: "789 Elm Blvd", City: "Chicago", State: "IL"},
}
// Process bulk addresses
results := processor.ProcessAddresses(context.Background(), requests)
// Handle results
for _, result := range results {
if result.Error != nil {
log.Printf("Address %d failed: %v", result.Index, result.Error)
continue
}
fmt.Printf("Standardized: %s, %s, %s %s\n",
result.Response.Address.StreetAddress,
result.Response.Address.City,
result.Response.Address.State,
result.Response.Address.ZIPCode)
}
func (*BulkProcessor) ProcessCityStates ¶
func (bp *BulkProcessor) ProcessCityStates(ctx context.Context, requests []*models.CityStateRequest) []*CityStateResult
ProcessCityStates looks up city/state for multiple ZIP codes concurrently with rate limiting
Example ¶
ExampleBulkProcessor_ProcessCityStates demonstrates bulk city/state lookup
client := usps.NewClientWithOAuth("client-id", "client-secret")
processor := usps.NewBulkProcessor(client, usps.DefaultBulkConfig())
requests := []*models.CityStateRequest{
{ZIPCode: "10001"},
{ZIPCode: "90210"},
{ZIPCode: "60601"},
}
results := processor.ProcessCityStates(context.Background(), requests)
for _, result := range results {
if result.Error != nil {
log.Printf("ZIP %s failed: %v", result.Request.ZIPCode, result.Error)
continue
}
fmt.Printf("%s: %s, %s\n",
result.Request.ZIPCode,
result.Response.City,
result.Response.State)
}
func (*BulkProcessor) ProcessZIPCodes ¶
func (bp *BulkProcessor) ProcessZIPCodes(ctx context.Context, requests []*models.ZIPCodeRequest) []*ZIPCodeResult
ProcessZIPCodes looks up ZIP codes for multiple addresses concurrently with rate limiting
Example ¶
ExampleBulkProcessor_ProcessZIPCodes demonstrates bulk ZIP code lookup
client := usps.NewClientWithOAuth("client-id", "client-secret")
// Custom configuration for high-volume processing
config := &usps.BulkConfig{
MaxConcurrency: 20, // Higher concurrency
RequestsPerSecond: 50, // Higher rate limit (if your API plan allows)
MaxRetries: 5, // More retries for critical operations
}
processor := usps.NewBulkProcessor(client, config)
requests := []*models.ZIPCodeRequest{
{StreetAddress: "123 Main St", City: "New York", State: "NY"},
{StreetAddress: "456 Oak Ave", City: "Los Angeles", State: "CA"},
}
results := processor.ProcessZIPCodes(context.Background(), requests)
for _, result := range results {
if result.Error != nil {
log.Printf("Request %d failed: %v", result.Index, result.Error)
continue
}
zip := result.Response.Address.ZIPCode
if result.Response.Address.ZIPPlus4 != nil && *result.Response.Address.ZIPPlus4 != "" {
zip = fmt.Sprintf("%s-%s", zip, *result.Response.Address.ZIPPlus4)
}
fmt.Printf("ZIP Code: %s\n", zip)
}
type CityStateResult ¶
type CityStateResult struct {
Index int
Request *models.CityStateRequest
Response *models.CityStateResponse
Error error
}
CityStateResult represents the result of a bulk city/state lookup
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the USPS API client
func NewClient ¶
func NewClient(tokenProvider TokenProvider, opts ...Option) *Client
NewClient creates a new USPS API client
func NewClientWithOAuth ¶
func NewClientWithOAuth(clientID, clientSecret string, opts ...OAuthTokenOption) *Client
NewClientWithOAuth creates a new USPS API client with automatic OAuth token management. This is a convenience function that creates an OAuthTokenProvider and a Client in one step.
The OAuth provider automatically handles token acquisition, caching, and refresh. Additional OAuth options can be passed to customize the provider behavior.
Example:
client := usps.NewClientWithOAuth("client-id", "client-secret")
Example with options:
client := usps.NewClientWithOAuth(
"client-id",
"client-secret",
usps.WithOAuthScopes("addresses tracking"),
usps.WithTokenRefreshBuffer(10 * time.Minute),
)
Example ¶
// Create a client with automatic OAuth token management in one step
client := usps.NewClientWithOAuth("your-client-id", "your-client-secret")
// Use the client - tokens are managed automatically
req := &models.AddressRequest{
StreetAddress: "123 Main St",
City: "New York",
State: "NY",
}
resp, err := client.GetAddress(context.Background(), req)
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Printf("Address: %s\n", resp.Address.StreetAddress)
func NewTestClient ¶
func NewTestClient(tokenProvider TokenProvider, opts ...Option) *Client
NewTestClient creates a new USPS API client configured for the testing environment
Example ¶
// Create a token provider with your test OAuth token
tokenProvider := usps.NewStaticTokenProvider("your-test-oauth-token")
// Create a client configured for the testing environment
client := usps.NewTestClient(tokenProvider)
req := &models.AddressRequest{
StreetAddress: "123 Test St",
City: "Test City",
State: "NY",
}
resp, err := client.GetAddress(context.Background(), req)
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Printf("Test Address: %s\n", resp.Address.StreetAddress)
func NewTestClientWithOAuth ¶
func NewTestClientWithOAuth(clientID, clientSecret string, opts ...OAuthTokenOption) *Client
NewTestClientWithOAuth creates a new USPS API client with automatic OAuth token management configured for the testing environment. This is a convenience function that combines NewOAuthTestTokenProvider and NewTestClient.
Example:
client := usps.NewTestClientWithOAuth("test-client-id", "test-client-secret")
Example ¶
// Create a test client with automatic OAuth token management
client := usps.NewTestClientWithOAuth("test-client-id", "test-client-secret")
req := &models.CityStateRequest{
ZIPCode: "10001",
}
resp, err := client.GetCityState(context.Background(), req)
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Printf("City: %s, State: %s\n", resp.City, resp.State)
func (*Client) GetAddress ¶
func (c *Client) GetAddress(ctx context.Context, req *models.AddressRequest) (*models.AddressResponse, error)
GetAddress standardizes a street address
Example ¶
// Create a token provider with your OAuth token
tokenProvider := usps.NewStaticTokenProvider("your-oauth-token")
// Create a new client
client := usps.NewClient(tokenProvider)
// Prepare the address request
req := &models.AddressRequest{
StreetAddress: "123 Main St",
City: "New York",
State: "NY",
}
// Get the standardized address
resp, err := client.GetAddress(context.Background(), req)
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Printf("Standardized Address: %s, %s, %s %s\n",
resp.Address.StreetAddress,
resp.Address.City,
resp.Address.State,
resp.Address.ZIPCode)
func (*Client) GetCityState ¶
func (c *Client) GetCityState(ctx context.Context, req *models.CityStateRequest) (*models.CityStateResponse, error)
GetCityState returns the city and state for a given ZIP code
Example ¶
// Create a token provider with your OAuth token
tokenProvider := usps.NewStaticTokenProvider("your-oauth-token")
// Create a new client
client := usps.NewClient(tokenProvider)
// Prepare the city-state request
req := &models.CityStateRequest{
ZIPCode: "10001",
}
// Get the city and state
resp, err := client.GetCityState(context.Background(), req)
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Printf("City: %s, State: %s\n", resp.City, resp.State)
func (*Client) GetZIPCode ¶
func (c *Client) GetZIPCode(ctx context.Context, req *models.ZIPCodeRequest) (*models.ZIPCodeResponse, error)
GetZIPCode returns the ZIP code for a given address
Example ¶
// Create a token provider with your OAuth token
tokenProvider := usps.NewStaticTokenProvider("your-oauth-token")
// Create a new client
client := usps.NewClient(tokenProvider)
// Prepare the ZIP code request
req := &models.ZIPCodeRequest{
StreetAddress: "123 Main St",
City: "New York",
State: "NY",
}
// Get the ZIP code
resp, err := client.GetZIPCode(context.Background(), req)
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Printf("ZIP Code: %s", resp.Address.ZIPCode)
if resp.Address.ZIPPlus4 != nil {
fmt.Printf("-%s", *resp.Address.ZIPPlus4)
}
fmt.Println()
type OAuthClient ¶
type OAuthClient struct {
// contains filtered or unexported fields
}
OAuthClient is the USPS OAuth API client for managing OAuth 2.0 tokens. It supports Client Credentials, Refresh Token, and Authorization Code grant types.
func NewOAuthClient ¶
func NewOAuthClient(opts ...Option) *OAuthClient
NewOAuthClient creates a new USPS OAuth API client configured for the production environment. Use functional options to customize the client configuration.
Example:
client := usps.NewOAuthClient() client := usps.NewOAuthClient(usps.WithTimeout(60 * time.Second))
func NewOAuthTestClient ¶
func NewOAuthTestClient(opts ...Option) *OAuthClient
NewOAuthTestClient creates a new USPS OAuth API client configured for the testing environment. This is equivalent to calling NewOAuthClient with WithBaseURL(OAuthTestingBaseURL).
Example:
client := usps.NewOAuthTestClient()
Example ¶
// Create an OAuth client configured for the testing environment
client := usps.NewOAuthTestClient()
req := &models.ClientCredentials{
GrantType: "client_credentials",
ClientID: "test-client-id",
ClientSecret: "test-client-secret",
}
result, err := client.PostToken(context.Background(), req)
if err != nil {
log.Fatalf("Error: %v", err)
}
accessTokenResp := result.(*models.ProviderAccessTokenResponse)
fmt.Printf("Test Access Token obtained (expires in %d seconds)\n", accessTokenResp.ExpiresIn)
func (*OAuthClient) PostRevoke ¶
func (c *OAuthClient) PostRevoke(ctx context.Context, clientID, clientSecret string, req *models.TokenRevokeRequest) error
PostRevoke revokes an OAuth token using HTTP Basic Authentication. This method is used to invalidate refresh tokens that are no longer needed or suspected of being compromised.
The clientID and clientSecret are used for Basic Authentication as required by the USPS OAuth API. The request specifies which token to revoke and optionally provides a hint about the token type.
Example:
req := &models.TokenRevokeRequest{
Token: "refresh-token-to-revoke",
TokenTypeHint: "refresh_token",
}
err := client.PostRevoke(ctx, "client-id", "client-secret", req)
Example ¶
// Create an OAuth client
client := usps.NewOAuthClient()
// Prepare the revoke request
req := &models.TokenRevokeRequest{
Token: "refresh-token-to-revoke",
TokenTypeHint: "refresh_token",
}
// Revoke the token
err := client.PostRevoke(context.Background(), "your-client-id", "your-client-secret", req)
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Println("Token revoked successfully")
func (*OAuthClient) PostToken ¶
func (c *OAuthClient) PostToken(ctx context.Context, req interface{}) (interface{}, error)
PostToken generates OAuth tokens based on the grant type. It supports three grant types:
- Client Credentials: Pass *models.ClientCredentials to get an access token
- Refresh Token: Pass *models.RefreshTokenCredentials to refresh an access token
- Authorization Code: Pass *models.AuthorizationCodeCredentials to exchange an auth code
The method returns either *models.ProviderAccessTokenResponse (for client credentials) or *models.ProviderTokensResponse (for grants that include a refresh token).
Access tokens are valid for 8 hours. Refresh tokens are valid for 7 days.
Example (Client Credentials):
req := &models.ClientCredentials{
GrantType: "client_credentials",
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
Scope: "addresses tracking",
}
result, err := client.PostToken(ctx, req)
if err != nil {
return err
}
accessTokenResp := result.(*models.ProviderAccessTokenResponse)
Example (Refresh Token):
req := &models.RefreshTokenCredentials{
GrantType: "refresh_token",
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
RefreshToken: "your-refresh-token",
}
result, err := client.PostToken(ctx, req)
if err != nil {
return err
}
tokensResp := result.(*models.ProviderTokensResponse)
Example (ClientCredentials) ¶
// Create an OAuth client
client := usps.NewOAuthClient()
// Prepare the client credentials request
req := &models.ClientCredentials{
GrantType: "client_credentials",
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
Scope: "addresses tracking labels",
}
// Get an access token
result, err := client.PostToken(context.Background(), req)
if err != nil {
log.Fatalf("Error: %v", err)
}
accessTokenResp := result.(*models.ProviderAccessTokenResponse)
fmt.Printf("Access Token: %s\n", accessTokenResp.AccessToken)
fmt.Printf("Expires In: %d seconds\n", accessTokenResp.ExpiresIn)
Example (RefreshToken) ¶
// Create an OAuth client
client := usps.NewOAuthClient()
// Prepare the refresh token request
req := &models.RefreshTokenCredentials{
GrantType: "refresh_token",
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
RefreshToken: "your-refresh-token",
}
// Get a new access token and refresh token
result, err := client.PostToken(context.Background(), req)
if err != nil {
log.Fatalf("Error: %v", err)
}
tokensResp := result.(*models.ProviderTokensResponse)
fmt.Printf("Access Token: %s\n", tokensResp.AccessToken)
fmt.Printf("New Refresh Token: %s\n", tokensResp.RefreshToken)
type OAuthError ¶
type OAuthError struct {
StatusCode int
ErrorMessage models.StandardErrorResponse
}
OAuthError represents an error returned by the USPS OAuth API
type OAuthTokenOption ¶
type OAuthTokenOption func(*OAuthTokenProvider)
OAuthTokenOption is a functional option for configuring OAuthTokenProvider.
func WithOAuthEnvironment ¶
func WithOAuthEnvironment(env string) OAuthTokenOption
WithOAuthEnvironment configures the OAuth environment. Use "production" (default) or "testing" to set the OAuth base URL.
func WithOAuthScopes ¶
func WithOAuthScopes(scopes string) OAuthTokenOption
WithOAuthScopes sets the OAuth scopes for token requests. Multiple scopes should be space-separated (e.g., "addresses tracking labels").
func WithRefreshTokens ¶
func WithRefreshTokens(enabled bool) OAuthTokenOption
WithRefreshTokens enables the use of refresh tokens when available. When enabled, the provider will use refresh tokens to obtain new access tokens instead of always using client credentials. This is more efficient and allows for longer-lived sessions. Default is false (always use client credentials).
func WithTokenRefreshBuffer ¶
func WithTokenRefreshBuffer(duration time.Duration) OAuthTokenOption
WithTokenRefreshBuffer sets how early before expiration to refresh the token. Default is DefaultTokenRefreshBuffer (5 minutes) before the token expires. This ensures tokens are refreshed proactively before they expire.
type OAuthTokenProvider ¶
type OAuthTokenProvider struct {
// contains filtered or unexported fields
}
OAuthTokenProvider is a TokenProvider that automatically manages OAuth 2.0 tokens. It handles token acquisition, caching, and automatic refresh before expiration. This provider is thread-safe and suitable for concurrent use in production environments.
func NewOAuthTestTokenProvider ¶
func NewOAuthTestTokenProvider(clientID, clientSecret string, opts ...OAuthTokenOption) *OAuthTokenProvider
NewOAuthTestTokenProvider creates a new OAuthTokenProvider configured for the testing environment. This is equivalent to calling NewOAuthTokenProvider with WithOAuthEnvironment("testing").
Example:
provider := usps.NewOAuthTestTokenProvider("test-client-id", "test-client-secret")
client := usps.NewTestClient(provider)
func NewOAuthTokenProvider ¶
func NewOAuthTokenProvider(clientID, clientSecret string, opts ...OAuthTokenOption) *OAuthTokenProvider
NewOAuthTokenProvider creates a new OAuthTokenProvider that automatically manages OAuth 2.0 tokens using the client credentials flow.
The provider handles:
- Initial token acquisition
- Token caching
- Automatic refresh before expiration (default: 5 minutes before expiry)
- Thread-safe concurrent access
Access tokens from USPS are valid for 8 hours. The provider will automatically refresh the token 5 minutes before expiration (configurable via WithTokenRefreshBuffer).
Example:
provider := usps.NewOAuthTokenProvider("client-id", "client-secret")
client := usps.NewClient(provider)
Example with options:
provider := usps.NewOAuthTokenProvider(
"client-id",
"client-secret",
usps.WithOAuthScopes("addresses tracking"),
usps.WithTokenRefreshBuffer(10 * time.Minute),
usps.WithOAuthEnvironment("testing"),
)
Example ¶
// Create an OAuth token provider with your client credentials
// This will automatically handle token acquisition and refresh
tokenProvider := usps.NewOAuthTokenProvider("your-client-id", "your-client-secret")
// Create a client using the OAuth token provider
client := usps.NewClient(tokenProvider)
// The token provider automatically manages tokens
req := &models.AddressRequest{
StreetAddress: "123 Main St",
City: "New York",
State: "NY",
}
resp, err := client.GetAddress(context.Background(), req)
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Printf("Address: %s\n", resp.Address.StreetAddress)
Example (WithOptions) ¶
// Create an OAuth token provider with custom options
tokenProvider := usps.NewOAuthTokenProvider(
"your-client-id",
"your-client-secret",
usps.WithOAuthScopes("addresses tracking labels"),
usps.WithTokenRefreshBuffer(10*time.Minute),
usps.WithOAuthEnvironment("testing"),
usps.WithRefreshTokens(true),
)
// Use with the USPS client
client := usps.NewClient(tokenProvider)
req := &models.CityStateRequest{
ZIPCode: "10001",
}
resp, err := client.GetCityState(context.Background(), req)
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Printf("City: %s, State: %s\n", resp.City, resp.State)
type Option ¶
type Option func(*Client)
Option is a functional option for configuring the Client
func WithBaseURL ¶
WithBaseURL sets a custom base URL for the client
func WithHTTPClient ¶
WithHTTPClient sets a custom HTTP client
func WithTimeout ¶
WithTimeout sets a custom timeout for the HTTP client
type StaticTokenProvider ¶
type StaticTokenProvider struct {
// contains filtered or unexported fields
}
StaticTokenProvider is a simple TokenProvider that returns a fixed token
func NewStaticTokenProvider ¶
func NewStaticTokenProvider(token string) *StaticTokenProvider
NewStaticTokenProvider creates a new StaticTokenProvider with the given token
type TokenProvider ¶
type TokenProvider interface {
// GetToken returns the current OAuth token
GetToken(ctx context.Context) (string, error)
}
TokenProvider is an interface for providing OAuth tokens
type ZIPCodeResult ¶
type ZIPCodeResult struct {
Index int
Request *models.ZIPCodeRequest
Response *models.ZIPCodeResponse
Error error
}
ZIPCodeResult represents the result of a bulk ZIP code lookup
Directories
¶
| Path | Synopsis |
|---|---|
|
Package models provides strongly-typed data structures for the USPS Addresses API and OAuth 2.0 API.
|
Package models provides strongly-typed data structures for the USPS Addresses API and OAuth 2.0 API. |
|
Package parser provides comprehensive parsing for free-form address entry.
|
Package parser provides comprehensive parsing for free-form address entry. |