一个请求对应多个JSON响应

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

Multiple JSON responses to one request

问题

一个错误的uid被传递给了服务器:1

以下代码为单个请求返回了3个JSON响应。

据我理解,一旦响应被写入ResponseWriter,就表示完成了;但这似乎不是真的。

我在哪里可以找到更多关于这个问题的信息,我在这里解决的确切问题是什么?

func getJob(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    vars := mux.Vars(r)
    job_id := vars["job_id"]
    var job job
    
    // 对UUID job_id进行基本验证
    uid, err := uuid.FromString(job_id)

    fmt.Println(uid)
    fmt.Println(err)

    if _, err := uuid.FromString(job_id); err != nil {
        sendErrorResponse(w, "Invalid job id "+job_id, err)
    }

    if result := db.Where("job_id = ?", uid).First(&job); result.Error != nil {
        sendErrorResponse(w, "Error retrieving job with "+job_id, result.Error)
    }

    json.NewEncoder(w).Encode(job)
}


func sendErrorResponse(w http.ResponseWriter, message string, err error) {
    w.WriteHeader(http.StatusInternalServerError)
    if err := json.NewEncoder(w).Encode(Response{Message: message, Error: err.Error()}); err != nil {
        panic(err)
    }
}

这是Postman的输出:

{
    "Message": "Invalid job id 1",
    "Error": "uuid: incorrect UUID length: 1"
}
{
    "Message": "Error retrieving job with 1",
    "Error": "record not found"
}
{
    "ID": 0,
    "CreatedAt": "0001-01-01T00:00:00Z",
    "UpdatedAt": "0001-01-01T00:00:00Z",
    "DeletedAt": null,
    "application": "",
    "status": "",
    "worker": "",
    "job_id": "00000000-0000-0000-0000-000000000000"
}

一个请求对应多个JSON响应

英文:

A wrong uid is passed to the server : 1

The following code returns 3 JSON responses for a single request.

As far as my understanding goes, as soon as the Response is written to the ResponseWriter its done; this doesn't appear to be true.

Where do I read more about this and what's the exact issue I am tackling here?

func getJob(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	vars := mux.Vars(r)
	job_id := vars["job_id"]
	var job job
	
    // basic validation for UUID job_id
	uid, err := uuid.FromString(job_id)

	fmt.Println(uid)
	fmt.Println(err)

	if _, err := uuid.FromString(job_id); err != nil {
		sendErrorResponse(w, "Invalid job id "+job_id, err)
	}

	if result := db.Where("job_id = ?", uid).First(&job); result.Error != nil {
		sendErrorResponse(w, "Error retrieving job with "+job_id, result.Error)
	}

	json.NewEncoder(w).Encode(job)
}


func sendErrorResponse(w http.ResponseWriter, message string, err error) {
	w.WriteHeader(http.StatusInternalServerError)
	if err := json.NewEncoder(w).Encode(Response{Message: message, Error: err.Error()}); err != nil {
		panic(err)
	}
}

Here's the output in Postman :

{
    "Message": "Invalid job id 1",
    "Error": "uuid: incorrect UUID length: 1"
}
{
    "Message": "Error retrieving job with 1",
    "Error": "record not found"
}
{
    "ID": 0,
    "CreatedAt": "0001-01-01T00:00:00Z",
    "UpdatedAt": "0001-01-01T00:00:00Z",
    "DeletedAt": null,
    "application": "",
    "status": "",
    "worker": "",
    "job_id": "00000000-0000-0000-0000-000000000000"
}

一个请求对应多个JSON响应

答案1

得分: 3

所有对http.ResponseWriter的写入都会写入到通过网络传输的响应主体中。当处理程序返回给net/http服务器时,响应完成。

添加返回语句以解决问题。

if _, err := uuid.FromString(job_id); err != nil {
    sendErrorResponse(w, "无效的作业ID "+job_id, err)
    return
}

if result := db.Where("job_id = ?", uid).First(&job); result.Error != nil {
    sendErrorResponse(w, "检索作业时出错 "+job_id, result.Error)
    return
}
英文:

All writes to the http.ResponseWriter are written to the response body transmitted over the network. The response is completed when the handler returns to the net/http server.

Add return statements to fix the problem.

if _, err := uuid.FromString(job_id); err != nil {
    sendErrorResponse(w, "Invalid job id "+job_id, err)
    return
}

if result := db.Where("job_id = ?", uid).First(&job); result.Error != nil {
    sendErrorResponse(w, "Error retrieving job with "+job_id,  result.Error)
    return
}

huangapple
  • 本文由 发表于 2021年7月3日 14:35:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/68233786.html
匿名

发表评论

匿名网友

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

确定