Get a file extension from a URL in Golang

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
}
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)
}
})
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store