Home  >  Article  >  Backend Development  >  Golang interceptors: at a glance

Golang interceptors: at a glance

WBOY
WBOYOriginal
2024-04-07 21:24:02966browse

Overview: Go interceptor is a mechanism that handles the logic before and after functions implemented through intermediary software. Principle: The interceptor is passed to the function as a parameter, and the logic before and after the function is executed. Practical Combat: Demonstrates the use of interceptors by creating an interceptor that records request times and verifies request parameters, and links it to an HTTP handler.

Golang 拦截器: 一览无余

Go Interceptor: At a Glance

Introduction

Interceptor is a A mechanism to do some processing before and after function execution. In Golang, interceptors can be implemented using middleware.

Principle

Interceptors work by passing themselves as parameters to the function to be intercepted. When a function is called, the interceptor will execute its logic before and after the function is executed.

Practical case

We create a simple HTTP server to demonstrate how to use interceptors:

package main

import (
    "log"
    "net/http"
)

func main() {
    // 创建一个记录请求时间的拦截器
    timeInterceptor := func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            start := time.Now()
            defer func() { log.Printf("请求处理耗时:%fs", time.Since(start).Seconds()) }()
            next.ServeHTTP(w, r)
        })
    }

    // 创建一个校验请求参数的拦截器
    paramInterceptor := func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            if r.URL.Query().Get("id") == "" {
                http.Error(w, "缺少参数:id", http.StatusBadRequest)
                return
            }
            next.ServeHTTP(w, r)
        })
    }

    // 将拦截器与 HTTP 处理程序链接
    handler := paramInterceptor(timeInterceptor(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, World!"))
    })))

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

In this example, timeInterceptor The interceptor records the request processing time, while the paramInterceptor interceptor verifies the request parameters. By chaining interceptors we can execute this logic before and after processing the request.

Summary

Interceptors are powerful tools to enhance the functionality of Golang programs. They allow you to execute custom code before and after a function executes, enabling operations such as logging, validation, and authorization.

The above is the detailed content of Golang interceptors: at a glance. 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