Yes, you can use the config package to manage your AWS configuration and pass it as part of the context. This can be particularly useful if you want to centralize your configuration management and make it easily accessible throughout your application.
Here’s how you can achieve this:
Using the config Package and Context
config/config.go
Create a configuration package to manage your AWS configuration.
package config
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
)
type AWSConfig struct {
Session *session.Session
}
func NewAWSConfig(region string) (*AWSConfig, error) {
sess, err := session.NewSession(&aws.Config{
Region: aws.String(region)},
)
if err != nil {
return nil, err
}
return &AWSConfig{Session: sess}, nil
}
main.go
Initiate the AWS configuration in main.go and pass it via context.
package main
import (
"context"
"log"
"net/http"
"yourapp/config"
"yourapp/uploads"
)
func main() {
// Create AWS configuration
awsConfig, err := config.NewAWSConfig("us-west-2")
if err != nil {
log.Fatalf("failed to create AWS config, %v", err)
}
// Create context with AWS configuration
ctx := context.WithValue(context.Background(), "awsConfig", awsConfig)
// Pass the context to the upload handler
uploadHandler := uploads.NewUploadHandler(ctx)
// Set up your HTTP server
http.HandleFunc("/upload", uploadHandler.HandleUpload)
log.Fatal(http.ListenAndServe(":8080", nil))
}
uploads/uploads.go
Retrieve the AWS configuration from the context in your uploads package.
package uploads
import (
"context"
"log"
"net/http"
"github.com/aws/aws-sdk-go/service/s3"
)
type UploadHandler struct {
Ctx context.Context
}
func NewUploadHandler(ctx context.Context) *UploadHandler {
return &UploadHandler{Ctx: ctx}
}
func (h *UploadHandler) HandleUpload(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Retrieve AWS configuration from context
awsConfig := h.Ctx.Value("awsConfig").(*config.AWSConfig)
// Create an S3 service client
svc := s3.New(awsConfig.Session)
// Example: Upload logic
file, header, err := r.FormFile("file")
if err != nil {
log.Printf("Error retrieving file: %v", err)
http.Error(w, "Error retrieving file", http.StatusBadRequest)
return
}
defer file.Close()
// Upload the file to S3
_, err = svc.PutObject(&s3.PutObjectInput{
Bucket: aws.String("your-bucket-name"),
Key: aws.String(header.Filename),
Body: file,
})
if err != nil {
log.Printf("Error uploading file: %v", err)
http.Error(w, "Error uploading file", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("File uploaded successfully"))
}