Go Lang Echo Framework Header Based API Versioning
Today we will share how you can implement header based API versioning using Go lang echo framework. First, we will discuss the different way of API versioning Which can be done in echo framework. Before proceeding further make sure you already know the basics of Go Lang as well as installed Go Lang in the system unless can proceed with the following links to learn more about Go programming language
URL Based API Versioning
Most commonly used approach is URL based API versioning. This solution often uses URI routing to point to a specific version of the API.
Example:
- https://api.v1.onexlab.io/todo
- https://api.onexlab.io/v1/todo/
- https://api.onexlab.io/v2/todo/ and so on
Header Based API versioning
In this approach, You need to place the API version to the headers
Example:
curl -X GET \
http://127.0.0.1:1324/todo \
-H 'Postman-Token: e75880eb-ac09-44f6-81e8-f2b83bd53149' \
-H 'cache-control: no-cache' \
-H 'version: v1'
First, we will try URL based API versioning using echo framework
URL based API versioning using echo framework
Project Structure
go-header-based-versioning
- main.go
To install echo framework go to the root directory of your project in terminal/command prompt
Try to run the following command
go get -u github.com/labstack/echo/example:
go-header-based-versioning$ go get -u github.com/labstack/echo/
Here is main.go file code we have written using echo framework
main.go file
Try running following command to start the server
go run main.go
You can see the following screenshot if your program running successfully
Try to open the following URL to any browser
http://127.0.0.1:1324/v1/todo
You will see it will return you Hello, World as the following screenshot
Now we will implement header based API versioning using echo framework
Header based API versioning using echo framework
main.go file
You can see we have changed main.go file added two endpoints v1,v2 as well added APIVersion method/handler.
e.Pre(APIVersion);
Pre method used as middleware to modify the URL
Try running following command to start the server
go run main.go
Try to run following CURL command in terminal (MAC/Linux OS User) or CMD prompt (Windows OS User) or You can also try Postman
curl -X GET \
http://127.0.0.1:1324/todo \
-H 'Postman-Token: e75880eb-ac09-44f6-81e8-f2b83bd53149' \
-H 'cache-control: no-cache' \
-H 'version: v1'curl -X GET \
http://127.0.0.1:1324/todo \
-H 'Postman-Token: c326ac71-05ad-4ff4-8fc7-8ea5b129f121' \
-H 'cache-control: no-cache' \
-H 'version: v2'
You can see if you pass v1 to version header it will return you TODO v1 as the following screenshot
if you pass v2 to version header it will return you TODO v2 as the following screenshot
Conclusion
API versioning based on the header is a bit tricky using Go lang echo framework