Get a file extension from a URL in Golang

Eli Segev
1 min readApr 28, 2022

I am presenting a quick code snippet in case anyone else needs a safe way to get the file extension from a URL using Go (Golang). The issue with URLs is that they have many “parts” that using a regular expression might not be the best possible (and readable) way to solve this with. Instead, I am using the standard Go url library to isolate the path (without the host or the query-string), and extract the extension from it.

func GetFileExtensionFromUrl(rawUrl string) (string, error) {
u, err := url.Parse(rawUrl)
if err != nil {
return "", err
}
pos := strings.LastIndex(u.Path, ".")
if pos == -1 {
return "", errors.New("couldn't find a period to indicate a file extension")
}
return u.Path[pos+1 : len(u.Path)], nil
}

Tests:

func TestGetFileExtensionFromUrl(t *testing.T) {
tests := []struct{
fullUrl, want string
wantErr bool
}{
{
fullUrl: "https://assets.somedomain.com/assets/files/mypicture.jpg?width=1000&height=600",
want: "jpg",
wantErr: false,
}, {
fullUrl: "https://google.com",
wantErr: true,
},
}

for _, tt := range tests {
t.Run(tt.fullUrl, func(t *testing.T) {
ext, err := utils.GetFileExtensionFromUrl(tt.fullUrl)
if tt.wantErr {
assert.NotNil(t, err)
} else {
assert.Nil(t, err)
assert.Equal(t, ext, tt.want)
}
})
}
}

Tip: if you need the period ( . ) along the returned extension, just change u.Path[pos+1 : len(u.Path)] to u.Path[pos : len(u.Path)]

This is inspired by https://stackoverflow.com/a/44570361

--

--