简体   繁体   English

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

[英]How do I return a struct as valid JSON in a REST endpoint?

I am fetching some data from an API, which I want to serve in a REST endpoint from my Go application. 我正在从API中获取一些数据,我希望通过Go应用程序在REST端点中提供这些数据。

the struct is as such: 结构是这样的:

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

//
var StockDataMap Stock

And if printed in the console, it looks as it's supposed to. 如果在控制台中打印,它看起来应该像预期的那样。

My controller is as such: 我的控制器就是这样:

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

Printing StockDataMap results in a key:hashtable, which is what I want. 打印StockDataMap产生一个key:hashtable,这就是我想要的。 However, when accessing http://localhost:8081/stocks , it returns nothing. 但是,当访问http://localhost:8081/stocks ,它不返回任何内容。

returnStocksFromMemory surely is the problem. returnStocksFromMemory肯定是问题所在。 But how do I return the struct to valid JSON in there? 但是,如何在其中将结构返回到有效的JSON? Right now, it's empty as said. 现在,它是空的。

It looks like you're coming from Ruby or another language where a value in the tail position is the return value and exceptions are used to handle errors. 看起来您来自Ruby或另一种语言,其中尾位置的值是返回值,并且异常用于处理错误。 In Go you need to be explicit with both error handling and returns. 在Go中,您需要同时明确处理错误和返回。

This is a good article for developing a web app in Go; 这是在Go中开发Web应用程序的好文章。

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

In terms of your returnStocksFromMemory I would make the following changes ensuring you update HandleFunc with the new name appropriately: 根据您的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
    }
}

Note as your code is outlined it will only return {} . 请注意,因为代码概述了,它只会返回{} You need to populate the StockDataMap with values. 您需要使用值填充StockDataMap The change in function name is two-fold; 函数名称的更改有两个:

  1. Idiomatic Go uses concise names. 惯用Go使用简洁的名称。
  2. Handler is generally used as a postfix for http handlers. 处理程序通常用作http处理程序的后缀。

I would encourage you to read Effective Go article to help you map your current model of development to Go; 我鼓励您阅读“有效的Go”文章,以帮助您将当前的开发模型映射到Go。

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

On naming things you can review this slide deck; 在命名时,您可以查看此幻灯片。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM