对一个请求的多个 JSON 响应

将错误传递到服务器:uid1


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


就我的理解而言,一旦回复被写给回复作者,它就完成了;这似乎不是真的。


我在哪里可以阅读有关此内容的更多信息,我在这里解决的确切问题是什么?


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)

    }

}

这是邮递员的输出:


{

    "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"

}

http://img4.mukewang.com/631ef0010001d1c809840912.jpg

ibeautiful
浏览 67回答 1
1回答

ABOUTYOU

所有写入到响应编写器写入通过网络传输的响应正文。当处理程序返回到网络/http 服务器时,响应完成。添加返回语句以修复问题。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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go