### Full Session Configuration Example Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/README.md Demonstrates a comprehensive session setup including signer, logger, user agent, request limits, HTTP tracing, and retries. Use `session.NewRetryConfig()` for default retry settings. ```go sess, _ := session.New( session.WithSigner(edgerc), session.WithLog(customLogger), session.WithUserAgent("MyApp/1.0"), session.WithRequestLimit(10), session.WithHTTPTracing(true), session.WithRetries(session.NewRetryConfig()), ) ``` -------------------------------- ### Install Akamai EdgeGrid Go SDK Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/README.md Install the SDK using the go get command. ```bash go get github.com/akamai/AkamaiOPEN-edgegrid-golang/v13 ``` -------------------------------- ### Perform a GET Request with Go SDK Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/README.md Example of how to construct and execute a simple GET request using the SDK. It demonstrates setting up the request and handling the response. ```go var result struct{} req, _ := http.NewRequest(http.MethodGet, "/path", nil) resp, err := sess.Exec(req, &result) ``` -------------------------------- ### Run Go Example Command Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/examples/README.md Command to execute Go examples. Specify the subdirectory and operation name. ```bash go run examples///.go ``` -------------------------------- ### Complete Akamai API Integration Example Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/GETTING_STARTED.md A production-ready example demonstrating credential loading, logging configuration, session setup with retries and rate limiting, API client creation, and making an API call with a timeout. Includes error handling and result processing. ```go package main import ( "context" "errors" "fmt" "log/slog" "os" "time" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/iam" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/log" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/session" ) func main() { // 1. Load credentials edgerc, err := edgegrid.New( edgegrid.WithEnv(true), // Try environment first edgegrid.WithFile("~/.edgerc"), // Fall back to file edgegrid.WithSection("default"), ) if err != nil { fmt.Printf("Failed to load credentials: %v\n", err) os.Exit(1) } // 2. Configure logging handler := log.NewSlogHandler(os.Stderr, &slog.HandlerOptions{ Level: slog.LevelInfo, }) logger := log.NewSlogAdapter(handler) // 3. Create session sess, err := session.New( session.WithSigner(edgerc), session.WithLog(logger), session.WithRequestLimit(10), session.WithRetries(session.NewRetryConfig()), session.WithHTTPTracing(false), // Set true for debugging ) if err != nil { logger.Fatalf("Failed to create session: %v", err) } // 4. Create API client client := iam.Client(sess) // 5. Make API call with timeout ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() users, err := client.ListUsers(ctx, iam.ListUsersRequest{}) if err != nil { if errors.Is(err, iam.ErrStructValidation) { logger.Error("Invalid request", "error", err) } else { logger.Error("API call failed", "error", err) } os.Exit(1) } // 6. Process results logger.Info("Retrieved users", "count", len(users)) for i, user := range users { logger.Info("User", "index", i, "login", user.Login) } } ``` -------------------------------- ### Example Configuration File with Staging Section Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/configuration.md This example demonstrates the .edgerc file format with a staging section, illustrating how to configure credentials for different environments. ```ini [default] client_secret = abcdefghijklmnopqrstuvwxyz1234567890ABCD= host = akab-abcdefghijklmnop-qrstuvwxyz123456.luna.akamaiapis.net access_token = akab-access-token-1234567890abcdefghij client_token = akab-client-token-1234567890abcdefghij [staging] client_secret = staging-secret... host = staging-host.luna.akamaiapis.net access_token = akab-staging-access-token... client_token = akab-staging-client-token... ``` -------------------------------- ### Full Custom Logger Implementation Example Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/pkg/log/README.md This example demonstrates a complete implementation of a custom logger, including all required interface methods and usage within an Akamai session. ```go package main import ( "fmt" "maps" "net/http" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/log" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/session" ) const ( TraceLevel = iota - 2 // assuming that InfoLevel is default DebugLevel InfoLevel WarnLevel ErrorLevel FatalLevel ) type CustomLogger struct { loggingLevel int key string fields log.Fields } func (l CustomLogger) Fatal(msg string, _ ...any) { if l.loggingLevel <= FatalLevel { fmt.Println(fmt.Sprintf("[FATAL] %s %s %s", l.key, l.fields.Get(), msg)) } } func (l CustomLogger) Fatalf(msg string, args ...any) { if l.loggingLevel <= FatalLevel { fmt.Println(fmt.Sprintf("[FATAL] %s %s %s", l.key, l.fields.Get(), fmt.Sprintf(msg, args))) } } func (l CustomLogger) Error(msg string, _ ...any) { if l.loggingLevel <= ErrorLevel { fmt.Println(fmt.Sprintf("[ERROR] %s %s %s", l.key, l.fields.Get(), msg)) } } func (l CustomLogger) Errorf(msg string, args ...any) { if l.loggingLevel <= ErrorLevel { fmt.Println(fmt.Sprintf("[ERROR] %s %s %s", l.key, l.fields.Get(), fmt.Sprintf(msg, args))) } } func (l CustomLogger) Warn(msg string, _ ...any) { if l.loggingLevel <= WarnLevel { fmt.Println(fmt.Sprintf("[WARN] %s %s %s", l.key, l.fields.Get(), msg)) } } func (l CustomLogger) Warnf(msg string, args ...any) { if l.loggingLevel <= WarnLevel { fmt.Println(fmt.Sprintf("[WARN] %s %s %s", l.key, l.fields.Get(), fmt.Sprintf(msg, args))) } } func (l CustomLogger) Info(msg string, _ ...any) { if l.loggingLevel <= InfoLevel { fmt.Println(fmt.Sprintf("[INFO] %s %s %s", l.key, l.fields.Get(), msg)) } } func (l CustomLogger) Infof(msg string, args ...any) { if l.loggingLevel <= InfoLevel { fmt.Println(fmt.Sprintf("[INFO] %s %s %s", l.key, l.fields.Get(), fmt.Sprintf(msg, args))) } } func (l CustomLogger) Debug(msg string, _ ...any) { if l.loggingLevel <= DebugLevel { fmt.Println(fmt.Sprintf("[DEBUG] %s %s %s", l.key, l.fields.Get(), msg)) } } func (l CustomLogger) Debugf(msg string, args ...any) { if l.loggingLevel <= DebugLevel { fmt.Println(fmt.Sprintf("[DEBUG] %s %s %s", l.key, l.fields.Get(), fmt.Sprintf(msg, args))) } } func (l CustomLogger) Trace(msg string, _ ...any) { if l.loggingLevel <= TraceLevel { fmt.Println(fmt.Sprintf("[TRACE] %s %s %s", l.key, l.fields.Get(), msg)) } } func (l CustomLogger) Tracef(msg string, args ...any) { if l.loggingLevel <= TraceLevel { fmt.Println(fmt.Sprintf("[TRACE] %s %s %s", l.key, l.fields.Get(), fmt.Sprintf(msg, args))) } } func (l CustomLogger) With(key string, fields log.Fields) log.Interface { maps.Copy(l.fields, fields) return CustomLogger{loggingLevel: l.loggingLevel, key: l.key + key, fields: l.fields} } func main() { edgerc, _ := edgegrid.New( edgegrid.WithFile("~/.edgerc"), edgegrid.WithSection("default"), ) l := CustomLogger{loggingLevel: DebugLevel, key: "MyCustomLogger", fields: map[string]interface{}{"k1": "v1"}} l1 := l.With("_Modified", map[string]interface{}{"k2": "v2"}) sess, _ := session.New( session.WithSigner(edgerc), session.WithHTTPTracing(true), ) var userProfile struct { FirstName string `json:"firstName"` LastName string `json:"lastName"` UserName string `json:"uiUserName"` TimeZone string `json:"timeZone"` Country string `json:"country"` PreferredLanguage string `json:"preferredLanguage"` SessionTimeOut *int `json:"sessionTimeOut"` } req, _ := http.NewRequest(http.MethodGet, "/identity-management/v3/user-profile", nil) req = req.WithContext(session.ContextWithOptions(req.Context(), session.WithContextLog(l1))) result, err := sess.Exec(req, &userProfile) if err != nil { fmt.Println(err) return } fmt.Println(result, userProfile) } ``` -------------------------------- ### SlogAdapter Constructor Example Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/types.md Demonstrates how to create an instance of `SlogAdapter` by first setting up a custom `slog.Handler` with specified options and then passing it to the adapter's constructor. ```go handler := log.NewSlogHandler(os.Stderr, &slog.HandlerOptions{ Level: slog.LevelDebug, }) logger := log.NewSlogAdapter(handler) ``` -------------------------------- ### Example: Using ContextWithOptions with a Custom Logger Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/session.md Shows how to create a request context with a custom logger. This allows for request-specific logging configurations. ```go customLogger := log.NewSlogAdapter(...) c := session.ContextWithOptions( context.Background(), session.WithContextLog(customLogger), ) ``` -------------------------------- ### Example Retry Configuration Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/types.md Demonstrates how to initialize a RetryConfig struct with specific retry limits, wait times, and a list of excluded endpoints using shell-style patterns. ```go config := session.RetryConfig{ RetryMax: 5, RetryWaitMin: time.Second * 1, RetryWaitMax: time.Minute * 2, ExcludedEndpoints: []string{ "/papi/*", // All PAPI paths "/beta/*", // Beta endpoints "/analytics/*", // Analytics endpoint }, } ``` -------------------------------- ### Create API Client Credentials (SDK) Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/examples/README.md Example to create new API client credentials using the SDK method. This creates a quick client with default permissions. ```go package main import ( "fmt" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/iam" ) func main() { client := iam.NewClient() resp, err := client.CreateCredentials(nil) if err != nil { fmt.Printf("Error: %v\n", err) } fmt.Printf("Response: %v\n", resp) } ``` -------------------------------- ### EdgeGrid Configuration File (.edgerc) Example Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/configuration.md This is an example of the .edgerc file format, which stores Akamai API credentials in INI format. It shows both a default and a production section. ```ini [default] client_secret = C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN= host = akab-h05tnam3wl42son7nktnlnnx-kbob3i3v.luna.akamaiapis.net access_token = akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij client_token = akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj [production] client_secret = AnotherSecret... host = production-host.luna.akamaiapis.net access_token = ... client_token = ... ``` -------------------------------- ### Log with key-value pairs and formatted strings Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/log.md Demonstrates logging messages using both key-value pairs and formatted string syntax. The default logger is used for these examples. ```go logger := log.Default() // Key-value syntax logger.Info("Processing request", "user_id", 12345, "action", "update") // Formatted syntax logger.Infof("Processing request for user %d", 12345) ``` -------------------------------- ### Sign Request with Query Parameters Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/edgegrid.md Illustrates how to sign an HTTP GET request that includes query parameters. Ensure the URL is correctly formatted before signing. ```go req, _ := http.NewRequest( http.MethodGet, "/identity-management/v3/user-profile?authGrants=true¬ifications=true", nil, ) edgerc.SignRequest(req) ``` -------------------------------- ### List API Client Credentials (SDK) Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/examples/README.md Example to list API client credentials using the SDK method. Ensure your .edgerc file is configured. ```go package main import ( "fmt" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/iam" ) func main() { client := iam.NewClient() resp, err := client.GetCredentials(nil) if err != nil { fmt.Printf("Error: %v\n", err) } fmt.Printf("Response: %v\n", resp) } ``` -------------------------------- ### Successful JSON Marshaling Example in Go Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/errors.md An example of a valid struct that can be marshaled to JSON for use with the Exec() method. Ensure all fields are JSON-serializable. ```go type RequestData struct { Name string `json:"name"` Age int `json:"age"` } data := RequestData{Name: "John", Age: 30} resp, err := sess.Exec(req, nil, data) // OK ``` -------------------------------- ### Example: Using ContextWithOptions with Custom Headers Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/session.md Demonstrates how to create a request context with custom headers and apply it to an HTTP request. This is useful for sending specific metadata with your API calls. ```go req, _ := http.NewRequest(http.MethodGet, "/identity-management/v3/user-profile", nil) ctx := session.ContextWithOptions( req.Context(), session.WithContextHeaders(customHeaders), ) req = req.WithContext(ctx) resp, _ := sess.Exec(req, &result) ``` -------------------------------- ### Create API Client Credentials (Auth Signer) Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/examples/README.md Example to create new API client credentials using the auth signer method. This creates a quick client with default permissions. ```go package main import ( "fmt" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/akamai/edgegrid" ) func main() { credential, _ := edgegrid.LoadCredentials("~/.edgerc", "default") client := edgegrid.NewClient(credential) resp, err := client.Post("/identity-management/v3/api-clients/self/credentials", nil) if err != nil { fmt.Printf("Error: %v\n", err) } fmt.Printf("Response: %s\n", resp) } ``` -------------------------------- ### EdgeGrid Configuration File Example Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/README.md Place your authentication credentials in the `~/.edgerc` file under the `[default]` section. This file is used by the library to authenticate API requests. ```ini [default] client_secret = C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN= host = akab-h05tnam3wl42son7nktnlnnx-kbob3i3v.luna.akamaiapis.net access_token = akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij client_token = akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj ``` -------------------------------- ### Valid Retry Configuration Example Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/errors.md Demonstrates a correctly configured RetryConfig struct. Ensure RetryWaitMax is not less than RetryWaitMin and excluded endpoint patterns are valid shell globs. ```go // Valid configuration retryConfig := session.RetryConfig{ RetryMax: 5, RetryWaitMin: time.Second * 1, RetryWaitMax: time.Second * 30, // Must be >= RetryWaitMin ExcludedEndpoints: []string{ "/papi/*", // Valid: * matches non-/ chars "/exact/path", // Valid: exact match }, } ``` -------------------------------- ### Create Session Retry Configuration Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/types.md Provides examples for creating a retry configuration for sessions, both using the default settings and custom values for retry attempts and wait times. ```go // Default config config := session.NewRetryConfig() // Custom config config := session.RetryConfig{ RetryMax: 5, RetryWaitMin: time.Second, RetryWaitMax: time.Minute, } sess, _ := session.New( session.WithRetries(config), ) ``` -------------------------------- ### List API Client Credentials (Auth Signer) Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/examples/README.md Example to list API client credentials using the auth signer method. Ensure your .edgerc file is configured. ```go package main import ( "fmt" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/akamai/edgegrid" ) func main() { credential, _ := edgegrid.LoadCredentials("~/.edgerc", "default") client := edgegrid.NewClient(credential) resp, err := client.Get("/identity-management/v3/api-clients/self/credentials", nil) if err != nil { fmt.Printf("Error: %v\n", err) } fmt.Printf("Response: %s\n", resp) } ``` -------------------------------- ### Initialize Session and Execute Request Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/README.md Demonstrates how to initialize an EdgeGrid session with a signer and execute an HTTP GET request to retrieve user profile information. The response is unmarshalled into a predefined struct. ```go package main import ( "fmt" "net/http" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/session" ) func main() { edgerc, _ := edgegrid.New( edgegrid.WithFile("~/.edgerc"), edgegrid.WithSection("default"), ) sess, err := session.New( session.WithSigner(edgerc), ) if err != nil { fmt.Println(err) return } var userProfile struct { FirstName string `json:"firstName"` LastName string `json:"lastName"` UserName string `json:"uiUserName"` TimeZone string `json:"timeZone"` Country string `json:"country"` PreferredLanguage string `json:"preferredLanguage"` SessionTimeOut *int `json:"sessionTimeOut"` } req, err := http.NewRequest(http.MethodGet, "/identity-management/v3/user-profile", nil) if err != nil { fmt.Println(err) return } result, err := sess.Exec(req, &userProfile) if err != nil { fmt.Println(err) return } fmt.Println(result, userProfile) } ``` -------------------------------- ### Configure Session Retries with Default Settings Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/README.md Create a new session with default retry configurations for GET requests using `session.WithRetries(session.NewRetryConfig())`. This enables automatic retries for transient network issues. ```go package main import ( "fmt" "net/http" "time" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/session" ) func main() { edgerc, _ := edgegrid.New( edgegrid.WithFile("~/.edgerc"), edgegrid.WithSection("default"), ) // The retries feature with default configuration. sess, err := session.New( session.WithSigner(edgerc), session.WithRetries(session.NewRetryConfig()), ) // The retries feature with custom configuration. ssess, err := session.New( session.WithSigner(edgerc), session.WithRetries(session.RetryConfig{ RetryMax: 5, RetryWaitMax: time.Minute * 2, RetryWaitMin: time.Second * 3, }), ) if err != nil { fmt.Println(err) return } var userProfile struct { FirstName string `json:"firstName"` LastName string `json:"lastName"` UserName string `json:"uiUserName"` TimeZone string `json:"timeZone"` Country string `json:"country"` PreferredLanguage string `json:"preferredLanguage"` SessionTimeOut *int `json:"sessionTimeOut"` } req, err := http.NewRequest(http.MethodGet, "/identity-management/v3/user-profile", nil) if err != nil { fmt.Println(err) return } result, err := sess.Exec(req, &userProfile) if err != nil { fmt.Println(err) return } fmt.Println(result, userProfile) } ``` -------------------------------- ### WithRetries Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/session.md Configures the HTTP client to automatically retry failed GET requests. Respects rate limit headers from the server. Only GET requests are retried by default. ```APIDOC ## WithRetries ### Description Option to enable automatic HTTP retries. ### Signature ```go func WithRetries(conf RetryConfig) Option ``` ### Parameters #### Path Parameters - **conf** (`RetryConfig`) - Required - Retry configuration ### Returns - `Option` ### Example ```go sess, _ := session.New( session.WithRetries(session.RetryConfig{ RetryMax: 5, RetryWaitMin: time.Second * 1, RetryWaitMax: time.Minute * 2, }), ) ``` ``` -------------------------------- ### Create Session Context with Options Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/types.md Illustrates creating a session context using ContextWithOptions, allowing customization of logging and headers. ```go ctx := session.ContextWithOptions( context.Background(), session.WithContextLog(log.Default()), session.WithContextHeaders(http.Header{}), ) ``` -------------------------------- ### Create Session from Config Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/types.md Shows how to create a new session using the session.New function, passing a configuration object that implements the Signer interface. ```go config, _ := edgegrid.New() sess, _ := session.New( session.WithSigner(config), // Signer interface ) ``` -------------------------------- ### Basic GET Request with Response Unmarshaling Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/session.md Demonstrates how to perform a basic GET request and unmarshal the JSON response into a Go struct. Ensure your ~/.edgerc file is configured. ```go package main import ( "context" "fmt" "net/http" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/session" ) func main() { edgerc, _ := edgegrid.New(edgegrid.WithFile("~/.edgerc")) sess, _ := session.New(session.WithSigner(edgerc)) var userProfile struct { FirstName string `json:"firstName"` LastName string `json:"lastName"` } req, _ := http.NewRequest(http.MethodGet, "/identity-management/v3/user-profile", nil) _, err := sess.Exec(req, &userProfile) if err != nil { fmt.Println(err) return } fmt.Printf("User: %s %s\n", userProfile.FirstName, userProfile.LastName) } ``` -------------------------------- ### Make a Simple GET Request Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/INDEX.md Executes a basic GET request to an Akamai API endpoint using the established session. Ensure the URL is correct and the session is properly configured. ```go import ( "fmt" "log" "net/http" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/config" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/session" ) func main() { cfg, err := config.NewConfig("~/.edgerc") if err != nil { log.Fatalf("Failed to load config: %v", err) } sapiSession, err := session.New(cfg) if err != nil { log.Fatalf("Failed to create session: %v", err) } req, err := http.NewRequest("GET", "https:///some/resource", nil) if err != nil { log.Fatalf("Failed to create request: %v", err) } resp, err := sapiSession.Exec(req) if err != nil { log.Fatalf("Failed to execute request: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { log.Fatalf("Request failed with status: %s", resp.Status) } fmt.Println("Request successful!") // Process the response body here } ``` -------------------------------- ### Client Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/session.md Gets the underlying HTTP client used by the session. This is useful for advanced customization or inspection of the HTTP client. ```APIDOC ## Client ### Description Gets the underlying HTTP client used by the session. ### Method `Client()` ### Returns `*http.Client` — HTTP client used by the session ### Description Returns the underlying HTTP client, useful for advanced customization or inspection. ``` -------------------------------- ### Initialize EdgeGrid with Local File Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/README.md Import the `edgegrid` package and initialize it using `edgegrid.New()`, providing the path to your `.edgerc` file and the desired section header. ```go package main import ( "fmt" "io" "net/http" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" ) func main() { edgerc, err := edgegrid.New( edgegrid.WithFile("path/to/.edgerc"), edgegrid.WithSection("section-header"), ) ... } ``` -------------------------------- ### Configure client with file and section Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/configuration.md Combine `WithFile` and `WithSection` to load credentials from a specific section in your `.edgerc` file. ```go edgegrid.New( edgegrid.WithFile("~/.edgerc"), edgegrid.WithSection("production"), ) ``` -------------------------------- ### Get Underlying HTTP Client Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/session.md Retrieves the HTTP client associated with the session. This is useful for advanced customization or inspection of the client's behavior. ```go func (s *session) Client() *http.Client ``` -------------------------------- ### Initialize IAM Client and List Users Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/overview.md Demonstrates how to initialize the IAM client using an Edgegrid configuration file and then list users. Ensure you have a valid '~/.edgerc' file configured. ```go import ( "context" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/iam" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/session" ) edgerc, _ := edgegrid.New(edgegrid.WithFile("~/.edgerc")) sess, _ := session.New(session.WithSigner(edgerc)) client := iam.Client(sess) users, err := client.ListUsers(context.Background(), iam.ListUsersRequest{})) ``` -------------------------------- ### Add Custom Headers to a Request in Go Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/README.md Example of how to add custom HTTP headers to a request. This is often used for authentication, tracking, or custom metadata. ```go req.Header.Add("X-Custom-Header", "value") ``` -------------------------------- ### Client Creation Pattern Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/overview.md Use the `Client()` function provided by each API package to create a client instance from a session. This is the generic pattern for initializing API clients. ```go // Generic pattern client := .Client(sess) ``` ```go // Examples iamc := iam.Client(sess) papiClient := papi.Client(sess) gtmClient := gtm.Client(sess) ``` -------------------------------- ### Load Configuration from .edgerc File Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/INDEX.md Demonstrates how to load API credentials and configuration from a standard .edgerc file. Ensure the file exists and is correctly formatted. ```go import ( "fmt" "log" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/config" ) func main() { cfg, err := config.NewConfig("~/.edgerc") if err != nil { log.Fatalf("Failed to load config: %v", err) } fmt.Printf("Client Token: %s\n", cfg.ClientToken) fmt.Printf("Client Secret: %s\n", cfg.ClientSecret) fmt.Printf("Access Token: %s\n", cfg.AccessToken) fmt.Printf("Host: %s\n", cfg.Host) } ``` -------------------------------- ### Include Query String Parameters in Request Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/README.md Append query string parameters to the URL path after a question mark. This example demonstrates adding multiple parameters. ```go package main import ( "fmt" "io" "net/http" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" ) func main() { edgerc, err := edgegrid.New( edgegrid.WithFile("~/.edgerc"), edgegrid.WithSection("default"), ) client := http.Client{} req, err := http.NewRequest(http.MethodGet, "/identity-management/v3/user-profile?authGrants=true¬ifications=true&actions=true", nil) ... } ``` -------------------------------- ### Load Configuration from Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/README.md This snippet shows how to load API credentials and configuration using environment variables. Set `กับการ` to true to enable this. ```go edgegrid.New( edgegrid.WithEnv(true), edgegrid.WithSection("default"), ) ``` -------------------------------- ### Handle EdgeGrid Initialization Errors in Go Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/GETTING_STARTED.md Demonstrates how to check for specific errors when initializing the EdgeGrid client, such as missing configuration files or credentials. ```go package main import ( "context" "errors" "fmt" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/iam" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/session" ) func main() { // Load credentials edgerc, err := edgegrid.New(edgegrid.WithFile("~/.edgerc")) if err != nil { if errors.Is(err, edgegrid.ErrLoadingFile) { fmt.Println("Cannot load .edgerc file") return } if errors.Is(err, edgegrid.ErrRequiredOptionEdgerc) { fmt.Println("Missing required credential in .edgerc") return } fmt.Printf("Unexpected error: %v\n", err) return } // Create session sess, err := session.New(session.WithSigner(edgerc)) if err != nil { fmt.Printf("Cannot create session: %v\n", err) return } // Make API call client := iam.Client(sess) users, err := client.ListUsers(context.Background(), iam.ListUsersRequest{}) if err != nil { if errors.Is(err, iam.ErrStructValidation) { fmt.Println("Invalid request structure") } else { fmt.Printf("API error: %v\n", err) } return } fmt.Printf("Success: Found %d users\n", len(users)) } ``` -------------------------------- ### Example: Deferring Response Body Closure Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/session.md Illustrates the use of `defer session.CloseResponseBody(resp)` to ensure the response body is closed after the function execution. This prevents resource leaks. ```go resp, _ := sess.Exec(req, &result) defer session.CloseResponseBody(resp) ``` -------------------------------- ### Load EdgeGrid Config from Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/edgegrid.md Shows how to initialize the EdgeGrid client using environment variables for credentials. This is suitable for CI/CD pipelines and server environments. ```go edgerc, err := edgegrid.New( edgegrid.WithEnv(true), edgegrid.WithSection("ccu"), ) if err != nil { fmt.Println(err) return } ``` -------------------------------- ### Load EdgeGrid Config from .edgerc File Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/edgegrid.md Demonstrates initializing the EdgeGrid client by loading credentials from a specified .edgerc file and section. This is useful for local development and testing. ```go package main import ( "fmt" "io" "net/http" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" ) func main() { edgerc, err := edgegrid.New( edgegrid.WithFile("~/.edgerc"), edgegrid.WithSection("default"), ) if err != nil { fmt.Println(err) return } client := &http.Client{} req, _ := http.NewRequest(http.MethodGet, "/identity-management/v3/user-profile", nil) req.Header.Add("Accept", "application/json") edgerc.SignRequest(req) resp, err := client.Do(req) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(string(body)) } ``` -------------------------------- ### Configure client with environment variables and fallback Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/configuration.md Prioritize environment variables for credentials using `WithEnv(true)`, falling back to a specified `.edgerc` file and section if environment variables are not found. ```go edgegrid.New( edgegrid.WithEnv(true), edgegrid.WithFile("~/.edgerc"), edgegrid.WithSection("ccu"), ) ``` -------------------------------- ### Load Configuration from Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/INDEX.md Shows how to load API credentials and configuration directly from environment variables. This is useful for containerized environments or when avoiding configuration files. ```go import ( "fmt" "log" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/config" ) func main() { // Ensure AKAMAI_CLIENT_TOKEN, AKAMAI_CLIENT_SECRET, AKAMAI_ACCESS_TOKEN, AKAMAI_HOST are set cfg, err := config.NewConfig("") // Pass empty string to load from env vars if err != nil { log.Fatalf("Failed to load config from environment: %v", err) } fmt.Printf("Client Token: %s\n", cfg.ClientToken) fmt.Printf("Host: %s\n", cfg.Host) } ``` -------------------------------- ### Get Session Logger Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/session.md Retrieves the logger instance associated with the session or context. It returns a context-specific logger if available, otherwise the session's logger, or the default logger. ```go func (s *session) Log(ctx context.Context) log.Interface ``` -------------------------------- ### Create New Session with Signer and Tracing Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/session.md Initializes a new Akamai API session, applying configuration options. If no signer is provided, it attempts to load credentials from `.edgerc`. ```go edgerc, _ := edgegrid.New( edgegrid.WithFile("~/.edgerc"), ) sess, err := session.New( session.WithSigner(edgerc), session.WithHTTPTracing(true), ) if err != nil { fmt.Println(err) return } ``` -------------------------------- ### Get Default Logger in Go Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/log.md Retrieve the currently configured global default logger. If no logger has been explicitly set, a default SlogAdapter with Info level is created and returned. ```go logger := log.Default() logger.Info("Application started") ``` -------------------------------- ### Load Configuration from Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/edgegrid.md Populates the Config with credentials from environment variables. Variable names are prefixed with AKAMAI_ and an optional section name. ```go func (c *Config) FromEnv(section string) error ``` -------------------------------- ### Handling Extra Fields During Unmarshaling in Go Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/errors.md Example demonstrating how the SDK handles response JSON with extra fields not present in the output struct. These extra fields are ignored by default. ```go // Response might have additional fields type Response struct { ID int `json:"id"` Name string `json:"name"` // Extra fields in response are ignored } resp, err := sess.Exec(req, &Response{}) ``` -------------------------------- ### Create Session with Custom Logger Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/session.md Initializes a new session with a custom logger implementation. If not specified, a default logger is used. ```go logger := log.NewSlogAdapter(log.NewSlogHandler(os.Stderr, &slog.HandlerOptions{ Level: slog.LevelDebug, })) sess, _ := session.New( session.WithLog(logger), ) ``` -------------------------------- ### Delete API Client Credentials (SDK) Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/examples/README.md Example to delete API client credentials by ID using the SDK method. Replace `credentialId` with a valid ID. Do not use active credentials. ```go package main import ( "fmt" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/iam" ) func main() { client := iam.NewClient() credentialId := "YOUR_CREDENTIAL_ID" err := client.DeleteCredentials(credentialId) if err != nil { fmt.Printf("Error: %v\n", err) } fmt.Println("Credentials deleted successfully.") } ``` -------------------------------- ### Initialize EdgeGrid Config with File and Section Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/edgegrid.md Creates a new EdgeGrid configuration by specifying the path to the .edgerc file and the desired section. This is useful when you need to load credentials from a specific configuration file and section. ```go edgerc, err := edgegrid.New( edgegrid.WithFile("~/.edgerc"), edgegrid.WithSection("default"), ) if err != nil { fmt.Println(err) return } ``` -------------------------------- ### Update API Client Credentials (SDK) Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/examples/README.md Example to update API client credentials by ID using the SDK method. Replace `credentialId` with a valid ID. Do not use active credentials. ```go package main import ( "fmt" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/iam" ) func main() { client := iam.NewClient() credentialId := "YOUR_CREDENTIAL_ID" resp, err := client.UpdateCredentials(credentialId, nil) if err != nil { fmt.Printf("Error: %v\n", err) } fmt.Printf("Response: %v\n", resp) } ``` -------------------------------- ### Initialize EdgeGrid Config with File Only Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/edgegrid.md Creates a new EdgeGrid configuration using a specified .edgerc file. This is a common way to load credentials when not using environment variables. ```go edgerc, err := edgegrid.New( edgegrid.WithFile("~/.edgerc"), ) ``` -------------------------------- ### Configure Akamai EdgeGrid Session in Go Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/overview.md Illustrates how to create a new session with custom configurations like signers, loggers, HTTP tracing, and retries. Clients created from this session will inherit these settings. ```Go sess, _ := session.New( session.WithSigner(edgerc), session.WithLog(logger), session.WithHTTPTracing(true), session.WithRetries(retryConfig), ) // All API clients created from this session use these settings iamClient := iam.Client(sess) papiClient := papi.Client(sess) ``` -------------------------------- ### Initialize EdgeGrid with Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/README.md Load credentials from environment variables by setting `edgegrid.WithEnv(true)` and optionally specifying a section header with `edgegrid.WithSection()`. The library will look for variables prefixed with `AKAMAI_` and the section header. ```go package main import ( "fmt" "io" "net/http" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" ) func main() { // Load from AKAMAI_CCU_ edgerc, err := edgegrid.New( edgegrid.WithEnv(true), edgegrid.WithSection("ccu"), ) ... } ``` -------------------------------- ### Configure Automatic HTTP Retries Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/session.md Use this option to enable automatic retries for failed GET requests. It respects rate limit headers and allows configuration of retry attempts and wait times. ```go func WithRetries(conf RetryConfig) Option ``` ```go sess, _ := session.New( session.WithRetries(session.RetryConfig{ RetryMax: 5, RetryWaitMin: time.Second * 1, RetryWaitMax: time.Minute * 2, }), ) ``` -------------------------------- ### Integrate Logging for Akamai API Calls in Go Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/GETTING_STARTED.md Shows how to set up a logger and integrate it with the session to log API requests, responses, and errors. HTTP tracing can be enabled to log detailed traffic. ```go package main import ( "context" "fmt" "log/slog" "os" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/iam" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/log" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/session" ) func main() { edgerc, _ := edgegrid.New(edgegrid.WithFile("~/.edgerc")) // Create logger handler := log.NewSlogHandler(os.Stderr, &slog.HandlerOptions{ Level: slog.LevelDebug, }) logger := log.NewSlogAdapter(handler) // Create session with logging sess, _ := session.New( session.WithSigner(edgerc), session.WithLog(logger), session.WithHTTPTracing(true), // Log HTTP traffic ) // Make API call client := iam.Client(sess) users, err := client.ListUsers(context.Background(), iam.ListUsersRequest{}) if err != nil { logger.Error("Failed to list users", "error", err) } else { logger.Info("Listed users", "count", len(users)) } } ``` -------------------------------- ### Specify Configuration Section for Edgegrid New Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/errors.md Instantiate the Edgegrid client, specifying the configuration file and the desired section name to use. ```go edgegrid.New( edgegrid.WithFile("~/.edgerc"), edgegrid.WithSection("production"), // Match actual section ) ``` -------------------------------- ### Delete API Client Credentials (Auth Signer) Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/examples/README.md Example to delete API client credentials by ID using the auth signer method. Replace `credentialId` with a valid ID. Do not use active credentials. ```go package main import ( "fmt" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/akamai/edgegrid" ) func main() { credential, _ := edgegrid.LoadCredentials("~/.edgerc", "default") client := edgegrid.NewClient(credential) credentialId := "YOUR_CREDENTIAL_ID" resp, err := client.Delete("/identity-management/v3/api-clients/self/credentials/"+credentialId) if err != nil { fmt.Printf("Error: %v\n", err) } fmt.Printf("Response: %s\n", resp) } ``` -------------------------------- ### Update API Client Credentials (Auth Signer) Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/examples/README.md Example to update API client credentials by ID using the auth signer method. Replace `credentialId` with a valid ID. Do not use active credentials. ```go package main import ( "fmt" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/akamai/edgegrid" ) func main() { credential, _ := edgegrid.LoadCredentials("~/.edgerc", "default") client := edgegrid.NewClient(credential) credentialId := "YOUR_CREDENTIAL_ID" resp, err := client.Put("/identity-management/v3/api-clients/self/credentials/"+credentialId, nil) if err != nil { fmt.Printf("Error: %v\n", err) } fmt.Printf("Response: %s\n", resp) } ``` -------------------------------- ### Custom Error Handler Middleware in Go Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/errors.md Provides an example of a custom error handler function that uses a switch statement with errors.Is to differentiate and handle various specific error types, including those from different packages. ```go func handleError(err error) { switch { case errors.Is(err, edgegrid.ErrLoadingFile): log.Fatal("Cannot load .edgerc file") case errors.Is(err, edgegrid.ErrRequiredOptionEnv): log.Fatal("Missing required environment variables") case errors.Is(err, session.ErrUnmarshaling): log.Error("Response parsing failed") default: log.Printf("Unexpected error: %v", err) } } ``` -------------------------------- ### Client Creation Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/api-reference/overview.md All API packages provide a `Client()` function that creates an API client from a Session. This function is the entry point for interacting with any specific API service. ```APIDOC ## Client Creation All API packages provide a `Client()` function that creates an API client from a Session. ### Description This function initializes and returns a client object for a specific API service, configured with the provided session. ### Usage ```go // Generic pattern client := .Client(sess) // Examples iamc := iam.Client(sess) papiClient := papi.Client(sess) gtmClient := gtm.Client(sess) ``` ### Parameters - **sess** (*Session) - Required - The session object used to authenticate and authorize API requests. ``` -------------------------------- ### Use API Package (SDK Style) Source: https://github.com/akamai/akamaiopen-edgegrid-golang/blob/master/_autodocs/GETTING_STARTED.md Leverage domain-specific API packages for idiomatic interactions with Akamai services. This provides a higher-level abstraction for common operations. ```go package main import ( "context" "fmt" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/iam" "github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/session" ) func main() { edgerc, _ := edgegrid.New(edgegrid.WithFile("~/.edgerc")) sess, _ := session.New(session.WithSigner(edgerc)) client := iam.Client(sess) users, err := client.ListUsers( context.Background(), iam.ListUsersRequest{}, ) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Found %d users\n", len(users)) } ```