Ask Your Question

Revision history [back]

click to hide/show revision 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:

  1. Define a custom header for your API version:
const apiVersionHeader = "X-API-Version"
  1. When sending a request to the server, set the custom header to the current 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")
  1. In your server code, read the custom header and determine the appropriate response based on the version:
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.