解決Golang中ResponseWriter的一個(gè)坑
在使用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寫(xiě)入報(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)它在沒(méi)有設(shè)置Header時(shí)會(huì)panic,當(dāng)然這跟我們當(dāng)前要討論的問(wèn)題關(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重新試下,問(wèn)題解決。
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ò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
談?wù)揋o 什么時(shí)候會(huì)觸發(fā) GC問(wèn)題
Go 語(yǔ)言作為一門(mén)新語(yǔ)言,在早期經(jīng)常遭到唾棄的就是在垃圾回收(下稱(chēng):GC)機(jī)制中 STW(Stop-The-World)的時(shí)間過(guò)長(zhǎng)。下面文章就對(duì)此話(huà)題展開(kāi),感興趣的小伙伴可以參考下面文章的內(nèi)容2021-09-09
go語(yǔ)言通過(guò)反射獲取和設(shè)置結(jié)構(gòu)體字段值的方法
這篇文章主要介紹了go語(yǔ)言通過(guò)反射獲取和設(shè)置結(jié)構(gòu)體字段值的方法,實(shí)例分析了Go語(yǔ)言反射的使用技巧,需要的朋友可以參考下2015-03-03
golang中json小談之字符串轉(zhuǎn)浮點(diǎn)數(shù)的操作
這篇文章主要介紹了golang中json小談之字符串轉(zhuǎn)浮點(diǎn)數(shù)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03

