ronantakizawa/codereview-bench huggingface dataset:
Repository: traefik/traefik
File: pkg/middlewares/redirect/redirect_scheme.go (Go)

Code before:
	}
	uri := req.RequestURI

	if match := uriRegexp.FindStringSubmatch(req.RequestURI); len(match) > 0 {
		scheme = match[1]

		if len(match[2]) > 0 {
			host = match[2]
		}

		if len(match[3]) > 0 {
			port = match[3]
		}

		uri = match[4]
	}

	if req.TLS != nil {
		scheme = schemeHTTPS
	}

	if xProto := req.Header.Get(xForwardedProto); xProto != "" {
		// X-Forwarded-Proto header can be set to ws(s) when the client sends a websocket
		// connection upgrade request whereas the request is made through the HTTP(S) protocol.
		// As this middleware supports only HTTP(S) requests, we ignore the websocket
		// protocols and converts them to the HTTP(S) protocol.
		switch strings.ToLower(xProto) {
		case "ws", "http":
			scheme = schemeHTTP
		case "wss", "https":
			scheme = schemeHTTPS
		}
	}

	if scheme == schemeHTTP && port == ":80" || scheme == schemeHTTPS && port == ":443" {
		port = ""
	}

	return strings.Join([]string{scheme, "://", host, port, uri}, "")
}


Review comment (suggestion):
```suggestion
		// When the initial request is a connection upgrade request, X-Forwarded-Proto
		// header might have been set by a previous hop to ws(s), even though the actual
		// protocol used so far is HTTP(s).
		// Given that we're in a middleware that is only used in the context of HTTP(s)
		// requests, the only possible valid schemes are one of "http" or "https", so we
		// convert back to them.		
```

Code after:
	}
	uri := req.RequestURI

	if match := uriRegexp.FindStringSubmatch(req.RequestURI); len(match) > 0 {
		scheme = match[1]

		if len(match[2]) > 0 {
			host = match[2]
		}

		if len(match[3]) > 0 {
			port = match[3]
		}

		uri = match[4]
	}

	if req.TLS != nil {
		scheme = schemeHTTPS
	}

	if xProto := req.Header.Get(xForwardedProto); xProto != "" {
		// When the initial request is a connection upgrade request,
		// X-Forwarded-Proto header might have been set by a previous hop to ws(s),
		// even though the actual protocol used so far is HTTP(s).
		// Given that we're in a middleware that is only used in the context of HTTP(s) requests,
		// the only possible valid schemes are one of "http" or "https", so we convert back to them.
		switch {
		case strings.EqualFold(xProto, "ws"):
			scheme = schemeHTTP
		case strings.EqualFold(xProto, "wss"):
			scheme = schemeHTTPS
		default:
			scheme = xProto
		}
	}

	if scheme == schemeHTTP && port == ":80" || scheme == schemeHTTPS && port == ":443" {
		port = ""
	}

	return strings.Join([]string{scheme, "://", host, port, uri}, "")
}
Repository: traefik/traefik
File: pkg/tls/certificate_store.go (Go)

Code before:
	}

	if len(matchedCerts) > 0 {
		// sort map by keys
		keys := make([]string, 0, len(matchedCerts))
		for k := range matchedCerts {
			keys = append(keys, k)
		}
		sort.Strings(keys)

		// cache best match
		c.CertCache.SetDefault(serverName, matchedCerts[keys[len(keys)-1]])
		return matchedCerts[keys[len(keys)-1]]
	}

	return nil
}

// ResetCache clears the cache in the store.
func (c CertificateStore) ResetCache() {
	if c.CertCache != nil {
		c.CertCache.Flush()
	}
}

// matchDomain returns true if the server name matches the cert domain.
// The server name, from TLS SNI, can't have trailing dots (https://datatracker.ietf.org/doc/html/rfc6066#section-3).
// This is enforced by https://github.com/golang/go/blob/d3d7998756c33f69706488cade1cd2b9b10a4c7f/src/crypto/tls/handshake_messages.go#L423-L427.
func matchDomain(serverName, certDomain string) bool {
	// TODO: assert equality after removing the trailing dots?
	if serverName == certDomain {
		return true
	}

	for len(certDomain) > 0 && certDomain[len(certDomain)-1] == '.' {
		certDomain = certDomain[:len(certDomain)-1]
	}

	labels := strings.Split(serverName, ".")
	for i := range labels {
		labels[i] = "*"
		candidate := strings.Join(labels, ".")
		if certDomain == candidate {
			return true
		}
	}
	return false
}


Review comment (suggestion):
```suggestion
// matchDomain returns whether the server name matches the cert domain.
```

Code after:
	}

	if len(matchedCerts) > 0 {
		// sort map by keys
		keys := make([]string, 0, len(matchedCerts))
		for k := range matchedCerts {
			keys = append(keys, k)
		}
		sort.Strings(keys)

		// cache best match
		c.CertCache.SetDefault(serverName, matchedCerts[keys[len(keys)-1]])
		return matchedCerts[keys[len(keys)-1]]
	}

	return nil
}

// ResetCache clears the cache in the store.
func (c CertificateStore) ResetCache() {
	if c.CertCache != nil {
		c.CertCache.Flush()
	}
}

// matchDomain returns whether the server name matches the cert domain.
// The server name, from TLS SNI, must not have trailing dots (https://datatracker.ietf.org/doc/html/rfc6066#section-3).
// This is enforced by https://github.com/golang/go/blob/d3d7998756c33f69706488cade1cd2b9b10a4c7f/src/crypto/tls/handshake_messages.go#L423-L427.
func matchDomain(serverName, certDomain string) bool {
	// TODO: assert equality after removing the trailing dots?
	if serverName == certDomain {
		return true
	}

	for len(certDomain) > 0 && certDomain[len(certDomain)-1] == '.' {
		certDomain = certDomain[:len(certDomain)-1]
	}

	labels := strings.Split(serverName, ".")
	for i := range labels {
		labels[i] = "*"
		candidate := strings.Join(labels, ".")
		if certDomain == candidate {
			return true
		}
	}
	return false
}
Repository: traefik/traefik
File: pkg/tls/certificate_store.go (Go)

Code before:

	if len(matchedCerts) > 0 {
		// sort map by keys
		keys := make([]string, 0, len(matchedCerts))
		for k := range matchedCerts {
			keys = append(keys, k)
		}
		sort.Strings(keys)

		// cache best match
		c.CertCache.SetDefault(serverName, matchedCerts[keys[len(keys)-1]])
		return matchedCerts[keys[len(keys)-1]]
	}

	return nil
}

// ResetCache clears the cache in the store.
func (c CertificateStore) ResetCache() {
	if c.CertCache != nil {
		c.CertCache.Flush()
	}
}

// matchDomain returns true if the server name matches the cert domain.
// The server name, from TLS SNI, can't have trailing dots (https://datatracker.ietf.org/doc/html/rfc6066#section-3).
// This is enforced by https://github.com/golang/go/blob/d3d7998756c33f69706488cade1cd2b9b10a4c7f/src/crypto/tls/handshake_messages.go#L423-L427.
func matchDomain(serverName, certDomain string) bool {
	// TODO: assert equality after removing the trailing dots?
	if serverName == certDomain {
		return true
	}

	for len(certDomain) > 0 && certDomain[len(certDomain)-1] == '.' {
		certDomain = certDomain[:len(certDomain)-1]
	}

	labels := strings.Split(serverName, ".")
	for i := range labels {
		labels[i] = "*"
		candidate := strings.Join(labels, ".")
		if certDomain == candidate {
			return true
		}
	}
	return false
}


Review comment (suggestion):
```suggestion
// The server name, from TLS SNI, must not have trailing dots (https://datatracker.ietf.org/doc/html/rfc6066#section-3).
```

Code after:

	if len(matchedCerts) > 0 {
		// sort map by keys
		keys := make([]string, 0, len(matchedCerts))
		for k := range matchedCerts {
			keys = append(keys, k)
		}
		sort.Strings(keys)

		// cache best match
		c.CertCache.SetDefault(serverName, matchedCerts[keys[len(keys)-1]])
		return matchedCerts[keys[len(keys)-1]]
	}

	return nil
}

// ResetCache clears the cache in the store.
func (c CertificateStore) ResetCache() {
	if c.CertCache != nil {
		c.CertCache.Flush()
	}
}

// matchDomain returns whether the server name matches the cert domain.
// The server name, from TLS SNI, must not have trailing dots (https://datatracker.ietf.org/doc/html/rfc6066#section-3).
// This is enforced by https://github.com/golang/go/blob/d3d7998756c33f69706488cade1cd2b9b10a4c7f/src/crypto/tls/handshake_messages.go#L423-L427.
func matchDomain(serverName, certDomain string) bool {
	// TODO: assert equality after removing the trailing dots?
	if serverName == certDomain {
		return true
	}

	for len(certDomain) > 0 && certDomain[len(certDomain)-1] == '.' {
		certDomain = certDomain[:len(certDomain)-1]
	}

	labels := strings.Split(serverName, ".")
	for i := range labels {
		labels[i] = "*"
		candidate := strings.Join(labels, ".")
		if certDomain == candidate {
			return true
		}
	}
	return false
}
Repository: traefik/traefik
File: pkg/tracing/datadog/datadog.go (Go)

Code before:
// SetDefaults sets the default values.
func (c *Config) SetDefaults() {
	host, ok := os.LookupEnv("DD_AGENT_HOST")
	if !ok {
		host = "localhost"
	}

	port, ok := os.LookupEnv("DD_TRACE_AGENT_PORT")
	if !ok {
		port = "8126"
	}

	c.LocalAgentHostPort = net.JoinHostPort(host, port)
}

// Setup sets up the tracer.
func (c *Config) Setup(serviceName string) (opentracing.Tracer, io.Closer, error) {
	if c.GlobalTag != "" {
		log.WithoutContext().Warn(`Datadog: option "globalTag" is deprecated, please use "globalTags" instead.`)

		parts := strings.SplitN(c.GlobalTag, ":", 2)

		key, value := parts[0], ""
		if len(parts) == 2 {
			value = parts[1]
		}

		// Don't override a tag already defined with the new option.
		if _, ok := c.GlobalTags[key]; !ok {
			if c.GlobalTags == nil {
				c.GlobalTags = make(map[string]string)
			}

			c.GlobalTags[key] = value
		}
	}

	opts := []datadog.StartOption{
		datadog.WithAgentAddr(c.LocalAgentHostPort),
		datadog.WithServiceName(serviceName),
		datadog.WithDebugMode(c.Debug),
		datadog.WithPropagator(datadog.NewPropagator(&datadog.PropagatorConfig{
			TraceHeader:    c.TraceIDHeaderName,
			ParentHeader:   c.ParentIDHeaderName,
			PriorityHeader: c.SamplingPriorityHeaderName,
			BaggagePrefix:  c.BagagePrefixHeaderName,
		})),
	}

	for k, v := range c.GlobalTags {
		opts = append(opts, datadog.WithGlobalTag(k, v))

Review comment (suggestion):
```suggestion
		key, value, _ := strings.Cut(c.GlobalTag, ":")
```

Code after:
// SetDefaults sets the default values.
func (c *Config) SetDefaults() {
	host, ok := os.LookupEnv("DD_AGENT_HOST")
	if !ok {
		host = "localhost"
	}

	port, ok := os.LookupEnv("DD_TRACE_AGENT_PORT")
	if !ok {
		port = "8126"
	}

	c.LocalAgentHostPort = net.JoinHostPort(host, port)
}

// Setup sets up the tracer.
func (c *Config) Setup(serviceName string) (opentracing.Tracer, io.Closer, error) {
	opts := []datadog.StartOption{
		datadog.WithAgentAddr(c.LocalAgentHostPort),
		datadog.WithServiceName(serviceName),
		datadog.WithDebugMode(c.Debug),
		datadog.WithPropagator(datadog.NewPropagator(&datadog.PropagatorConfig{
			TraceHeader:    c.TraceIDHeaderName,
			ParentHeader:   c.ParentIDHeaderName,
			PriorityHeader: c.SamplingPriorityHeaderName,
			BaggagePrefix:  c.BagagePrefixHeaderName,
		})),
	}

	for k, v := range c.GlobalTags {
		opts = append(opts, datadog.WithGlobalTag(k, v))
	}

	if c.GlobalTag != "" {
		log.WithoutContext().Warn(`Datadog: option "globalTag" is deprecated, please use "globalTags" instead.`)

		key, value, _ := strings.Cut(c.GlobalTag, ":")

		// Don't override a tag already defined with the new option.
		if _, ok := c.GlobalTags[key]; !ok {
			opts = append(opts, datadog.WithGlobalTag(key, value))
		}
	}

	if c.PrioritySampling {
		opts = append(opts, datadog.WithPrioritySampling())
	}
	tracer := ddtracer.New(opts...)

	// Without this, child spans are getting the NOOP tracer
	opentracing.SetGlobalTracer(tracer)
Repository: traefik/traefik
File: pkg/server/router/tcp/postgres.go (Go)

Code before:
package tcp

import (
	"bufio"
	"bytes"
	"errors"

	"github.com/traefik/traefik/v2/pkg/log"
	tcpmuxer "github.com/traefik/traefik/v2/pkg/muxer/tcp"
	"github.com/traefik/traefik/v2/pkg/tcp"
)

var (
	PostgresStartTLSReply = []byte{83}                         // S
	PostgresStartTLSMsg   = []byte{0, 0, 0, 8, 4, 210, 22, 47} // int32(8) + int32(80877103)
)

// isPostGRESql determines whether the buffer contains the Postgres STARTTLS message.
func isPostGRESql(br *bufio.Reader) (bool, error) {
	for i := 0; i < len(PostgresStartTLSMsg); i++ {
		peeked, err := br.Peek(i)
		if err != nil {
			log.WithoutContext().Errorf("Error while Peeking first bytes: %s", err)
			return false, err
		}

		if !bytes.Equal(peeked, PostgresStartTLSMsg[:i]) {
			return false, nil
		}
	}
	return true, nil
}

// servePostGreSQL serves a connection with a Postgres client negotiating a STARTTLS session.
// It handles TCP TLS routing, after accepting to start the STARTTLS session.
func (r *Router) servePostGreSQL(conn tcp.WriteCloser) {
	_, err := conn.Write(PostgresStartTLSReply)
	if err != nil {
		conn.Close()
		return
	}

	br := bufio.NewReader(conn)


Review comment (suggestion):
```suggestion
func isPostgres(br *bufio.Reader) (bool, error) {
```

Code after:
package tcp

import (
	"bufio"
	"bytes"
	"errors"
	"sync"

	"github.com/traefik/traefik/v2/pkg/log"
	tcpmuxer "github.com/traefik/traefik/v2/pkg/muxer/tcp"
	"github.com/traefik/traefik/v2/pkg/tcp"
)

var (
	PostgresStartTLSMsg   = []byte{0, 0, 0, 8, 4, 210, 22, 47} // int32(8) + int32(80877103)
	PostgresStartTLSReply = []byte{83}                         // S
)

// isPostgres determines whether the buffer contains the Postgres STARTTLS message.
func isPostgres(br *bufio.Reader) (bool, error) {
	// Peek the first 8 bytes individually to prevent blocking on peek
	// if the underlying conn does not send enough bytes.
	// It could happen if a protocol start by sending less than 8 bytes,
	// and expect a response before proceeding.
	for i := 1; i < len(PostgresStartTLSMsg)+1; i++ {
		peeked, err := br.Peek(i)
		if err != nil {
			log.WithoutContext().Errorf("Error while Peeking first bytes: %s", err)
			return false, err
		}

		if !bytes.Equal(peeked, PostgresStartTLSMsg[:i]) {
			return false, nil
		}
	}
	return true, nil
}

// servePostgres serves a connection with a Postgres client negotiating a STARTTLS session.
// It handles TCP TLS routing, after accepting to start the STARTTLS session.
func (r *Router) servePostgres(conn tcp.WriteCloser) {
	_, err := conn.Write(PostgresStartTLSReply)
	if err != nil {
		conn.Close()
Repository: traefik/traefik
File: pkg/provider/kubernetes/gateway/kubernetes.go (Go)

Code before:

	hostRegexp := "HostRegexp(`" + strings.Join(hostRegexNames, "`, `") + "`)"

	if len(res) > 0 {
		return "(" + res + " || " + hostRegexp + ")", nil
	}

	return hostRegexp, nil
}

func hostSNIRule(hostnames []v1alpha2.Hostname) (string, error) {
	matchers := map[string][]string{}
	uniqHostnames := map[v1alpha2.Hostname]struct{}{}
	for _, hostname := range hostnames {
		if len(hostname) == 0 {
			continue
		}

		if _, exists := uniqHostnames[hostname]; exists {
			continue
		}

		h := string(hostname)

		wildcard := strings.Count(h, "*")
		switch wildcard {
		case 0:
			matchers["HostSNI("] = append(matchers["HostSNI("], "`"+h+"`")
		case 1:
			if strings.HasPrefix(h, "*.") {
				matchers["HostSNIRegexp("] = append(matchers["HostSNIRegexp("], "`"+strings.Replace(h, "*.", "{subdomain:[a-zA-Z0-9-]+}.", 1)+"`")
				break
			}
			fallthrough
		default:
			return "", fmt.Errorf("invalid rule: %q", h)
		}

		uniqHostnames[hostname] = struct{}{}
	}

	if len(hostnames) == 0 || len(matchers) == 0 {
		return "HostSNI(`*`)", nil
	}

	var rules []string
	for k, v := range matchers {
		rules = append(rules, k+strings.Join(v, ",")+")")
	}

	// Sort the rules so we can write predictable unit tests and be consistent with log output

Review comment (suggestion):
If #9531 is merged, it should be the following:

```suggestion
				matchers["HostSNIRegexp("] = append(matchers["HostSNIRegexp("], "`^"+strings.Replace(regexp.QuoteMeta(h), `\*\.`, `[a-zA-Z0-9-]+\.`, 1)+"$`")
```

Code after:
	default:
		return fmt.Sprintf("(%s)", strings.Join(rules, " || ")), nil
	}
}

func hostSNIRule(hostnames []v1alpha2.Hostname) (string, error) {
	rules := make([]string, 0, len(hostnames))
	uniqHostnames := map[v1alpha2.Hostname]struct{}{}

	for _, hostname := range hostnames {
		if len(hostname) == 0 {
			continue
		}

		if _, exists := uniqHostnames[hostname]; exists {
			continue
		}

		host := string(hostname)
		uniqHostnames[hostname] = struct{}{}

		wildcard := strings.Count(host, "*")
		if wildcard == 0 {
			rules = append(rules, fmt.Sprintf("HostSNI(`%s`)", host))
			continue
		}

		if !strings.HasPrefix(host, "*.") || wildcard > 1 {
			return "", fmt.Errorf("invalid rule: %q", host)
		}

		host = strings.Replace(regexp.QuoteMeta(host), `\*\.`, `[a-zA-Z0-9-]+\.`, 1)
		rules = append(rules, fmt.Sprintf("HostSNIRegexp(`^%s$`)", host))
	}

	if len(hostnames) == 0 || len(rules) == 0 {
		return "HostSNI(`*`)", nil
	}

	return strings.Join(rules, " || "), nil
}

func extractRule(routeRule v1alpha2.HTTPRouteRule, hostRule string) (string, error) {
	var rule string
	var matchesRules []string

	for _, match := range routeRule.Matches {
		if (match.Path == nil || match.Path.Type == nil) && match.Headers == nil {
			continue
		}
Repository: traefik/traefik
File: pkg/provider/kubernetes/gateway/kubernetes_test.go (Go)

Code before:
		},
		{
			desc: "Kind is nil",
			gateway: &v1alpha2.Gateway{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "gateway",
					Namespace: "default",
				},
			},
			listener: v1alpha2.Listener{
				Name: "foo",
			},
			routeNamespace: "default",
			routeSpec: v1alpha2.CommonRouteSpec{
				ParentRefs: []v1alpha2.ParentRef{
					{
						SectionName: sectionNamePtr("bar"),
						Name:        "gateway",
						Namespace:   namespacePtr("default"),
						Group:       groupPtr(v1alpha2.GroupName),
					},
				},
			},
			expectedAttach: false,
		},
		{
			desc: "Group is nil",
			gateway: &v1alpha2.Gateway{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "gateway",
					Namespace: "default",
				},
			},
			listener: v1alpha2.Listener{
				Name: "foo",
			},
			routeNamespace: "default",
			routeSpec: v1alpha2.CommonRouteSpec{
				ParentRefs: []v1alpha2.ParentRef{
					{
						SectionName: sectionNamePtr("bar"),
						Name:        "gateway",
						Namespace:   namespacePtr("default"),
						Kind:        kindPtr("Gateway"),
					},
				},
			},
			expectedAttach: false,
		},
		{
			desc: "SectionName does not match a listener desc",

Review comment (suggestion):
If #9531 is merged, it should be the following:

```suggestion
			expectedRule: "HostSNIRegexp(`^[a-zA-Z0-9-]+\.foo$`)",
```

Code after:

func Test_hostSNIRule(t *testing.T) {
	testCases := []struct {
		desc         string
		hostnames    []v1alpha2.Hostname
		expectedRule string
		expectError  bool
	}{
		{
			desc:         "Empty",
			expectedRule: "HostSNI(`*`)",
		},
		{
			desc:         "Empty hostname",
			hostnames:    []v1alpha2.Hostname{""},
			expectedRule: "HostSNI(`*`)",
		},
		{
			desc:        "Unsupported wildcard",
			hostnames:   []v1alpha2.Hostname{"*"},
			expectError: true,
		},
		{
			desc:         "Supported wildcard",
			hostnames:    []v1alpha2.Hostname{"*.foo"},
			expectedRule: "HostSNIRegexp(`^[a-zA-Z0-9-]+\\.foo$`)",
		},
		{
			desc:        "Multiple malformed wildcard",
			hostnames:   []v1alpha2.Hostname{"*.foo.*"},
			expectError: true,
		},
		{
			desc:         "Some empty hostnames",
			hostnames:    []v1alpha2.Hostname{"foo", "", "bar"},
			expectedRule: "HostSNI(`foo`) || HostSNI(`bar`)",
		},
		{
			desc:         "Valid hostname",
			hostnames:    []v1alpha2.Hostname{"foo"},
			expectedRule: "HostSNI(`foo`)",
		},
		{
			desc:         "Multiple valid hostnames",
			hostnames:    []v1alpha2.Hostname{"foo", "bar"},
			expectedRule: "HostSNI(`foo`) || HostSNI(`bar`)",
		},
		{
			desc:         "Multiple valid hostnames with wildcard",
			hostnames:    []v1alpha2.Hostname{"bar.foo", "foo.foo", "*.foo"},
			expectedRule: "HostSNI(`bar.foo`) || HostSNI(`foo.foo`) || HostSNIRegexp(`^[a-zA-Z0-9-]+\\.foo$`)",
Repository: traefik/traefik
File: pkg/provider/kubernetes/gateway/kubernetes.go (Go)

Code before:
			continue
		}

		// https://gateway-api.sigs.k8s.io/v1alpha2/references/spec/#gateway.networking.k8s.io/v1alpha2.Hostname
		if !strings.HasPrefix(host, "*.") || wildcard > 1 {
			return "", fmt.Errorf("invalid rule: %q", host)
		}

		hostRegexNames = append(hostRegexNames, strings.Replace(host, "*.", "{subdomain:[a-zA-Z0-9-]+}.", 1))
	}

	var res string
	if len(hostNames) > 0 {
		res = "Host(`" + strings.Join(hostNames, "`, `") + "`)"
	}

	if len(hostRegexNames) == 0 {
		return res, nil
	}

	hostRegexp := "HostRegexp(`" + strings.Join(hostRegexNames, "`, `") + "`)"

	if len(res) > 0 {
		return "(" + res + " || " + hostRegexp + ")", nil
	}

	return hostRegexp, nil
}

func hostSNIRule(hostnames []v1alpha2.Hostname) (string, error) {
	matchers := map[string][]string{}
	uniqHostnames := map[v1alpha2.Hostname]struct{}{}
	for _, hostname := range hostnames {
		if len(hostname) == 0 {
			continue
		}

		if _, exists := uniqHostnames[hostname]; exists {
			continue
		}

		h := string(hostname)

		wildcard := strings.Count(h, "*")
		switch wildcard {
		case 0:
			matchers["HostSNI("] = append(matchers["HostSNI("], "`"+h+"`")
		case 1:
			if strings.HasPrefix(h, "*.") {
				matchers["HostSNIRegexp("] = append(matchers["HostSNIRegexp("], "`"+strings.Replace(h, "*.", "{subdomain:[a-zA-Z0-9-]+}.", 1)+"`")
				break

Review comment (suggestion):
For this, I would go with the approach of the [`hostRule` function](https://github.com/traefik/traefik/blob/e54ee89330a800d509da7b11b46a6ecbb331e791/pkg/provider/kubernetes/gateway/kubernetes.go#L1166-L1201) that uses one slice to hold matchers, and then build the final rule.

Code after:
		if wildcard == 0 {
			rules = append(rules, fmt.Sprintf("Host(`%s`)", host))
			continue
		}

		// https://gateway-api.sigs.k8s.io/v1alpha2/references/spec/#gateway.networking.k8s.io/v1alpha2.Hostname
		if !strings.HasPrefix(host, "*.") || wildcard > 1 {
			return "", fmt.Errorf("invalid rule: %q", host)
		}

		host = strings.Replace(regexp.QuoteMeta(host), `\*\.`, `[a-zA-Z0-9-]+\.`, 1)
		rules = append(rules, fmt.Sprintf("HostRegexp(`^%s$`)", host))
	}

	switch len(rules) {
	case 0:
		return "", nil
	case 1:
		return rules[0], nil
	default:
		return fmt.Sprintf("(%s)", strings.Join(rules, " || ")), nil
	}
}

func hostSNIRule(hostnames []v1alpha2.Hostname) (string, error) {
	rules := make([]string, 0, len(hostnames))
	uniqHostnames := map[v1alpha2.Hostname]struct{}{}

	for _, hostname := range hostnames {
		if len(hostname) == 0 {
			continue
		}

		if _, exists := uniqHostnames[hostname]; exists {
			continue
		}

		host := string(hostname)
		uniqHostnames[hostname] = struct{}{}

		wildcard := strings.Count(host, "*")
		if wildcard == 0 {
			rules = append(rules, fmt.Sprintf("HostSNI(`%s`)", host))
			continue
		}

		if !strings.HasPrefix(host, "*.") || wildcard > 1 {
			return "", fmt.Errorf("invalid rule: %q", host)
		}

		host = strings.Replace(regexp.QuoteMeta(host), `\*\.`, `[a-zA-Z0-9-]+\.`, 1)