编写一个http的调用链

这李借鉴我同事写的一个调用链,看看如果个一个请求加上一个调用链,这个其实在其它编程里面都会用到,如果熟悉拦截器的对此会应该会更有体会
先看看测试代码

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.ListenAndServe(":8080", regisry())
}

func Hello(rw http.ResponseWriter, req *http.Request){
    //return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
        rw.Write([]byte("hello world!"))
    //})
}


func Authentication() http.Handler {
    return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
        fmt.Println("Authentication")
        Hello(rw,req)
    })
}

func Authorizer(handle http.Handler) http.Handler {
    return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
        fmt.Println("Authorizer")
        handle.ServeHTTP(rw, req)
    })
}

func Step3(handle http.Handler) http.Handler {
    return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
        fmt.Println("Step3")
        handle.ServeHTTP(rw, req)
    })
}

func Step4(handle http.Handler) http.Handler {
    return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
        fmt.Println("Step4")
        handle.ServeHTTP(rw, req)
    })
}

func regisry() http.Handler {

    h := Authentication()
    h = Authorizer(h)
    h = Step3(h)
    h = Step4(h)
    return h
}

启功服务,测试一下,

Step4
Step3
Authorizer
Authentication

输出如下,下面分析一个这个请求的过程,先看定义的过程,从下向上,创建一个Step4方法,这个里面传入的是Step3,那么在Step4方法执行完之后将会执行 Step3方法 ,以此类推,最后创建一个Authentication的方法,Authentication之后调用自己的业务方法。
这个就可以逐层去过滤请求了。上面的每层函数返回的h都是一个新的http handle,只是名称一样。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳清风09

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值