我剛剛開始學習GoLang,我正在嘗試構建一個簡單的Rest API Web服務器。有沒有辦法在golang中格式化這個json?
這裏的響應結構我想給每個請求發送到Web服務器:
package main
type HttpResp struct{
Status int `json:"status"`
Description string `json:"description"`
Body string `json:"body"`
}
這是我的articles.go文件誰擁有誰得到數據庫中的所有文章的功能:
package main
import (
"encoding/json"
"net/http"
"log"
)
type Article struct{
Id string `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
Description string `json:"description"`
}
func AllArticles(w http.ResponseWriter, r *http.Request){
log.Print("/articles - GET")
db := connect()
defer db.Close()
var articles []Article
results, err := db.Query("SELECT * FROM Articles")
if err != nil{
log.Print(err)
return
}
for results.Next(){
var article Article
err = results.Scan(&article.Title, &article.Description, &article.Body, &article.Id)
if err != nil{
serr, _ := json.Marshal(err)
json.NewEncoder(w).Encode(HttpResp{Status: 500, Description: "Failed to retrieve all articles", Body: string(serr)})
}
articles = append(articles, article)
}
sarr, _ := json.Marshal(articles)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(HttpResp{Status: 200, Body: string(sarr)})
}
我這裏面臨的問題是,反應是這樣的:
{「status」:200,「description」:「」,「body」:「[{\」id \「:\」1 \「,\」title \「:\」First \「,\」body \ 「:\」 這是 人體試驗\ 「\ 」描述\「:\ 」這是一個測試\「}]」}
我想身體只是JSON和不一個字符串。我怎麼能實現這個目標?
這只是雙重編碼,因爲你的代碼雙重編碼它。將身體編碼爲JSON,然後將該JSON放入另一個結構的字段中,然後將* that *編碼爲JSON。如果你不這樣做,你會得到你想要的結果。 – Adrian
這也有用https://mholt.github.io/json-to-go/ – RayfenWindspear