Created
October 5, 2017 18:28
-
-
Save amanelis/25e1570005946390d35fe8f080745e5f to your computer and use it in GitHub Desktop.
Golang async stock quote fetcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"sync" | |
"time" | |
) | |
var prf = fmt.Printf | |
var srf = fmt.Sprintf | |
var client = http.Client{ | |
Timeout: time.Second * 2, | |
} | |
var syms = []string{ | |
"AAPL", | |
"AMZN", | |
"FB", | |
"GOOG", | |
"LMT", | |
"LULU", | |
"NKE", | |
"SBUX", | |
"SNAP", | |
"XOM", | |
"YHOO", | |
} | |
type Symbol struct { | |
Change int `json:"-"` | |
ChangePercent float64 `json:"ChangePercent"` | |
ChangePercentYTD float64 `json:"ChangePercentYTD"` | |
ChangeYTD float64 `json:"ChangeYTD"` | |
High float64 `json:"High"` | |
LastPrice float64 `json:"LastPrice"` | |
Low float64 `json:"Low"` | |
MSDate int `json:"-"` | |
MarketCap int `json:"MarketCap"` | |
Name string `json:"Name"` | |
Open float64 `json:"Open"` | |
Status string `json:"Status"` | |
Symbol string `json:"Symbol"` | |
Timestamp string `json:"Timestamp"` | |
Volume int `json:"Volume"` | |
} | |
func process(i int, s string, wg *sync.WaitGroup) { | |
url := srf("http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=%s", s) | |
req, err := http.NewRequest(http.MethodGet, url, nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
req.Header.Set("User-Agent", "golang-local") | |
res, getErr := client.Do(req) | |
if getErr != nil { | |
log.Fatal(getErr) | |
} | |
body, readErr := ioutil.ReadAll(res.Body) | |
if readErr != nil { | |
log.Fatal(readErr) | |
} | |
var symbol Symbol | |
jsonErr := json.Unmarshal(body, &symbol) | |
if jsonErr != nil { | |
log.Fatal(jsonErr) | |
} | |
prf("worker.%-6d %-6s - open[%-10.6f], close[%-8.6f]\n", i, s, symbol.Open, symbol.LastPrice) | |
wg.Done() | |
} | |
func main() { | |
var wg sync.WaitGroup | |
for i := 0; i < len(syms); i++ { | |
wg.Add(1) | |
go process(i, syms[i], &wg) | |
} | |
wg.Wait() | |
fmt.Println("All go routines finished executing, stopping process.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment