Home  >  Article  >  Backend Development  >  How to implement golang routing

How to implement golang routing

PHPz
PHPzOriginal
2023-04-14 10:31:29861browse

Golang is an extremely popular programming language that is efficient, concise and scalable. In terms of network programming, Golang also performs very well. Its standard library provides a wealth of APIs related to network operations, and it is very simple to write high-performance services using Golang.

Routing is the foundation of network programming and an essential component of the Web framework. This article will explore how to use Golang to implement basic routing functions.

For the sake of simplicity, we choose the Gin framework for demonstration. Gin is an efficient, lightweight Web framework that is fast, easy to use, and powerful. To install the Gin library, you can use the command:

go get -u github.com/gin-gonic/gin

After knowing the basics of the framework, we can start to implement routing. In Gin, routing is divided into two types: HTTP basic routing and packet routing.

HTTP basic routing can implement the following functions:

  • Routes that handle HTTP methods such as GET, POST, PUT, PATCH, DELETE, etc.
  • Parameters used in routing
  • Using Query parameters in routing
  • Using Fragment parameters in routing

Now, let’s demonstrate how to create a basic route:

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

The above In the example, we create a route that can access the /ping route through the HTTP GET method. When a request is received, it returns a JSON-formatted response with HTTP status code 200.

Next let’s take a look at how to implement routing with parameters:

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    // 路由中使用参数
    r.GET("/user/:name", func(c *gin.Context) {
        name := c.Param("name")
        c.String(200, fmt.Sprintf("Hello, %s", name))
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

In the above example, we use the :name in the route as a parameter. When we access / by using the HTTP GET method When user/xxx, the routing will prompt us "Hello, xxx".

The Query parameter is the standard query string format used in HTTP requests. The following example demonstrates how to use Query parameters in routing:

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    // 路由中使用Query参数
    r.GET("/welcome", func(c *gin.Context) {
        firstname := c.Query("firstname")
        lastname := c.Query("lastname")
        c.String(200, fmt.Sprintf("Welcome, %s %s", firstname, lastname))
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

In the above example, we used the HTTP GET method to access the /welcome route and passed the Query parameters firstname and lastname. The route returns a string containing the values ​​of these parameters. For example: When we use the following URL to access the route, we will get the return value "Welcome, John Doe":

http://localhost:8080/welcome?firstname=John&lastname=Doe

In some cases, Fragment parameters may be needed in the route to perform specific operations. The following example demonstrates how to use Fragment parameters in routing:

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    // 路由中使用Fragment参数
    r.GET("/blog/:id/:title/*fragment", func(c *gin.Context) {
        id := c.Param("id")
        title := c.Param("title")
        fragment := c.Param("fragment")
        c.String(200, fmt.Sprintf("This is Blog %s: %s %s", id, title, fragment))
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

In the above example, we created a route. When we visit /blog/1234/best-blog-ever#comments, the route will Can successfully return a string containing the values ​​of id, title and fragment.

In addition to basic routing, Gin also supports group routing.

In group routing, we group routes according to functions or permissions. Different sub-routes can point to different functions, and they can also share middleware, call the same function, and share routing parameters.

The following is a simple example of group routing:

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    // 创建一个分组路由
    guest := r.Group("/guest")
    {
        guest.GET("/login", func(c *gin.Context) {
            c.String(200, "Welcome to Login Page!")
        })
        guest.GET("/register", func(c *gin.Context) {
            c.String(200, "Welcome to Register Page!")
        })
    }

    admin := r.Group("/admin")
    {
        admin.GET("/dashboard", func(c *gin.Context) {
            c.String(200, "Welcome to Dashboard!")
        })
        admin.GET("/users", func(c *gin.Context) {
            c.String(200, "Welcome to Users page!")
        })
    }

    r.Run() // listen and serve on 0.0.0.0:8080
}

In the above example, we used group routing to divide the routes into two groups: guest and admin. Each set of routes has its own routing function. This way we can serve different pages to each user type.

Implementing routing in Golang is very simple, and using the Gin framework is even more effortless. By using the above-mentioned functions and APIs, we can create a web application with multiple routes. I wish you success!

The above is the detailed content of How to implement golang routing. 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