All checks were successful
CI - Build and Push / Build and Push Docker Image (push) Successful in 53s
98 lines
2.2 KiB
Go
98 lines
2.2 KiB
Go
package svc
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
|
|
"git.cialloo.com/CiallooWeb/Blog/app/internal/config"
|
|
"git.cialloo.com/CiallooWeb/Blog/app/internal/middleware"
|
|
"github.com/aws/aws-sdk-go-v2/aws"
|
|
awsconfig "github.com/aws/aws-sdk-go-v2/config"
|
|
"github.com/aws/aws-sdk-go-v2/credentials"
|
|
"github.com/aws/aws-sdk-go-v2/service/s3"
|
|
_ "github.com/lib/pq"
|
|
"github.com/zeromicro/go-zero/rest"
|
|
)
|
|
|
|
type ServiceContext struct {
|
|
Config config.Config
|
|
|
|
SuperAdminAuthMiddleware rest.Middleware
|
|
|
|
S3Client *s3.Client
|
|
DB *sql.DB
|
|
}
|
|
|
|
func NewServiceContext(c config.Config) *ServiceContext {
|
|
return &ServiceContext{
|
|
Config: c,
|
|
|
|
SuperAdminAuthMiddleware: middleware.NewSuperAdminAuthMiddleware(c).Handle,
|
|
|
|
S3Client: initS3Client(c.S3),
|
|
DB: initDatabase(c.Database),
|
|
}
|
|
}
|
|
|
|
func initDatabase(dbConfig config.DatabaseConfig) *sql.DB {
|
|
db, err := sql.Open("postgres", dbConfig.DSN)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
// Verify connection
|
|
if err := db.Ping(); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return db
|
|
}
|
|
|
|
func initS3Client(s3Config config.S3Config) *s3.Client {
|
|
cfg, err := awsconfig.LoadDefaultConfig(context.Background(),
|
|
awsconfig.WithRegion(s3Config.Region),
|
|
awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
|
|
s3Config.AccessKeyID,
|
|
s3Config.SecretAccessKey,
|
|
"",
|
|
)),
|
|
)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
client := s3.NewFromConfig(cfg, func(o *s3.Options) {
|
|
o.BaseEndpoint = aws.String(s3Config.Endpoint)
|
|
o.UsePathStyle = true
|
|
})
|
|
|
|
// Set bucket policy for public read access
|
|
setBucketPublicReadPolicy(client, s3Config.Bucket)
|
|
|
|
return client
|
|
}
|
|
|
|
func setBucketPublicReadPolicy(client *s3.Client, bucket string) {
|
|
policy := `{
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{
|
|
"Effect": "Allow",
|
|
"Principal": "*",
|
|
"Action": "s3:GetObject",
|
|
"Resource": "arn:aws:s3:::` + bucket + `/*"
|
|
}
|
|
]
|
|
}`
|
|
|
|
_, err := client.PutBucketPolicy(context.Background(), &s3.PutBucketPolicyInput{
|
|
Bucket: aws.String(bucket),
|
|
Policy: aws.String(policy),
|
|
})
|
|
if err != nil {
|
|
// Log error but don't panic - bucket might already have the policy
|
|
// or the user might not have permission to set policies
|
|
println("Warning: Failed to set bucket policy:", err.Error())
|
|
}
|
|
}
|