概述
golang的net/http包提供了状态码常量,可以用来返回不同的状态码----
HTTP 403状态代码由以下常量定义:
http.StatusForbidden
在这篇文章中,我们还将看到如何在返回403(禁止)状态代码的同时返回一个JSON体。
程序
下面是同样的程序
package main
import (
"encoding/json"
"log"
"net/http"
)
func main() {
handler := http.HandlerFunc(handleRequest)
http.Handle("/example", handler)
http.ListenAndServe(":8080", nil)
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
w.Header().Set("Content-Type", "application/json")
resp := make(map[string]string)
resp["message"] = "Forbidden"
jsonResp, err := json.Marshal(resp)
if err != nil {
log.Fatalf("Error happened in JSON marshal. Err: %s", err)
}
w.Write(jsonResp)
return
}
这里我们使用WriteHeader函数来指定403状态代码,并使用Write函数来返回响应体。
{"message":"Forbidden"}
运行上述程序。它将在你的本地机器上启动一个8080端口的服务器。现在对服务器进行下面的curl调用
curl -v -X POST http://localhost:8080/example
下面将是输出结果
* Connected to localhost (::1) port 8080 (#0)
> POST /example HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 403 Forbidden
< Date: Sat, 10 Jul 2021 08:16:22 GMT
< Content-Length: 23
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
{"message":"Forbidden"}
你可以从输出中看到,它将正确地返回403状态代码和正文。
你也可以直接将403传递给WriteHeader函数来发送403响应:
w.WriteHeader(403)
这也能正确工作。试一试吧。