普通网友 2018-05-21 07:18
浏览 340
已采纳

在GO中返回简单的JSON响应

I am currently moving an Express API over to a Golang implementation.

In Express, if I want to return a simple, ad hoc json response I can do like

app.get('/status', (req, res) => res.json({status: 'OK'}))

However, I am struggling to understand this in Go.

Do I need to create a struct for this simple response?

I was trying something like this

func getStatus(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode({status: "OK"})
}

but this is obviously not going to work.

  • 写回答

1条回答 默认 最新

  • dpvp56187 2018-05-21 07:20
    关注

    For something that simple, you can just send a string:

    w.Write(`{"status":"OK"}`)
    

    But to answer your broader question, you need to define your object in Go notation. This can be as simple as:

    json.NewEncoder(w).Encode(map[string]string{"status": "OK"})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?