douyi4912 2016-07-21 20:28
浏览 194
已采纳

将GoLang的http.ResponseWriter功能扩展到处理前/处理后响应

I am trying to write a simple http MiddleWare handler that will process an http response. Unfortunately, it does not work and I cannot figure out what mistake I am making. Any/all help is appreciated!

I am using Go Gorilla mux router Here are illustrative parts of the code:

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}
}

The output I get is listed below (extra logging text omitted for clarity):

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

However, notice the message "******* Processor writing..." was not displayed, suggesting that the "Write" function did not get called.

What changes need to be made to allow the "Write" function to be called?

  • 写回答

1条回答 默认 最新

  • dsj8086 2016-07-21 21:01
    关注

    return r.Write(b) caused an infinite loop of calls to the Processor's Write() method. Replacing it with return r.ResponseWriter.Write(b) fixed the bug.

    Here is the corrected code:

    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}
    }
    

    Output:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题