Matty
Matty

Reputation: 283

Accessing Data From Interfaces in Go

I am trying to implement a simple api in Golang. My experience in the backend is more with python and node, so I am having some difficulty printing out data held within the interface since it won't allow me to index it. I have searched around and several people have asked similar questions when the interface is one value, but not when the interface is a slice, I believe ([]interface{}). I have tried vaping the interface to no avail.

When I point the browser to /quandl/ddd/10 I would like to fmt.Println the specific numerical data, i.e. ("2017-01-13", 15.67, 16.41, 15.67, 16.11, 3595248, 0, 1, 15.67, 16.41, 15.67, 16.11, 3595248 ])

 package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"

    "github.com/fatih/color"
    "github.com/gorilla/mux"
)

type QuandlResponse struct {
    SourceCode string      `json:"source_code"`
    SourceName string      `json:"source_name"`
    Code       string      `json:"code"`
    Frequency  string      `json:"frequency"`
    FromDate   string      `json:"from_date"`
    ToDate     string      `json:"to_date"`
    Columns    []string    `json:"column_names"`
    Data       interface{} `json:"data"`
}

func getContent(w http.ResponseWriter, r *http.Request) {
    stock := mux.Vars(r)["stock"]
    limit := mux.Vars(r)["limit"]
    url := "https://www.quandl.com/api/v1/datasets/WIKI/" + url.QueryEscape(stock) + ".json?&limit=" + url.QueryEscape(limit) + "&auth_token=XXXXX"
    response, err := http.Get(url)
    if err != nil {
        fmt.Println(err)
    }
    contents, err := ioutil.ReadAll(response.Body)
    var result QuandlResponse
    json.Unmarshal(contents, &result)
    json.NewEncoder(w).Encode(result)
    fmt.Println(result.Data[0]) 


}
    func callAll() {
        rabbit := mux.NewRouter()
        rabbit.HandleFunc("/quandl/{stock}/{limit}", getContent)
        http.ListenAndServe(":8000", rabbit)
    }

func main() {
    color.Blue("Running Server @localhost:8000")
    callAll()

}

Upvotes: 0

Views: 3024

Answers (1)

Andy Schweig
Andy Schweig

Reputation: 6739

If you know that the type of Data is []interface{}, you can do a type assertion:

slice := result.Data.([]interface{})
fmt.Println(slice[0])

If there are several possibilities for the type of Data, you can use a type switch:

switch data := result.Data.(type) {
case []interface{}:
    fmt.Println(data[0])
case string:
    fmt.Println(data)
default:
    // unexpected type
}

You may also want to look at the reflect package if your requirements are more complicated.

Upvotes: 2

Related Questions