I have an URL in golang. I want to add an endpoint to it (like /users) how do I add it…
- User
I have an URL in golang. I want to add an endpoint to it (like /users) how do I add it so that I can create a http request?
- Assistant
To add an endpoint like
/usersto an existing URL in Go and create an HTTP request, you can use thenet/urlpackage to safely manipulate the URL paths.Here's how you can do it:
gopackage main import ( "fmt" "net/http" "net/url" "path" ) func main() { baseURL := "https://example.com/api" // Parse the base URL u, err := url.Parse(baseURL) if err != nil { panic(err) } // Append the endpoint "/users" to the existing path u.Path = path.Join(u.Path, "users") // Create a new HTTP request with the full URL req, err := http.NewRequest("GET", u.String(), nil) if err != nil { panic(err) } fmt.Println("Final URL:", req.URL.String()) // Output: Final URL: https://example.com/api/users } - User
Can I create a query first and modify query.URL?
- Assistant
It's better to create and modify the query parameters using the
url.Valuestype obtained via theURL.Query()method, but you cannot replace the entireURLfield of aurl.URLstruct because it's part of that struct itself.Let me clarify this with example code showing how to add query parameters to a URL and modify the URL's path:
go