关于go:go使用nethttp-创建middleware中间件

在上一节文章 go应用net/http 创立web服务器-高阶篇
咱们学会了创立 服务器。
在个别的C/S架构中,在多个客户端与服务器进行通信时,咱们常常应用中间件,来进去一些,在业务逻辑之前的,客户端发送给服务器的数据验证。

一、什么是http中间件

在互联网的http通信中,如果多个客户端拜访服务器,咱们就会构建一个 client/server 客户端/服务器 架构来实现。
服务器用来承受客户端的申请,而后返回特定的资源或者数据给客户端。

中间件是客户端申请达到解决办法之前对其进行预处理的一些逻辑。
罕用的利用场景有:

  1. 客户端身份校验
  2. 用户鉴权
  3. 客户端对服务器提供的特定服务是否有拜访权限
  4. 验证用户 session,并放弃通信存活
  5. 客户端申请参数解密
  6. 客户端参数格式化
  7. 日志记录器,用于记录每个 REST API 拜访申请
  8. 跨域配置
  9. 返回数据格式化
  10. Header设置

中间件原理

在 Go 语言中,中间件 Handler 是封装另一个 http.Handler 以对申请进行预处理或后续解决的 http.Handler。它介于 Go Web 服务器与理论的处理程序之间,因而被称为“中间件”。

原理剖析:
咱们先看一个最简略的一个http服务器

package main

import (
    "fmt"
    "net/http"
)

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

func main() {
    http.HandleFunc("/index", index)
    http.ListenAndServe(":8090", nil)
}

下面的示例代码就实现了一个 http服务器。
在路由的解决方面,次要是 通过http.HandleFunc函数,咱们能够看一下官网的源代码

// HandleFunc registers the handler function for the given pattern
// HandleFunc 注册handler处理函数到DefaultServeMux,用来绑定给定的url
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
// ServeMux文档有具体的url解析匹配介绍
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    DefaultServeMux.HandleFunc(pattern, handler)
}

// HandleFunc registers the handler function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    if handler == nil {
        panic("http: nil handler")
    }
    mux.Handle(pattern, HandlerFunc(handler))
}

// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}

咱们能够看到最初的解决是通过 HandlerFunc 反射。
这个正是咱们传过来的index(w http.ResponseWriter, r *http.Request)

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据