1 | initial version |
Versioning can be implemented using headers in Golang by adding a custom header to the HTTP request that specifies the current version of the API. This custom header can be used to identify the version of the API being called, and the server can then use this information to determine how to handle the request.
Here's an example of how this can be done:
const apiVersionHeader = "X-API-Version"
req, err := http.NewRequest("GET", "https://example.com/path/to/api", nil)
if err != nil {
// handle error
}
req.Header.Set(apiVersionHeader, "1.0")
func apiHandler(w http.ResponseWriter, r *http.Request) {
version := r.Header.Get(apiVersionHeader)
switch version {
case "1.0":
// handle API version 1.0 request
case "2.0":
// handle API version 2.0 request
default:
// return error for unsupported version
}
}
By using custom headers to specify the API version, you can easily add and support multiple versions of your API without having to change the URL or query parameters.