亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在中間件中重寫內容長度

在中間件中重寫內容長度

Go
交互式愛情 2023-06-12 16:57:49
下面的代碼重寫了一些查詢的 http body 響應。但是,它無法更新“內容長度”標頭字段,它始終保持相同的原始值。如何更新 http 響應的內容長度標頭字段?type writeReplacer struct {    http.ResponseWriter    search  []byte    replace func(*http.Request) string    buf     []byte    r       *http.Request    dir     string}func (w *writeReplacer) Write(in []byte) (int, error) {    if w.buf == nil {        w.buf = []byte{}    }    w.buf = append(w.buf, in...)    n := len(in)    if index := bytes.LastIndex(w.buf, w.search); index > -1 {        var r []byte        if w.dir == "before" {            g := []byte(w.replace(w.r))            n += len(g)            r = append(g, w.buf[index:]...)            w.buf = append(w.buf[:index], r...)        } else {            g := []byte(w.replace(w.r))            n += len(g)            r = append(r, w.buf[:index+len(w.search)]...)            r = append(r, g...)            r = append(r, w.buf[index:]...)            w.buf = r        }    }    return n, nil}func (w *writeReplacer) Flush() {    w.ResponseWriter.Header().Set("Content-Length", fmt.Sprint(len(w.buf)))    w.ResponseWriter.Write(w.buf[:])    w.buf = w.buf[:0]}func InsertAfter(h http.Handler, path string, search []byte, replace func(*http.Request) string) http.Handler {    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        if r.URL.Path == path {            w.Header().Del("Content-length")            w = &writeReplacer{ResponseWriter: w, search: search, replace: replace, r: r, dir: "after"}            defer w.(http.Flusher).Flush()        }        h.ServeHTTP(w, r)    })}func InsertBefore(h http.Handler, path string, search []byte, replace func(*http.Request) string) http.Handler {    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        if r.URL.Path == path {            w.Header().Del("Content-length")            w = &writeReplacer{ResponseWriter: w, search: search, replace: replace, r: r, dir: "before"}            defer w.(http.Flusher).Flush()        }        h.ServeHTTP(w, r)    })}
查看完整描述

1 回答

?
慕少森

TA貢獻2019條經驗 獲得超9個贊

訣竅是重寫ResponseWriter.WriteHeader.


我相信這與 write 可能會在第一次調用時調用 writeheader 這一事實有關,從那里我沒有將指令放在正確的位置。


為了防止進一步的困難,我更喜歡使用分塊傳輸。


代碼更改是:


func (w *writeReplacer) WriteHeader(statusCode int) {

? ? w.Header().Del("Content-length")

? ? w.Header().Set("Transfer-Encoding", "chunked")

? ? w.ResponseWriter.WriteHeader(statusCode)

}


查看完整回答
反對 回復 2023-06-12
  • 1 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號