【问题标题】:Extending GoLang's http.ResponseWriter functionality to pre/post process responses将 GoLang 的 http.ResponseWriter 功能扩展到前/后处理响应
【发布时间】:2016-07-21 20:28:28
【问题描述】:

我正在尝试编写一个简单的 http MiddleWare 处理程序来处理 http 响应。不幸的是,它不起作用,我无法弄清楚我犯了什么错误。感谢任何/所有帮助!

我正在使用 Go Gorilla mux 路由器 以下是代码的说明性部分:

import (
    "fmt"
    "log"
    "github.com/gorilla/mux"
)
:
func Start() {
    router := mux.NewRouter()
    router.HandleFunc("/", myHandler)
    :
    log.Fatal(http.ListenAndServe(":8088", Middleware(router)))
}

func myHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "myHandler called")
}
func Middleware(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        neww := NewProcessor(w)
        h.ServeHTTP(neww, r)
    })
}

type Processor struct {
    http.ResponseWriter
}
func (r *Processor) Write(b []byte) (int, error) {
    fmt.Printf("******* Processor writing...")
    log.Print(string(b)) // log it out
    return r.Write(b)    // pass it to the original ResponseWriter
}
func NewProcessor(w http.ResponseWriter) http.ResponseWriter {
    fmt.Printf("******* Creating new Processor...")
    return &Processor{ResponseWriter: w}
}

下面列出了我得到的输出(为清楚起见,省略了额外的日志记录文本):

******* Creating new Processor 
myHandler called

但是,请注意“*******处理器正在写入...”的消息没有显示,这表明“写入”函数没有被调用。

需要进行哪些更改才能调用“Write”函数?

【问题讨论】:

    标签: go


    【解决方案1】:

    return r.Write(b) 导致对处理器的Write() 方法的无限循环调用。将其替换为 return r.ResponseWriter.Write(b) 修复了该错误。

    以下是更正后的代码:

    package main
    
    import (
        "fmt"
        "log"
        "net/http"
    )
    
    func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("/", myHandler)
        log.Fatal(http.ListenAndServe(":8088", Middleware(mux)))
    }
    
    func myHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "myHandler called")
    }
    
    func Middleware(h http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            new := NewProcessor(w)
            h.ServeHTTP(new, r)
        })
    }
    
    type Processor struct {
        http.ResponseWriter
    }
    
    func (r *Processor) Write(b []byte) (int, error) {
        log.Print("******* Processor writing...")
        log.Print(string(b)) // log it out
        return r.ResponseWriter.Write(b)    // pass it to the original ResponseWriter
    }
    
    func NewProcessor(w http.ResponseWriter) http.ResponseWriter {
        log.Print("******* Creating new Processor...")
        return &Processor{ResponseWriter: w}
    }
    

    输出:

    2016/07/21 22:59:08 ******* Creating new Processor...
    2016/07/21 22:59:08 ******* Processor writing...
    2016/07/21 22:59:08 myHandler called
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      • 2018-06-05
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多