Gin-Gonic Middleware that implements fields selection pattern
At my company we use Go to build internal tools. Recently I worked in a REST API using gin-gonic, that required displaying a lot of data across many endpoints.
One must have feature in this type of scenario, is pagination, but and often overlooked pattern is partial response (a.k.a field selection). Which is also a very nice addition to filter out the amount of data in the responses of your web server.
What’s field selection?
Let us first make it clear what I mean with a field selection. Imagine that you have the following endpoint:
// > GET /api/products [ { "id": 1, "createdAt": "2024-18-11", "updatedAt": "2024-18-11", "code": "1", "price": { "amount": 100, "currency": "EUR" }, "manufacturedBy": "myshop", "stock": 552, ... }, ... ]
Using partial responses, clients can filter the output with a fields query parameter, e.g.
// > GET /api/products?fields=code,price [ { "code": "1", "price": { "amount": 100, "currency": "EUR" } }, ... ]
Only the fields declared in the query parameter are returned. Reducing the payload size and saving bandwidth.
Introducing Milogo
I could not find any implementation available for this pattern, so I decided to create it myself, and that is how Milogo was born.
Milogo is a Gin middleware that processes API responses, filters out fields specified in the fields query parameter, and return only the requested data.
Some of the main features available:
Support for json objects and json arrays.
So Milogo can filter fields for JSON responses that starts with an array of items or just with one single item.Support for filtering out fields in nested json objects.
Milogo also supports filtering nested JSON objects with the following format e.g. code,price(amount)Support for json wrapped in another json.
Sometimes the JSON responses are wrapped in another JSON object, Milogo support filtering the actual payload (see example wrapped):
// GET /products?fields=code,price(amount) { "data": [ { "code": 1, "price": { "amount": 100 } }, ... ], "_metadata": { ... } }
Getting Started
As any gin middleware, Milogo is really easy to use and setup, you can follow the README in the github repository, but basically:
r := gin.Default() r.Use(Milogo())
is enough to add Milogo middleware to your api.
In the previous example Milogo is applied to every single endpoint, but it is also possible to apply only to a group of endpoints, or just to an specific endpoint, e.g.
group := r.Group("/products", milogo.Milogo()) group.GET("", productsHandler)
In the previous example, only the /products group would have the Milogo’s middleware applied.
Conclusion
Milogo is designed to simplify REST API development and improve client-server interactions. Check out the GitHub repository for examples and documentation.
Feel free to reach out or contribute — let’s make REST APIs efficient together!
The above is the detailed content of Simplify Your REST API Responses with Milogo for Gin-Gonic. For more information, please follow other related articles on the PHP Chinese website!

This article explains Go's package import mechanisms: named imports (e.g., import "fmt") and blank imports (e.g., import _ "fmt"). Named imports make package contents accessible, while blank imports only execute t

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
