2017-08-25 7 views
1

今日、私は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とないように体が欲しいのです。これは、テスト\である "}] "}

: "\" は "\" この は、試験体の\"、\" 説明\です文字列。どのように私はそれを達成することができますか?

+1

あなたのコードがそれをダブルエンコードするためにのみ、二重エンコードされます。本文をJSONにエンコードし、そのJSONを別の構造体のフィールドに入れてから、* JSONに*エンコードします。あなたがそれをしないと、あなたが望む結果を得るでしょう。 – Adrian

+1

これも便利ですhttps://mholt.github.io/json-to-go/ – RayfenWindspear

答えて

1

HttpRespとは別にマーシャリングすることはできません。代わりにBodyフィールドのタイプをinterface{}に変更し、フィールドをjson文字列ではなく具体的​​なタイプの任意の値に設定します。 []Articleし、respを一度マーシャリングします。

type HttpResp struct{ 
    Status  int   `json:"status"` 
    Description string  `json:"description"` 
    Body  interface{} `json:"body"` 
} 

そして残り...

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) 
    } 

    w.Header().Set("Content-Type", "application/json") 
    json.NewEncoder(w).Encode(HttpResp{Status: 200, Body: articles}) 
} 
+0

はい!ありがとう! 私は4時間前のようにそれを学び始めましたが、インターフェイスタイプについてまだ学んでいませんでしたが、それについて少しお読みになります。 –

関連する問題