在Go(Golang)的HTTP响应中返回202(StatusAccepted)状态的教程

379 阅读1分钟

概述

golang的net/http包提供了状态代码常量,可以用来返回不同的状态代码-golang.org/src/net/htt…

同样也可以用来返回202(StatusAccepted)的HTTP状态代码。 HTTP 202状态码是由下面的常量定义的。

http.StatusAccepted

在这篇文章中,我们还将看到如何在返回202(StatusAccepted)状态码的同时返回一个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.StatusAccepted)
	w.Header().Set("Content-Type", "application/json")
	resp := make(map[string]string)
	resp["message"] = "Status Accepted"
	jsonResp, err := json.Marshal(resp)
	if err != nil {
		log.Fatalf("Error happened in JSON marshal. Err: %s", err)
	}
	w.Write(jsonResp)
	return
}

这里我们使用WriteHeader函数来指定202 http状态代码,并使用Write函数来返回响应体。上述代码在响应中返回以下JSON请求体

{"message":"Status Accepted"}

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

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

你也可以直接把202传给WriteHeader函数来发送202响应。

w.WriteHeader(202)

这也能正确工作。试一试吧。