Golang如何在HTTP响应中更改状态码和响应体?

huangapple go评论132阅读模式
英文:

Golang Changing HTTP Response Status Code 201 with Body in the Response

问题

你好!要同时设置响应状态码为201并在响应体中包含JSON对象,你可以按照以下步骤进行操作:

  1. 首先,确保你的开发环境支持操作HTTP响应。
  2. 创建一个包含你要返回的JSON对象的变量。
  3. 设置响应状态码为201。
  4. 将JSON对象转换为字符串格式。
  5. 将字符串作为响应体返回。

以下是一个示例代码片段,展示了如何实现上述步骤:

import json

# 创建要返回的JSON对象
response_data = {
    "message": "Success",
    "data": {
        "key": "value"
    }
}

# 设置响应状态码为201
response_status_code = 201

# 将JSON对象转换为字符串
response_body = json.dumps(response_data)

# 返回响应
return response_status_code, response_body

请根据你的具体开发环境和需求进行相应的调整。希望对你有帮助!

英文:

How do I set the response status code to 201 while including a JSON object in the response body? I can't seem to perform both of these at once -- either I return a 200 with a message body, or a 201 without one.

答案1

得分: 8

我刚刚尝试了一下,似乎可以工作。

你有一段错误的代码示例吗?

简单示例:(https://play.golang.org/p/xg8lGNofze)

package main

import (
	"encoding/json"
	"log"
	"net/http"
)

func testHdlr(w http.ResponseWriter, req *http.Request) {
	m := map[string]string{
		"foo": "bar",
	}
	w.Header().Add("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	_ = json.NewEncoder(w).Encode(m)
}

func main() {
	http.HandleFunc("/", testHdlr)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

然后执行:

$> curl -v http://localhost:8080
[...]
< HTTP/1.1 201 Created
< Date: Thu, 25 May 2017 00:54:15 GMT
< Content-Length: 14
< Content-Type: application/json
< 
{ [14 bytes data]
* Curl_http_done: called premature == 0

100    14  100    14    0     0   2831      0 --:--:-- --:--:-- --:--:--  3500
* Connection #0 to host localhost left intact
{"foo":"bar"}
英文:

I just tried and it seems to work.

Would you have a sample of broken code?

Simple example: (https://play.golang.org/p/xg8lGNofze)

package main

import (
	&quot;encoding/json&quot;
	&quot;log&quot;
	&quot;net/http&quot;
)

func testHdlr(w http.ResponseWriter, req *http.Request) {
	m := map[string]string{
		&quot;foo&quot;: &quot;bar&quot;,
	}
    w.Header().Add(&quot;Content-Type&quot;, &quot;application/json&quot;)
	w.WriteHeader(http.StatusCreated)
	_ = json.NewEncoder(w).Encode(m)
}

func main() {
	http.HandleFunc(&quot;/&quot;, testHdlr)
	log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))
}

Then

$&gt; curl -v http://localhost:8080
[...]
&lt; HTTP/1.1 201 Created
&lt; Date: Thu, 25 May 2017 00:54:15 GMT
&lt; Content-Length: 14
&lt; Content-Type: application/json
&lt; 
{ [14 bytes data]
* Curl_http_done: called premature == 0

100    14  100    14    0     0   2831      0 --:--:-- --:--:-- --:--:--  3500
* Connection #0 to host localhost left intact
{&quot;foo&quot;:&quot;bar&quot;}

huangapple
  • 本文由 发表于 2017年5月25日 08:16:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/44170367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定