From 9516f30d37bf20b9101e2f1d36d3c53095311395 Mon Sep 17 00:00:00 2001 From: Kenshi Muto Date: Wed, 23 Jul 2025 21:45:15 +0900 Subject: [PATCH] add the feature to parse URL path --- internal/metric/export.go | 15 +++++++++++++-- internal/metric/export_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/internal/metric/export.go b/internal/metric/export.go index 4b44b24..c433028 100644 --- a/internal/metric/export.go +++ b/internal/metric/export.go @@ -3,6 +3,8 @@ package metric import ( "context" "fmt" + "net/url" + "strings" "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc" "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp" @@ -31,13 +33,22 @@ func NewExporter(p *NewExporterParams) (sdkmetric.Exporter, error) { exporter, err := otlpmetricgrpc.New(context.Background(), options...) return exporter, err case "http": + if !strings.Contains(p.OTLPEndpoint, "://") { + p.OTLPEndpoint = "https://" + p.OTLPEndpoint + } + u, err := url.Parse(p.OTLPEndpoint) + if err != nil { + return nil, fmt.Errorf("invalid OTLP endpoint URL: %w", err) + } + options := []otlpmetrichttp.Option{ - otlpmetrichttp.WithEndpoint(p.OTLPEndpoint), + otlpmetrichttp.WithEndpoint(u.Host), + otlpmetrichttp.WithURLPath(u.Path), } if len(p.OTLPHeaders) > 0 { options = append(options, otlpmetrichttp.WithHeaders(p.OTLPHeaders)) } - if p.OTLPInsecure { + if p.OTLPInsecure || u.Scheme == "http" { options = append(options, otlpmetrichttp.WithInsecure()) } exporter, err := otlpmetrichttp.New(context.Background(), options...) diff --git a/internal/metric/export_test.go b/internal/metric/export_test.go index f4471a8..32527e6 100644 --- a/internal/metric/export_test.go +++ b/internal/metric/export_test.go @@ -35,6 +35,30 @@ func TestNewExporter(t *testing.T) { // TODO: test with dummy server }) + t.Run("returns otlpmetrichttp.Exporter (with scheme and custom path)", func(t *testing.T) { + t.Parallel() + params := &NewExporterParams{ + OTLPProtocol: "http", + OTLPEndpoint: "http://localhost:4318/custom/path/v1/metrics", + } + + got, err := NewExporter(params) + assert.NoError(t, err) + assert.IsType(t, got, &otlpmetrichttp.Exporter{}) + }) + + t.Run("returns otlpmetrichttp.Exporter (no scheme, with custom path)", func(t *testing.T) { + t.Parallel() + params := &NewExporterParams{ + OTLPProtocol: "http", + OTLPEndpoint: "localhost:4318/custom/path/v1/metrics", + } + + got, err := NewExporter(params) + assert.NoError(t, err) + assert.IsType(t, got, &otlpmetrichttp.Exporter{}) + }) + t.Run("returns error when unexpected protocol is passed", func(t *testing.T) { t.Parallel() params := &NewExporterParams{