search
HomeBackend DevelopmentGolangTaking Pagination to the Next Level: Sorting and Filtering in Go APIs

In the last post, we tackled Pagination breaking down large API responses into manageable chunks. But if you've ever wanted to let users control how data is sorted or filter specific results, then you're ready for the next step: sorting and filtering.
Let's dive in and make our APIs even more powerful by adding these features.

If you haven't gone through the previous tutorial, here's the link.

Why Sorting and Filtering Matter

Image description
Pagination alone isn't always enough. Imagine a user searching for the newest items or only those created in a specific timeframe. Sorting and filtering let users:

- Sort: Choose the order of results (e.g. newest to oldest)
- Filter: Narrow down results to what they need (e.g. items created today)

By combining pagination with sorting and filtering, we create a more user-friendly API.

Extending Our Database Query

We'll build on the items table from the previous blog. To recap, here's the scheme:

CREATE TABLE items (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

Adding Sorting

Sorting is all about ordering the results. We'll allow users to sort by the name or created_at columns in ascending or descending order.

Step 1: Accept Sort Parameters

Users will pass two query parameters:

  • sort : The column to sort by ( name or created_at ).
  • order : The sort direction ( asc or desc ).

Example URL:

/items?page=1&limit=10&sort=created_at&order=desc

Step 2: Adjust the SQL Query

We'll dynamically modify the SQL query to include sorting:

// Extract sort and order query parameters
sort := r.URL.Query().Get("sort")
order := r.URL.Query().Get("order")

// Validate the sort column
validSortColumns := map[string]bool{"name": true, "created_at": true}
if !validSortColumns[sort] {
    sort = "created_at" // Default sort column
}

// Validate the sort order
if order != "asc" && order != "desc" {
    order = "asc" // Default sort order
}

// Modify the SQL query
query := fmt.Sprintf("SELECT id, name, created_at FROM items ORDER BY %s %s LIMIT  OFFSET ", sort, order)
rows, err := db.Query(query, limit, offset)
if err != nil {
    http.Error(w, "Failed to fetch items", http.StatusInternalServerError)
    return
}

Adding Filtering

Filtering lets users refine their search. For example, we can filter items by a date range or items containing a specific keyword in their name.

Step 1: Accept Filter Parameters

We'll support two filters:

  • name : Search for items containing a specific substring.
  • created_after : Fetch items created after a specific date.

Example URL :

/items?page=1&limit=10&name=Item&created_after=2025-01-10 20:38:57.832777

Step 2: Adjust the SQL Query

We'll add WHERE conditions to handle these filters:

CREATE TABLE items (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

Testing the Enhanced API

  • Sorting by name in ascending order:
/items?page=1&limit=10&sort=created_at&order=desc
  • Filtering items created after a specific date:
// Extract sort and order query parameters
sort := r.URL.Query().Get("sort")
order := r.URL.Query().Get("order")

// Validate the sort column
validSortColumns := map[string]bool{"name": true, "created_at": true}
if !validSortColumns[sort] {
    sort = "created_at" // Default sort column
}

// Validate the sort order
if order != "asc" && order != "desc" {
    order = "asc" // Default sort order
}

// Modify the SQL query
query := fmt.Sprintf("SELECT id, name, created_at FROM items ORDER BY %s %s LIMIT  OFFSET ", sort, order)
rows, err := db.Query(query, limit, offset)
if err != nil {
    http.Error(w, "Failed to fetch items", http.StatusInternalServerError)
    return
}
  • Combining filters and sorting:
/items?page=1&limit=10&name=Item&created_after=2025-01-10 20:38:57.832777

Common Mistake to Avoid

Not validating user input: Allowing arbitrary columns or invalid sort orders can expose your database to SQL injection. Always validate inputs.

Conclusion / Next Steps

You can find the complete code repository for this tutorial here

With pagination, sorting, and filtering in place, your API is now more user-friendly and flexible. For even more advanced functionality, consider adding:

  • Cursor-based pagination for large datasets.
  • Faceted filtering for complex searches.

Stay tuned for the next post where we’ll explore these advanced techniques!

To get more information about Golang concepts, projects, etc. and to stay updated on the Tutorials do follow Siddhesh on Twitter and GitHub.

Until then Keep Learning, Keep Building ??

The above is the detailed content of Taking Pagination to the Next Level: Sorting and Filtering in Go APIs. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.