在Go(Golang)的HTTP响应中返回200(StatusOK)状态代码教程

1,716 阅读1分钟

概述

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

HTTP 200状态代码是由以下常量定义的。

http.StatusOK

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

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

{"message":"Status OK"}

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

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

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

w.WriteHeader(200)

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