1 回答

TA貢獻1864條經驗 獲得超2個贊
w
不是指針,但它是接口類型,它將指針包裝在引擎蓋下。因此,您可以按原樣傳遞它,當您調用其方法時,它將反映在調用方中。
只是不要忘記,如果之前有任何東西寫到響應,你不能(再次)寫標題。同樣,如果您向輸出寫入某些內容,則調用方無法將其取回。如果生成響應,則在這種情況下,調用方應返回。authError()
authError()
另請注意,必須首先設置標頭,然后調用 ,然后才能寫入響應正文。ResponseWriter.WriteHeader()
如果調用 ,則將寫入響應狀態(如果尚未寫入)(假設 )。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)
所以你應該是這樣的: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 關注
- 101 瀏覽
添加回答
舉報