Skip to content

Instantly share code, notes, and snippets.

@pwmcintyre
Last active April 5, 2019 03:27
Show Gist options
  • Save pwmcintyre/3bdf7ae7930ec44bb182a1b6e7c66d9e to your computer and use it in GitHub Desktop.
Save pwmcintyre/3bdf7ae7930ec44bb182a1b6e7c66d9e to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/url"
"github.com/pkg/errors"
)
func main() {
fmt.Println(mustCombine("https://www.example.com/foo/bar", "example"))
fmt.Println(mustCombine("https://www.example.com/foo/bar", "/example"))
fmt.Println(mustCombine("https://www.example.com/foo/bar/", "example"))
fmt.Println(mustCombine("https://www.example.com/foo/bar/", "/example"))
}
func mustCombine(baseStr, suffixStr string) *url.URL {
u, err := combine(baseStr, suffixStr)
if err != nil {
panic(err)
}
return u
}
func combine(baseStr, suffixStr string) (*url.URL, error) {
// parse base URL
base, err := url.Parse(baseStr)
if err != nil {
return nil, errors.Wrap(err, "bad base URL")
}
// parse suffix
suffix, err := url.Parse(suffixStr)
if err != nil {
return nil, errors.Wrap(err, "bad suffix")
}
return base.ResolveReference(suffix), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment