Use the Gin framework to implement search and filter functions

WBOY
Release: 2023-06-22 17:16:37
Original
1656 people have browsed it

Gin is a lightweight, extensible web framework that is becoming increasingly popular based on the speed and performance of the Go language, as well as its second-to-none concurrency and maintainability. In this article, we will learn how to use the Gin framework to implement search and filter functionality.

First, we need to set up a basic Gin application. To do this, we need to add the required dependencies in the go.mod file and install them. Here we use the Gin framework and Go's ORM library GORM. We will use MySQL as our relational database.

Our go.mod file should look like this:

module github.com/mygithubaccount/myginapp

require (
    github.com/gin-gonic/gin v1.7.2
    gorm.io/driver/mysql v1.2.1
    gorm.io/gorm v1.21.9
)
Copy after login

For the database connection, we will use the following style of format:

username:password@tcp(hostname:port)/database_name?charset=utf8mb4&parseTime=True&loc=Local
Copy after login

Next, we need to start from Import gin and net/http into the Gin package.

import (
    "net/http"

    "github.com/gin-gonic/gin"
)
Copy after login

In our main function, we need to connect to the database and create a variable called db, while enabling Gin's default middleware.

func main() {
    dsn := "username:password@tcp(hostname:port)/database_name?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    
    if err != nil {
        panic("failed to connect to database")
    }

    r := gin.Default()
    r.Use(cors.Default())

    // Routes
    r.GET("/healthcheck", healthCheckHandler)

    // Port binding
    port := os.Getenv("PORT")

    if port == "" {
        port = "8080"
    }

    r.Run(":" + port)
}
Copy after login

This is our basic setup. Now let's consider implementing search and filter functionality.

We will implement search and filtering functions on the following data model.

type User struct {
    ID        uint   `json:"id" gorm:"primarykey"`
    FirstName string `json:"firstName"`
    LastName  string `json:"lastName"`
    Age       int    `json:"age"`
    Gender    string `json:"gender"`
    Email     string `json:"email" gorm:"uniqueIndex"`
}
Copy after login

We will define the following request handler to handle our POST requests.

func searchUsersHandler(c *gin.Context) {
    var filter User
    var users []User

    if err := c.ShouldBindJSON(&filter); err != nil {
        c.AbortWithStatus(http.StatusBadRequest)
        return
    }

    db.Where(&filter).Find(&users)
    c.JSON(http.StatusOK, users)
}
Copy after login

This handler allows us to pass the parameters of the POST request into the User structure and execute a query in the database table. We can also handle queries in other ways:

  • LIKE
  • IN
  • NOT
  • OR

Here we will make runtime queries in the application. This is fine for small applications, but this may cause excessive server load for larger applications. A better approach would be to move the search query to the front-end, leveraging the client's browser resources for searching/filtering.

Now we need to bind the request and handler together. This can be done via Gin routing.

r.POST("/search", searchUsersHandler)
Copy after login

Through this route, we can issue a POST request and send a User structure to the application, which will be used to query user records.

This is how to use the Gin framework to implement search and filter functions. To summarize, in this article we learned how to connect to a database, use Gin's default middleware, define a data model, write a request handler, and bind routes to handlers. The application can now be used to perform basic operations of searching and filtering data records in a relational database.

The above is the detailed content of Use the Gin framework to implement search and filter functions. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template