Skip to content

Instantly share code, notes, and snippets.

@yeukhon
Created August 12, 2018 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yeukhon/709ad7cbfb4aab21a4e3e23f05a440eb to your computer and use it in GitHub Desktop.
Save yeukhon/709ad7cbfb4aab21a4e3e23f05a440eb to your computer and use it in GitHub Desktop.
package lib
type StockQuoteResponse struct {
Metadata ResponseMetadata `json:"Meta Data"`
BatchQuote BatchQuoteResponse `json:"Stock Batch Quotes"`
}
type ResponseMetadata struct {
Information string `json:"1. Information"`
Notes string `json:"2. Notes"`
TimeZone string `json:"3. Time Zone"`
}
type BatchQuoteResponse struct {
Quotes []StockQuote `json:"Stock Batch Quotes"`
}
type StockQuote struct {
Symbol string `json:"1. symbol"`
Open string `json:"2. open"`
High string `json:"3. high"`
Low string `json:"4. low"`
Price string `json:"5. price"`
Volume string `json:"6. volume"`
Last_TS string `json:"7. timestamp"`
Currency string `json:"8. currency"`
}
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
"github.com/yeukhon/stock-quote/lib"
)
var API_KEY string = os.Getenv("ALPHA_ADVANTAGE_API_KEY")
var QUOTE_URL string = "https://www.alphavantage.co/query?function=BATCH_QUOTES_US&symbols=MSFT,FB,NFLX,AMZN,IQ&apikey=" + API_KEY
// Modified from the https://stackoverflow.com/questions/17156371
var client = &http.Client{Timeout: time.Second * 5}
func getQuote(url string, target interface{}) error {
r, err := client.Get(url)
if err != nil {
return err
}
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(target)
}
func main() {
stock_quote := new(lib.StockQuoteResponse)
getQuote(QUOTE_URL, stock_quote)
fmt.Println(stock_quote)
}
@yeukhon
Copy link
Author

yeukhon commented Aug 12, 2018

Okay, so I took some advice, and tried to catch error, not sure if I am doing right:

  stock_quote := new(lib.StockQuoteResponse)
  r := getQuote(QUOTE_URL, stock_quote)
  if r != nil {
    panic(r)
  }
  fmt.Println(stock_quote)
}

Now I got

John-Wong:stock-quote jwong$ go run main.go
panic: json: cannot unmarshal array into Go struct field StockQuoteResponse.Stock Batch Quotes of type lib.BatchQuoteResponse

goroutine 1 [running]:
main.main()
	/Users/jwong/yeukhon/git/stock-quote/main.go:30 +0xd3
exit status 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment