Skip to content

Commit a9bca17

Browse files
authoredMar 3, 2025··
[confighttp] Add omitempty tag to fields (#12482)
<!--Ex. Fixing a bug - Describe the bug and how this fixes the issue. Ex. Adding a feature - Explain what this achieves.--> #### Description Depends on #12481. Note that I didn't add the tag to any fields where we set a default value. This is because the zero value is significant in these cases and omitting it from the output would cause it to be set to the default instead of the zero value. We could fix this with a custom interface implemented by our config structs, but that will have to be a separate effort, and simply using the `omitempty` tag is still an improvement for most fields. <!-- Issue number if applicable --> #### Link to tracking issue Works toward #12191
1 parent d510c86 commit a9bca17

File tree

3 files changed

+96
-27
lines changed

3 files changed

+96
-27
lines changed
 

‎.chloggen/confighttp-omitempty.yaml

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Use this changelog template to create an entry for release notes.
2+
3+
# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
4+
change_type: enhancement
5+
6+
# The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver)
7+
component: confighttp
8+
9+
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
10+
note: Add the `omitempty` mapstructure tag to struct fields
11+
12+
# One or more tracking issues or pull requests related to the change
13+
issues: [12191]
14+
15+
# (Optional) One or more lines of additional information to render under the primary note.
16+
# These lines will be padded with 2 spaces and then inserted directly into the document.
17+
# Use pipe (|) for multiline entries.
18+
subtext: This results in unset fields not being rendered when marshaling.
19+
20+
# Optional: The change log or logs in which this entry should be included.
21+
# e.g. '[user]' or '[user, api]'
22+
# Include 'user' if the change is relevant to end users.
23+
# Include 'api' if there is a change to a library API.
24+
# Default: '[user]'
25+
change_logs: [api]

‎config/confighttp/confighttp.go

+27-27
Original file line numberDiff line numberDiff line change
@@ -42,51 +42,51 @@ var defaultCompressionAlgorithms = []string{"", "gzip", "zstd", "zlib", "snappy"
4242
// ClientConfig defines settings for creating an HTTP client.
4343
type ClientConfig struct {
4444
// The target URL to send data to (e.g.: http://some.url:9411/v1/traces).
45-
Endpoint string `mapstructure:"endpoint"`
45+
Endpoint string `mapstructure:"endpoint,omitempty"`
4646

4747
// ProxyURL setting for the collector
48-
ProxyURL string `mapstructure:"proxy_url"`
48+
ProxyURL string `mapstructure:"proxy_url,omitempty"`
4949

5050
// TLSSetting struct exposes TLS client configuration.
51-
TLSSetting configtls.ClientConfig `mapstructure:"tls"`
51+
TLSSetting configtls.ClientConfig `mapstructure:"tls,omitempty"`
5252

5353
// ReadBufferSize for HTTP client. See http.Transport.ReadBufferSize.
5454
// Default is 0.
55-
ReadBufferSize int `mapstructure:"read_buffer_size"`
55+
ReadBufferSize int `mapstructure:"read_buffer_size,omitempty"`
5656

5757
// WriteBufferSize for HTTP client. See http.Transport.WriteBufferSize.
5858
// Default is 0.
59-
WriteBufferSize int `mapstructure:"write_buffer_size"`
59+
WriteBufferSize int `mapstructure:"write_buffer_size,omitempty"`
6060

6161
// Timeout parameter configures `http.Client.Timeout`.
6262
// Default is 0 (unlimited).
63-
Timeout time.Duration `mapstructure:"timeout"`
63+
Timeout time.Duration `mapstructure:"timeout,omitempty"`
6464

6565
// Additional headers attached to each HTTP request sent by the client.
6666
// Existing header values are overwritten if collision happens.
6767
// Header values are opaque since they may be sensitive.
68-
Headers map[string]configopaque.String `mapstructure:"headers"`
68+
Headers map[string]configopaque.String `mapstructure:"headers,omitempty"`
6969

7070
// Auth configuration for outgoing HTTP calls.
71-
Auth *configauth.Authentication `mapstructure:"auth"`
71+
Auth *configauth.Authentication `mapstructure:"auth,omitempty"`
7272

7373
// The compression key for supported compression types within collector.
74-
Compression configcompression.Type `mapstructure:"compression"`
74+
Compression configcompression.Type `mapstructure:"compression,omitempty"`
7575

7676
// Advanced configuration options for the Compression
77-
CompressionParams configcompression.CompressionParams `mapstructure:"compression_params"`
77+
CompressionParams configcompression.CompressionParams `mapstructure:"compression_params,omitempty"`
7878

7979
// MaxIdleConns is used to set a limit to the maximum idle HTTP connections the client can keep open.
8080
// By default, it is set to 100. Zero means no limit.
8181
MaxIdleConns int `mapstructure:"max_idle_conns"`
8282

8383
// MaxIdleConnsPerHost is used to set a limit to the maximum idle HTTP connections the host can keep open.
8484
// Default is 0 (unlimited).
85-
MaxIdleConnsPerHost int `mapstructure:"max_idle_conns_per_host"`
85+
MaxIdleConnsPerHost int `mapstructure:"max_idle_conns_per_host,omitempty"`
8686

8787
// MaxConnsPerHost limits the total number of connections per host, including connections in the dialing,
8888
// active, and idle states. Default is 0 (unlimited).
89-
MaxConnsPerHost int `mapstructure:"max_conns_per_host"`
89+
MaxConnsPerHost int `mapstructure:"max_conns_per_host,omitempty"`
9090

9191
// IdleConnTimeout is the maximum amount of time a connection will remain open before closing itself.
9292
// By default, it is set to 90 seconds.
@@ -98,25 +98,25 @@ type ClientConfig struct {
9898
// WARNING: enabling this option can result in significant overhead establishing a new HTTP(S)
9999
// connection for every request. Before enabling this option please consider whether changes
100100
// to idle connection settings can achieve your goal.
101-
DisableKeepAlives bool `mapstructure:"disable_keep_alives"`
101+
DisableKeepAlives bool `mapstructure:"disable_keep_alives,omitempty"`
102102

103103
// This is needed in case you run into
104104
// https://github.com/golang/go/issues/59690
105105
// https://github.com/golang/go/issues/36026
106106
// HTTP2ReadIdleTimeout if the connection has been idle for the configured value send a ping frame for health check
107107
// 0s means no health check will be performed.
108-
HTTP2ReadIdleTimeout time.Duration `mapstructure:"http2_read_idle_timeout"`
108+
HTTP2ReadIdleTimeout time.Duration `mapstructure:"http2_read_idle_timeout,omitempty"`
109109
// HTTP2PingTimeout if there's no response to the ping within the configured value, the connection will be closed.
110110
// If not set or set to 0, it defaults to 15s.
111-
HTTP2PingTimeout time.Duration `mapstructure:"http2_ping_timeout"`
111+
HTTP2PingTimeout time.Duration `mapstructure:"http2_ping_timeout,omitempty"`
112112
// Cookies configures the cookie management of the HTTP client.
113-
Cookies *CookiesConfig `mapstructure:"cookies"`
113+
Cookies *CookiesConfig `mapstructure:"cookies,omitempty"`
114114
}
115115

116116
// CookiesConfig defines the configuration of the HTTP client regarding cookies served by the server.
117117
type CookiesConfig struct {
118118
// Enabled if true, cookies from HTTP responses will be reused in further HTTP requests with the same server.
119-
Enabled bool `mapstructure:"enabled"`
119+
Enabled bool `mapstructure:"enabled,omitempty"`
120120
}
121121

122122
// NewDefaultClientConfig returns ClientConfig type object with
@@ -284,7 +284,7 @@ func (interceptor *headerRoundTripper) RoundTrip(req *http.Request) (*http.Respo
284284
// ServerConfig defines settings for creating an HTTP server.
285285
type ServerConfig struct {
286286
// Endpoint configures the listening address for the server.
287-
Endpoint string `mapstructure:"endpoint"`
287+
Endpoint string `mapstructure:"endpoint,omitempty"`
288288

289289
// TLSSetting struct exposes TLS client configuration.
290290
TLSSetting *configtls.ServerConfig `mapstructure:"tls"`
@@ -293,20 +293,20 @@ type ServerConfig struct {
293293
CORS *CORSConfig `mapstructure:"cors"`
294294

295295
// Auth for this receiver
296-
Auth *AuthConfig `mapstructure:"auth"`
296+
Auth *AuthConfig `mapstructure:"auth,omitempty"`
297297

298298
// MaxRequestBodySize sets the maximum request body size in bytes. Default: 20MiB.
299-
MaxRequestBodySize int64 `mapstructure:"max_request_body_size"`
299+
MaxRequestBodySize int64 `mapstructure:"max_request_body_size,omitempty"`
300300

301301
// IncludeMetadata propagates the client metadata from the incoming requests to the downstream consumers
302-
IncludeMetadata bool `mapstructure:"include_metadata"`
302+
IncludeMetadata bool `mapstructure:"include_metadata,omitempty"`
303303

304304
// Additional headers attached to each HTTP response sent to the client.
305305
// Header values are opaque since they may be sensitive.
306306
ResponseHeaders map[string]configopaque.String `mapstructure:"response_headers"`
307307

308308
// CompressionAlgorithms configures the list of compression algorithms the server can accept. Default: ["", "gzip", "zstd", "zlib", "snappy", "deflate"]
309-
CompressionAlgorithms []string `mapstructure:"compression_algorithms"`
309+
CompressionAlgorithms []string `mapstructure:"compression_algorithms,omitempty"`
310310

311311
// ReadTimeout is the maximum duration for reading the entire
312312
// request, including the body. A zero or negative value means
@@ -316,7 +316,7 @@ type ServerConfig struct {
316316
// decisions on each request body's acceptable deadline or
317317
// upload rate, most users will prefer to use
318318
// ReadHeaderTimeout. It is valid to use them both.
319-
ReadTimeout time.Duration `mapstructure:"read_timeout"`
319+
ReadTimeout time.Duration `mapstructure:"read_timeout,omitempty"`
320320

321321
// ReadHeaderTimeout is the amount of time allowed to read
322322
// request headers. The connection's read deadline is reset
@@ -360,7 +360,7 @@ type AuthConfig struct {
360360

361361
// RequestParameters is a list of parameters that should be extracted from the request and added to the context.
362362
// When a parameter is found in both the query string and the header, the value from the query string will be used.
363-
RequestParameters []string `mapstructure:"request_params"`
363+
RequestParameters []string `mapstructure:"request_params,omitempty"`
364364
}
365365

366366
// ToListener creates a net.Listener.
@@ -517,19 +517,19 @@ type CORSConfig struct {
517517
// HTTP/JSON requests to an OTLP receiver. An origin may contain a
518518
// wildcard (*) to replace 0 or more characters (e.g.,
519519
// "http://*.domain.com", or "*" to allow any origin).
520-
AllowedOrigins []string `mapstructure:"allowed_origins"`
520+
AllowedOrigins []string `mapstructure:"allowed_origins,omitempty"`
521521

522522
// AllowedHeaders sets what headers will be allowed in CORS requests.
523523
// The Accept, Accept-Language, Content-Type, and Content-Language
524524
// headers are implicitly allowed. If no headers are listed,
525525
// X-Requested-With will also be accepted by default. Include "*" to
526526
// allow any request header.
527-
AllowedHeaders []string `mapstructure:"allowed_headers"`
527+
AllowedHeaders []string `mapstructure:"allowed_headers,omitempty"`
528528

529529
// MaxAge sets the value of the Access-Control-Max-Age response header.
530530
// Set it to the number of seconds that browsers should cache a CORS
531531
// preflight response for.
532-
MaxAge int `mapstructure:"max_age"`
532+
MaxAge int `mapstructure:"max_age,omitempty"`
533533
}
534534

535535
// NewDefaultCORSConfig creates a default cross-origin resource sharing (CORS) configuration.

‎internal/e2e/confighttp_test.go

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Copyright The OpenTelemetry Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package e2e
5+
6+
import (
7+
"testing"
8+
"time"
9+
10+
"github.com/stretchr/testify/assert"
11+
"github.com/stretchr/testify/require"
12+
13+
"go.opentelemetry.io/collector/config/confighttp"
14+
"go.opentelemetry.io/collector/confmap"
15+
)
16+
17+
func TestConfmapMarshalConfigHTTP(t *testing.T) {
18+
conf := confmap.New()
19+
require.NoError(t, conf.Marshal(confighttp.NewDefaultClientConfig()))
20+
assert.Equal(t, map[string]any{
21+
"headers": map[string]any{},
22+
"idle_conn_timeout": 90 * time.Second,
23+
"max_idle_conns": 100,
24+
}, conf.ToStringMap())
25+
26+
conf = confmap.New()
27+
require.NoError(t, conf.Marshal(confighttp.NewDefaultCORSConfig()))
28+
assert.Equal(t, map[string]any{}, conf.ToStringMap())
29+
30+
conf = confmap.New()
31+
require.NoError(t, conf.Marshal(confighttp.NewDefaultServerConfig()))
32+
assert.Equal(t, map[string]any{
33+
"cors": map[string]any{},
34+
"idle_timeout": 60 * time.Second,
35+
"read_header_timeout": 60 * time.Second,
36+
"response_headers": map[string]any{},
37+
"tls": map[string]any{},
38+
"write_timeout": 30 * time.Second,
39+
}, conf.ToStringMap())
40+
41+
conf = confmap.New()
42+
require.NoError(t, conf.Marshal(confighttp.AuthConfig{}))
43+
assert.Equal(t, map[string]any{}, conf.ToStringMap())
44+
}

0 commit comments

Comments
 (0)
Please sign in to comment.