Home  >  Article  >  Backend Development  >  How to implement routing middleware in Go language

How to implement routing middleware in Go language

王林
王林Original
2023-12-17 17:28:001279browse

How to implement routing middleware in Go language

How to implement routing middleware in Go language, specific code examples are required

Introduction:

In the web development of Go language, routing is Indispensable part. Routing middleware is a functional module that is executed before the request reaches the target processing function. They can intercept, verify, record and other operations on requests, thereby helping developers handle some common functions and improve code reusability.

This article will introduce how to implement routing middleware in Go language and provide specific code examples.

1. Use the gorilla/mux library to implement routing middleware

  1. Install the gorilla/mux library

Execute the following command in the terminal to install gorilla/mux Library:

go get -u github.com/gorilla/mux
  1. Create routing middleware

Let’s start creating routing middleware. First, create a new file middleware.go to define our middleware function.

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
)

func middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // 在请求到达目标处理函数之前执行的操作
        
        fmt.Println("Executing middleware")

        // 调用下一个中间件或目标处理函数
        next.ServeHTTP(w, r)
    })
}

func main() {
    r := mux.NewRouter()

    // 使用我们的中间件
    r.Use(middleware)

    // 路由定义
    r.HandleFunc("/", homeHandler).Methods("GET")

    // 启动服务器
    http.ListenAndServe(":8080", r)
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, World!")
}

In the above code, we define a function named middleware, which accepts a parameter next of type http.Handler. We wrap the target handler function by returning a new http.Handler. In the wrapped handler, we can add our custom logic and then call next.ServeHTTP(w, r) to pass the request to the next middleware or target handler function.

In the main function, we apply our middleware to all routes through r.Use(middleware).

  1. Run the code

Execute the following command in the terminal to run the code:

go run main.go

Now, when we visit localhost:8080, we can see that The console output "Executing middleware".

2. Use the net/http library to implement routing middleware

If we do not use a third-party library, we can also use the net/http library to implement routing middleware.

The following is a specific sample code:

package main

import (
    "fmt"
    "log"
    "net/http"
)

type MyHandler struct{}

func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Executing middleware")
    // 调用目标处理函数
    homeHandler(w, r)
}

func middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // 在请求到达目标处理函数之前执行的操作
        fmt.Println("Executing middleware")
        next.ServeHTTP(w, r)
    })
}

func main() {
    mux := http.NewServeMux()

    // 创建中间件
    handler := middleware(&MyHandler{})

    // 设置路由
    mux.Handle("/", handler)

    // 启动服务器
    log.Fatal(http.ListenAndServe(":8080", mux))
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, World!")
}

In the above code, we define a function named middleware, which accepts a parameter next of type http.Handler. We wrap the target handler function by returning a new http.Handler. In the wrapped handler, we can add our custom logic and then call next.ServeHTTP(w, r) to pass the request to the next middleware or target handler function.

In the main function, we create a new ServeMux and use mux.Handle("/", handler) to apply our middleware to the root route.

  1. Run the code

Execute the following command in the terminal to run the code:

go run main.go

Now, when we visit localhost:8080, we can see that The console output "Executing middleware".

Conclusion:

Through the above sample code, we learned how to implement routing middleware in Go language. Routing middleware can be easily implemented using third-party libraries or directly using the net/http library. This feature can help us handle some common functional requirements, improve code reusability, and make our applications more flexible and easier to maintain. Hope this article is helpful to you!

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