В Go промежуточное ПО используется для перехвата и обработки HTTP-запросов и ответов в веб-приложении. Пользовательское промежуточное программное обеспечение позволяет добавлять собственную логику и функциональность в конвейер запросов/ответов. Вот несколько способов создания собственного промежуточного программного обеспечения в Go:
Метод 1: использование функции-обработчика
package main
import (
"fmt"
"net/http"
)
func customMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Perform actions before calling the next handler
fmt.Println("Executing custom middleware")
// Call the next handler
next(w, r)
}
}
func mainHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Executing main handler")
w.Write([]byte("Hello, World!"))
}
func main() {
// Create a new ServeMux
mux := http.NewServeMux()
// Register the mainHandler with the customMiddleware
mux.HandleFunc("/", customMiddleware(mainHandler))
// Start the server
http.ListenAndServe(":8080", mux)
}
Метод 2: использование структуры
package main
import (
"fmt"
"net/http"
)
type customMiddleware struct {
next http.Handler
}
func (m *customMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Perform actions before calling the next handler
fmt.Println("Executing custom middleware")
// Call the next handler
m.next.ServeHTTP(w, r)
}
func mainHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Executing main handler")
w.Write([]byte("Hello, World!"))
}
func main() {
// Create a new ServeMux
mux := http.NewServeMux()
// Create an instance of customMiddleware
middleware := &customMiddleware{
next: http.HandlerFunc(mainHandler),
}
// Register the middleware with the ServeMux
mux.Handle("/", middleware)
// Start the server
http.ListenAndServe(":8080", mux)
}
В обоих методах пользовательское промежуточное программное обеспечение выполняется перед вызовом основного обработчика. Вы можете добавить свою собственную логику внутри функции или метода промежуточного программного обеспечения.