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

--

--

--

Java, Golang, PHP, JavaScript, Databases

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Gutenberg: A JavaScript developer’s perspective

This tutorial will help you to setup the masternode on the Ubuntu 16 virtual private server and…

Add an SSL Certificate to any VPS.

Git Workflow at DeltaX

alt_text

How/when does repartitioning in spark helps to improve performance?

CLM providers leverage ALSPs to increase tech adoption & implementation

EFUN x CHAINLINK Integration

Backpack Support

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
Eli Segev

Eli Segev

Java, Golang, PHP, JavaScript, Databases

More from Medium

Learn Go: Structs

Publish a Go module in a monorepo

Using open source packages — Golang

“datediff” and “person” Go packages