1 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
w
不是指針,但它是接口類型,它將指針包裝在引擎蓋下。因此,您可以按原樣傳遞它,當(dāng)您調(diào)用其方法時(shí),它將反映在調(diào)用方中。
只是不要忘記,如果之前有任何東西寫到響應(yīng),你不能(再次)寫標(biāo)題。同樣,如果您向輸出寫入某些內(nèi)容,則調(diào)用方無法將其取回。如果生成響應(yīng),則在這種情況下,調(diào)用方應(yīng)返回。authError()
authError()
另請注意,必須首先設(shè)置標(biāo)頭,然后調(diào)用 ,然后才能寫入響應(yīng)正文。ResponseWriter.WriteHeader()
如果調(diào)用 ,則將寫入響應(yīng)狀態(tài)(如果尚未寫入)(假設(shè) )。ResponseWriter.Write()
HTTP 200 OK
// If WriteHeader has not yet been called, Write calls
// WriteHeader(http.StatusOK) before writing the data. If the Header
// does not contain a Content-Type line, Write adds a Content-Type set
// to the result of passing the initial 512 bytes of written data to
// DetectContentType. Additionally, if the total size of all written
// data is under a few KB and there are no Flush calls, the
// Content-Length header is added automatically.
Write([]byte) (int, error)
所以你應(yīng)該是這樣的:authError()
func authError(w http.ResponseWriter, err error, clientMsg string) {
log.Println("Authentication failed: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
err = json.NewEncoder(w).Encode(struct {
Error string
}{Error: clientMsg})
if err != nil {
log.Println("Failed to write response: %v", err)
}
return
}
- 1 回答
- 0 關(guān)注
- 109 瀏覽
添加回答
舉報(bào)