Created
June 17, 2021 13:23
-
-
Save v3rlly/369bb7d4bb58d61a37e23218af2fbbe1 to your computer and use it in GitHub Desktop.
Create signed request for any AWS service.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util | |
import ( | |
"net/http" | |
"strings" | |
"time" | |
"github.com/aws/aws-sdk-go/aws/credentials" | |
v4 "github.com/aws/aws-sdk-go/aws/signer/v4" | |
) | |
/* | |
Create signed request for any AWS service. | |
e.g. Managed Blockchain | |
Endpoint: | |
e.g. "https://nd-as4da74sd74a8s4d84d8s4d.ethereum.managedblockchain.us-east-1.amazonaws.com" | |
Region: | |
e.g. "us-east-1" | |
Service: | |
e.g. "managedblockchain" | |
BodyStr: | |
e.g. `{"id":1,"jsonrpc":"2.0","method":"web3_clientVersion","params":null}` | |
Headers: | |
e.g. map[string]string{"Content-Type": "application/json", "x": "y", "foo": "bar"} | |
*/ | |
func CreateClient(Endpoint string, Region string, Service string, BodyStr string, Headers map[string]string) (*http.Response, error) { | |
/* | |
Basic information for the Amazon Service "X" domain | |
*/ | |
// Parse body string to *strings.Reader | |
Body := strings.NewReader(BodyStr) | |
// Get credentials from environment variables and create the Signature Version 4 signer | |
credentials := credentials.NewEnvCredentials() | |
signer := v4.NewSigner(credentials) | |
// An HTTP client for sending the request | |
client := &http.Client{} | |
// Form the HTTP request | |
req, err := http.NewRequest(http.MethodPost, Endpoint, Body) | |
if err != nil { | |
return nil, err | |
} | |
// Trace/Debug HTTP request/response | |
// Optionally add custom HTTP Headers | |
if Headers != nil { | |
for key, value := range Headers { | |
req.Header.Add(key, value) | |
} | |
} | |
// Sign the request, send it, and print the response | |
signer.Sign(req, Body, Service, Region, time.Now()) | |
// Execute request | |
resp, err := client.Do(req) | |
if err != nil { | |
return nil, err | |
} | |
return resp, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment