Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions internal/hooks/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ package hooks
*/

func initHooks(h *Hooks) {
h.registerSDKInitHook(&ServerURLNormalizerHook{})

agentFileUploadHook := &AgentFileUploadHook{}
h.registerAfterErrorHook(agentFileUploadHook)

Expand Down
20 changes: 20 additions & 0 deletions internal/hooks/server_url_normalizer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package hooks

import (
"regexp"
"strings"
)

var schemeRegex = regexp.MustCompile(`(?i)^https?://`)

// ServerURLNormalizerHook normalizes server URLs by prepending https:// if no scheme is provided.
type ServerURLNormalizerHook struct{}

func (h *ServerURLNormalizerHook) SDKInit(baseURL string, client HTTPClient) (string, HTTPClient) {
normalized := baseURL
if !schemeRegex.MatchString(normalized) {
normalized = "https://" + normalized
}
normalized = strings.TrimRight(normalized, "/")
return normalized, client
}
65 changes: 65 additions & 0 deletions internal/hooks/server_url_normalizer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package hooks

import (
"net/http"
"testing"
)

func TestNormalizeServerURL(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "no scheme prepends https",
input: "example.glean.com",
expected: "https://example.glean.com",
},
{
name: "https preserved",
input: "https://example.glean.com",
expected: "https://example.glean.com",
},
{
name: "http localhost preserved",
input: "http://localhost:8080",
expected: "http://localhost:8080",
},
{
name: "trailing slashes stripped",
input: "https://example.glean.com///",
expected: "https://example.glean.com",
},
{
name: "url with path",
input: "https://example.glean.com/api/v1",
expected: "https://example.glean.com/api/v1",
},
{
name: "no scheme with trailing slash",
input: "example.glean.com/",
expected: "https://example.glean.com",
},
{
name: "no scheme with path",
input: "example.glean.com/api/v1",
expected: "https://example.glean.com/api/v1",
},
}

hook := &ServerURLNormalizerHook{}
client := http.DefaultClient

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, resultClient := hook.SDKInit(tt.input, client)
if result != tt.expected {
t.Errorf("expected %q, got %q", tt.expected, result)
}
if resultClient != client {
t.Error("expected client to be unchanged")
}
})
}
}