在Go(Golang)中设置响应中的HTTP状态代码的教程

896 阅读2分钟

概述

net/http包中ResponseWriter接口的WriteHeader方法可以用来返回golang服务器的状态代码。

在GO中,响应是由ResponseWriter接口表示的。 以下是该接口的链接 -

golang.org/pkg/net/htt…

ResponseWriter接口被HTTP处理程序用来构建一个HTTP响应。它提供了三个函数来设置响应参数

  • Header - 用于编写响应头

  • Write([]byte) - 用于写入响应的正文

  • WriteHeader(statusCode int) - 用于写入http状态码

正如你所看到的,WriteHeader函数将statusCode作为输入,该状态码将在HTTP响应中发送。而Write函数可以用来设置响应体。需要注意的是,如果WriteHeader没有被明确调用,那么对Write函数的调用将在内部调用WriteHeader函数,状态代码为200,即StatusOk。

例子

让我们看一个发送http状态码和正文的例子

下面是同样的程序

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.StatusCreated)
	w.Header().Set("Content-Type", "application/json")
	resp := make(map[string]string)
	resp["message"] = "Status Created"
	jsonResp, err := json.Marshal(resp)
	if err != nil {
		log.Fatalf("Error happened in JSON marshal. Err: %s", err)
	}
	w.Write(jsonResp)
	return
}

这里我们使用WriteHeader函数来指定201的http状态代码。同样地,我们可以向WriteHeader函数发送这里列出的任何状态代码

golang.org/src/net/htt…

同时,它使用Write函数来返回响应体。上述代码在响应中返回以下JSON请求体

{"message":"Status Created"}

运行上述程序。它将在你的本地机器上启动一个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 201 Created
< Date: Sat, 10 Jul 2021 10:40:33 GMT
< Content-Length: 28
< Content-Type: text/plain; charset=utf-8
< 
* Connection #0 to host localhost left intact
{"message":"Status Created"}

你可以从输出中看到,它将正确地返回201状态代码和正文。

你也可以直接将201传递给WriteHeader函数来发送201响应。

w.WriteHeader(201)

试试吧,会有效果的。

我们提到,我们没有明确地调用WriteHeader,那么对Write函数的调用将在内部调用WriteHeader函数,状态码为200,即StatusOk。让我们看一个例子--

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.Header().Set("Content-Type", "application/json")
	resp := make(map[string]string)
	resp["message"] = "Success"
	jsonResp, err := json.Marshal(resp)
	if err != nil {
		log.Fatalf("Error happened in JSON marshal. Err: %s", err)
	}
	w.Write(jsonResp)
	return
}

请看上面的代码。我们没有在任何地方调用WriteHeader函数。因此,该程序应该默认发送状态代码200。

运行上述程序。它将在你的本地机器上启动一个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 200 OK
< Content-Type: application/json
< Date: Sat, 10 Jul 2021 16:24:11 GMT
< Content-Length: 21
< 
* Connection #0 to host localhost left intact
{"message":"Success"}

你可以从输出中注意到,它返回200状态代码。