主頁 > 知識(shí)庫 > 解決Golang中ResponseWriter的一個(gè)坑

解決Golang中ResponseWriter的一個(gè)坑

熱門標(biāo)簽:外呼系統(tǒng)顯本地手機(jī)號(hào) 電話機(jī)器人軟件免費(fèi) 外呼系統(tǒng)用什么卡 阿克蘇地圖標(biāo)注 百度地圖標(biāo)注后傳給手機(jī) 涿州代理外呼系統(tǒng) 評(píng)價(jià)高的400電話辦理 壽光微信地圖標(biāo)注 excel地圖標(biāo)注分布數(shù)據(jù)

在使用Context.ResponseWriter中的Set/WriteHeader/Write這三個(gè)方法時(shí),使用順序必須如下所示,否則會(huì)出現(xiàn)某一設(shè)置不生效的情況。

ctx.ResponseWriter.Header().Set("Content-type", "application/text")
 ctx.ResponseWriter.WriteHeader(403)
 ctx.ResponseWriter.Write([]byte(resp))

如1:

ctx.ResponseWriter.Header().Set("Content-type", "application/text")
 ctx.ResponseWriter.Write([]byte(resp))
 ctx.ResponseWriter.WriteHeader(403)

會(huì)導(dǎo)致返回碼一直是200

補(bǔ)充:Go里w http.ResponseWriter,調(diào)用w.Write()方法報(bào)錯(cuò)

Go里w http.ResponseWriter寫入報(bào)錯(cuò)

http: request method or response status code does not allow

1. 下面是報(bào)錯(cuò)截圖

2. 點(diǎn)進(jìn)去Write方法

它首先是一個(gè)接口;

由于它是在HTTP web服務(wù)器的應(yīng)用場(chǎng)景,所以它具體的實(shí)現(xiàn)方法在net/http/server.go里:

func (w *response) Write(data []byte) (n int, err error) {
 return w.write(len(data), data, "")
}

再點(diǎn)進(jìn)去,函數(shù)里你會(huì)發(fā)現(xiàn)有一個(gè)關(guān)鍵的判斷

// 其中ErrBodyNotAllowed的
// 代碼內(nèi)容
// ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
if !w.bodyAllowed() {
 return 0, ErrBodyNotAllowed
}
 

點(diǎn)進(jìn)去,發(fā)現(xiàn)它在沒有設(shè)置Header時(shí)會(huì)panic,當(dāng)然這跟我們當(dāng)前要討論的問題關(guān)系不大,關(guān)鍵在bodyAllowedForStatus()方法

func (w *response) bodyAllowed() bool {
 if !w.wroteHeader {
  panic("")
 }
 return bodyAllowedForStatus(w.status)
}

再點(diǎn),終于看到了,當(dāng)設(shè)置狀態(tài)碼為【100,199】、204、304就會(huì)報(bào)這個(gè)錯(cuò),而我剛好設(shè)置的狀態(tài)碼就是204,我把它改成200重新試下,問題解決。

func bodyAllowedForStatus(status int) bool {
 switch {
 case status >= 100  status = 199:
  return false
 case status == 204:
  return false
 case status == 304:
  return false
 }
 return true
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。

您可能感興趣的文章:
  • golang設(shè)置http response響應(yīng)頭與填坑記錄
  • 解決golang處理http response碰到的問題和需要注意的點(diǎn)
  • golang中為什么Response.Body需要被關(guān)閉詳解

標(biāo)簽:雞西 銅川 重慶 梅河口 蘭州 汕頭 吐魯番 欽州

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《解決Golang中ResponseWriter的一個(gè)坑》,本文關(guān)鍵詞  解決,Golang,中,ResponseWriter,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《解決Golang中ResponseWriter的一個(gè)坑》相關(guān)的同類信息!
  • 本頁收集關(guān)于解決Golang中ResponseWriter的一個(gè)坑的相關(guān)信息資訊供網(wǎng)民參考!
  • 企业400电话

    智能AI客服机器人
    15000

    在线订购

    合计11份范本:公司章程+合伙协议+出资协议+合作协议+股权转让协议+增资扩股协议+股权激励+股东会决议+董事会决议

    推薦文章