在Go中的HTTP响应中返回纯文本正文的方法(Golang)

933 阅读2分钟

概述

net/http包中ResponseWriter接口的Write方法可以用来设置HTTP响应中的text/lainbody。

在GO中,响应是由ResponseWriter接口表示的。 以下是该接口的链接-https://golang.org/pkg/net/http/#ResponseWriter

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

  • Header - 用于编写响应头

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

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

Write函数可以用来设置响应体。它需要一个字节片作为输入。此外,还有一个Header 函数。这个函数可以用来使用Content-Type头来设置响应体的内容类型。例如,在text/plain响应体的情况下,我们需要将Content-Type头设置为**"text/plain"。**

w.Header().Set("Content-Type", "text/plain")

另外,注意WriteHeader 函数可以用来设置响应的HTTP状态代码。

例子

让我们看一个发送HTTP状态码和text/plain响应体的例子

下面是同样的程序

package main

import (
	"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/text")
	w.Write([]byte("Success"))
	return
}

我们使用Write函数来返回text/plain响应体。上述代码在响应中返回以下的文本/纯文本

Success

另外,我们使用WriteHeader函数来指定200http状态代码。 我们也在设置正确的头信息

运行上述程序。它将在你的本地机器上启动一个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 19:01:56 GMT
< Content-Length: 7
< Content-Type: text/plain; charset=utf-8
< 
* Connection #0 to host localhost left intact
Success

你可以从输出中看到,它将正确地返回200状态代码和text/plain正文。此外,响应头的Content-Type也被设置为text/plain