mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
feat: add S3 public endpoint configuration and complete detail HTML image URLs
This commit is contained in:
parent
2776c4d55c
commit
e86d4084f9
@ -7,6 +7,9 @@ POSTGRES_DB=ids_ecommerce
|
||||
POSTGRES_SCHEMA=product
|
||||
POSTGRES_SSLMODE=disable
|
||||
NATS_URL=nats://localhost:4222
|
||||
# Must match ids-svc-storage's public signing endpoint. It is used only when
|
||||
# returning storage-relative images embedded in product detail_html.
|
||||
S3_PUBLIC_ENDPOINT=http://localhost:9000
|
||||
|
||||
METRICS_PORT=:9102
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
|
||||
|
||||
@ -250,6 +250,7 @@ cp .env.example .env
|
||||
| `POSTGRES_SCHEMA` | `product` | 搜索路径 |
|
||||
| `POSTGRES_SSLMODE` | `disable` | SSL 模式 |
|
||||
| `NATS_URL` | `nats://localhost:4222` | 预留事件总线地址(首版查询链路不依赖) |
|
||||
| `S3_PUBLIC_ENDPOINT` | `http://localhost:9000` | 存储服务对外媒体域名;须与 `ids-svc-storage` 同值。商品详情返回时会用它补全 `/ids-storage/...` 图片地址。 |
|
||||
| `METRICS_PORT` | `:9102` | Prometheus 指标与 HTTP 健康检查监听地址 |
|
||||
| `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | OTLP HTTP trace exporter 地址 |
|
||||
| `OTEL_EXPORTER_OTLP_INSECURE` | `true` | OTLP exporter 是否使用明文连接 |
|
||||
|
||||
@ -86,7 +86,9 @@ func main() {
|
||||
}
|
||||
}()
|
||||
|
||||
productServer := server.NewProductServer(repo, idGenerator, logger, observer)
|
||||
productServer := server.NewProductServer(repo, idGenerator, logger, observer,
|
||||
server.WithDetailHTMLAssetOrigin(cfg.S3PublicEndpoint),
|
||||
)
|
||||
server.StartScheduledSaleWorker(ctx, repo, logger, time.Minute)
|
||||
|
||||
grpcServer := grpc.NewServer(
|
||||
|
||||
@ -16,6 +16,7 @@ services:
|
||||
POSTGRES_SCHEMA: ${POSTGRES_SCHEMA:-product}
|
||||
POSTGRES_SSLMODE: ${POSTGRES_SSLMODE:-disable}
|
||||
NATS_URL: nats://nats:4222
|
||||
S3_PUBLIC_ENDPOINT: "${S3_PUBLIC_ENDPOINT:-http://localhost:9000}"
|
||||
METRICS_PORT: ":9102"
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://ids-tempo:4318
|
||||
OTEL_EXPORTER_OTLP_INSECURE: "true"
|
||||
|
||||
@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
@ -21,6 +22,7 @@ const (
|
||||
defaultMetricsPort = ":9102"
|
||||
defaultOTLPEndpoint = "http://localhost:4318"
|
||||
defaultEnvironment = "development"
|
||||
defaultS3PublicEndpoint = "http://localhost:9000"
|
||||
)
|
||||
|
||||
// Config holds runtime configuration loaded from environment variables.
|
||||
@ -32,6 +34,9 @@ type Config struct {
|
||||
OTLPEndpoint string
|
||||
OTELInsecure bool
|
||||
Environment string
|
||||
// S3PublicEndpoint is the public media origin used when product rich-text
|
||||
// contains a storage-relative image URL. It must match ids-svc-storage.
|
||||
S3PublicEndpoint string
|
||||
}
|
||||
|
||||
// LoadConfig loads .env when present and assembles configuration from environment variables.
|
||||
@ -44,6 +49,10 @@ func LoadConfig() (*Config, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s3PublicEndpoint, err := publicMediaOrigin(getEnv("S3_PUBLIC_ENDPOINT", defaultS3PublicEndpoint))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid S3_PUBLIC_ENDPOINT: %w", err)
|
||||
}
|
||||
|
||||
return &Config{
|
||||
ServerPort: getEnv("SERVER_PORT", defaultServerPort),
|
||||
@ -53,9 +62,29 @@ func LoadConfig() (*Config, error) {
|
||||
OTLPEndpoint: getEnv("OTEL_EXPORTER_OTLP_ENDPOINT", defaultOTLPEndpoint),
|
||||
OTELInsecure: getEnv("OTEL_EXPORTER_OTLP_INSECURE", "true") == "true",
|
||||
Environment: getEnv("DEPLOYMENT_ENVIRONMENT", defaultEnvironment),
|
||||
S3PublicEndpoint: s3PublicEndpoint,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// publicMediaOrigin accepts an absolute HTTP(S) origin only. Relative paths,
|
||||
// credentials, queries and fragments make signed media URL rewriting ambiguous.
|
||||
func publicMediaOrigin(raw string) (string, error) {
|
||||
parsed, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||||
return "", errors.New("must use http or https")
|
||||
}
|
||||
if parsed.Host == "" {
|
||||
return "", errors.New("host is required")
|
||||
}
|
||||
if parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") {
|
||||
return "", errors.New("must be an origin without credentials, path, query, or fragment")
|
||||
}
|
||||
return strings.TrimRight(parsed.String(), "/"), nil
|
||||
}
|
||||
|
||||
func buildPostgresDSN() (string, error) {
|
||||
if dsn := os.Getenv("POSTGRES_DSN"); dsn != "" {
|
||||
return dsn, nil
|
||||
|
||||
78
internal/server/detail_html_url.go
Normal file
78
internal/server/detail_html_url.go
Normal file
@ -0,0 +1,78 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
var detailHTMLStorageImagePrefixes = []string{
|
||||
"/ids-storage/material-images/",
|
||||
"/ids-storage/catalog/",
|
||||
}
|
||||
|
||||
// completeDetailHTMLImageURLs completes only known storage-relative image
|
||||
// paths. It deliberately leaves the query string untouched because it can
|
||||
// contain a SigV4 signature whose encoding and parameter order are sensitive.
|
||||
// Invalid HTML is returned unchanged so a read response never damages data.
|
||||
func completeDetailHTMLImageURLs(raw, assetOrigin string) string {
|
||||
assetOrigin = strings.TrimRight(strings.TrimSpace(assetOrigin), "/")
|
||||
if raw == "" || assetOrigin == "" || !strings.Contains(strings.ToLower(raw), "<img") {
|
||||
return raw
|
||||
}
|
||||
|
||||
parser := html.NewTokenizer(strings.NewReader(raw))
|
||||
var output strings.Builder
|
||||
output.Grow(len(raw) + len(assetOrigin))
|
||||
changed := false
|
||||
|
||||
for {
|
||||
tokenType := parser.Next()
|
||||
if tokenType == html.ErrorToken {
|
||||
if parser.Err() == io.EOF && changed {
|
||||
return output.String()
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
rawToken := parser.Raw()
|
||||
if tokenType != html.StartTagToken && tokenType != html.SelfClosingTagToken {
|
||||
output.Write(rawToken)
|
||||
continue
|
||||
}
|
||||
|
||||
token := parser.Token()
|
||||
if !strings.EqualFold(token.Data, "img") {
|
||||
output.Write(rawToken)
|
||||
continue
|
||||
}
|
||||
|
||||
tokenChanged := false
|
||||
for index := range token.Attr {
|
||||
if !strings.EqualFold(token.Attr[index].Key, "src") {
|
||||
continue
|
||||
}
|
||||
if !isDetailHTMLStorageImagePath(token.Attr[index].Val) {
|
||||
continue
|
||||
}
|
||||
token.Attr[index].Val = assetOrigin + token.Attr[index].Val
|
||||
tokenChanged = true
|
||||
changed = true
|
||||
}
|
||||
if tokenChanged {
|
||||
output.WriteString(token.String())
|
||||
} else {
|
||||
output.Write(rawToken)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isDetailHTMLStorageImagePath(src string) bool {
|
||||
for _, prefix := range detailHTMLStorageImagePrefixes {
|
||||
if strings.HasPrefix(src, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@ -53,22 +53,40 @@ type ProductServer struct {
|
||||
idgen *idgen.Generator
|
||||
logger *zap.Logger
|
||||
observer *observability.Observer
|
||||
detailHTMLAssetOrigin string
|
||||
}
|
||||
|
||||
// ProductServerOption customizes ProductServer behavior.
|
||||
type ProductServerOption func(*ProductServer)
|
||||
|
||||
// WithDetailHTMLAssetOrigin configures the public origin used to complete
|
||||
// storage-relative image URLs in product detail_html response fields.
|
||||
func WithDetailHTMLAssetOrigin(origin string) ProductServerOption {
|
||||
return func(s *ProductServer) {
|
||||
s.detailHTMLAssetOrigin = strings.TrimRight(strings.TrimSpace(origin), "/")
|
||||
}
|
||||
}
|
||||
|
||||
// NewProductServer constructs the gRPC product service handler.
|
||||
func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Generator, logger *zap.Logger, observer *observability.Observer) *ProductServer {
|
||||
func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Generator, logger *zap.Logger, observer *observability.Observer, options ...ProductServerOption) *ProductServer {
|
||||
if logger == nil {
|
||||
logger = zap.NewNop()
|
||||
}
|
||||
if observer == nil {
|
||||
observer = observability.NewNoop(logger)
|
||||
}
|
||||
return &ProductServer{
|
||||
server := &ProductServer{
|
||||
repo: repo,
|
||||
idgen: idGenerator,
|
||||
logger: logger,
|
||||
observer: observer,
|
||||
}
|
||||
for _, option := range options {
|
||||
if option != nil {
|
||||
option(server)
|
||||
}
|
||||
}
|
||||
return server
|
||||
}
|
||||
|
||||
// CreateProduct creates a product SPU and optional SKU list.
|
||||
@ -181,7 +199,7 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc
|
||||
}
|
||||
|
||||
return &productv1.GetProductResponse{
|
||||
Product: toProtoProduct(product, skus),
|
||||
Product: s.toProtoProduct(product, skus),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@ -258,7 +276,7 @@ func (s *ProductServer) GetProductBySku(ctx context.Context, req *productv1.GetP
|
||||
}
|
||||
|
||||
return &productv1.GetProductResponse{
|
||||
Product: toProtoProduct(product, skus),
|
||||
Product: s.toProtoProduct(product, skus),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@ -440,7 +458,7 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update
|
||||
return nil, status.Errorf(codes.Internal, "load updated product: %v", err)
|
||||
}
|
||||
return &productv1.UpdateProductResponse{
|
||||
Product: toProtoProduct(updated, skus),
|
||||
Product: s.toProtoProduct(updated, skus),
|
||||
SkuChangeResult: toProtoSKUChangeResult(result),
|
||||
}, nil
|
||||
}
|
||||
@ -2564,6 +2582,14 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ProductServer) toProtoProduct(product *repository.ProductRecord, skus []repository.SKURecord) *productv1.Product {
|
||||
result := toProtoProduct(product, skus)
|
||||
if result != nil {
|
||||
result.DetailHtml = completeDetailHTMLImageURLs(result.GetDetailHtml(), s.detailHTMLAssetOrigin)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func toProtoCartItemProduct(lineID string, record repository.CartItemProductRecord) *productv1.CartItemProduct {
|
||||
result := &productv1.CartItemProduct{
|
||||
LineId: lineID,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user