如何在REST端点中将结构作为有效JSON返回?

问题描述 投票:-1回答:1

我从API中获取一些数据,我希望在Go应用程序的REST端点中提供这些数据。

结构是这样的:

type Stock struct {
    Stock     string            `json:"message_id,omitempty"`
    StockData  map[string]interface{} `json:"status,omitempty"`
}

//
var StockDataMap Stock

如果在控制台中打印,它看起来应该如此。

我的控制器是这样的:

package lib

import (
    "net/http"
    "log"
    "encoding/json"
)

func returnStocksFromMemory(w http.ResponseWriter, r *http.Request) {
    json.Marshal(StockDataMap)
}


// Expose controller at http://localhost:8081/
func StockMarketDataController() {
    http.HandleFunc("/stocks", returnStocksFromMemory)
    log.Fatal(http.ListenAndServe(":8081", nil))
}

打印StockDataMap会产生一个关键:hashtable,这就是我想要的。但是,访问http://localhost:8081/stocks时,它什么都不返回。

returnStocksFromMemory肯定是问题所在。但是如何在那里将结构返回到有效的JSON?现在,它说是空的。

json rest go
1个回答
2
投票

看起来你是来自Ruby或其他语言,其中尾部位置的值是返回值,异常用于处理错误。在Go中,您需要明确错误处理和返回。

这是在Go中开发Web应用程序的好文章;

https://golang.org/doc/articles/wiki/

就returnStocksFromMemory而言,我会做出以下更改,确保您使用新名称更新HandleFunc:

func stocksHandler(w http.ResponseWriter, r *http.Request) {
    enc := json.NewEncoder(w)
    err := enc.Encode(StockDataMap)
    if err != nil {
      http.Error(w, err.Error(), http.StatusInternalServerError)
      return
    }
}

请注意,您的代码概述了它只会返回{}。您需要使用值填充StockDataMap。功能名称的变化是双重的;

  1. Idiomatic Go使用简洁的名称。
  2. 处理程序通常用作http处理程序的后缀。

我鼓励您阅读Effective Go文章,以帮助您将当前的开发模型映射到Go;

https://golang.org/doc/effective_go.html

在命名事项时,您可以查看此幻灯片;

https://talks.golang.org/2014/names.slide#1

© www.soinside.com 2019 - 2024. All rights reserved.