How to concatenate paths for api request?


When I write an API client, I have a problem with using path.Join.
My API client needs to concatenate a base path and a subpath per each API call.

I don’t want to worry about multiple slashes, use path.Join.
However, I found path.Join remove trailing slash. (Please see below code.)
The last slash is important for API server that I use.

Is there good way for concatenate base path and subpath for API clients?

package main

import (

func main() {
	u, err := url.Parse("http://path:8080/api/v1/")
	if err != nil {
		panic("invalid url")

	u.Path = path.Join(u.Path, "/somepath/")
	fmt.Printf("%s\n", u.Path) // must be /api/v1/somepath/

Internally, Join calls Clean. According to the source code comments, Clean appends a slash if the path is absolute. (Remember, the path package is about file system paths.)
However, I was not able to confirm this after modifying your playground code so that Join receives an absolute path. (path.Join("/" + u.Path(...), ...) still returns a path without trailing slash.)

So the simple solution is to add the trailing slash through string concatenation: path.Join(...) + "/".
To be absolutely sure you don’t end up with a double trailing slash, you can apply strings.Trim to the result of Join before appending the slash.


Thank you for the pointer to the source code.

path.Clean is useful, but not customizable.
So, I decide to use string concatenation( path.Join(…) + “/” ) if the subpath has a / suffix (checked by HasSuffix).


1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.