Created
June 4, 2018 14:35
-
-
Save floydkots/ec681ca61b38611de1e26e51cd139b71 to your computer and use it in GitHub Desktop.
Go Asynchronous Web Service Calls
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 ( | |
"net/http" | |
"io/ioutil" | |
"encoding/xml" | |
"fmt" | |
"time" | |
"runtime" | |
) | |
func main() { | |
runtime.GOMAXPROCS(4) | |
start := time.Now() | |
stockSymbols := []string { | |
"googl", | |
"msft", | |
"aapl", | |
"bbry", | |
"hpq", | |
"vz", | |
"t", | |
"tmus", | |
"s", | |
} | |
numComplete := 0 | |
for _, symbol := range stockSymbols { | |
go func(symbol string) { | |
resp, _ := http.Get("http://dev.markitondemand.com/Api/v2/Quote?symbol=" + symbol) | |
defer resp.Body.Close() | |
body, _ := ioutil.ReadAll(resp.Body) | |
quote := new(QuoteResponse) | |
xml.Unmarshal(body, "e) | |
fmt.Printf("%s: %.2f\n", quote.Name, quote.LastPrice) | |
numComplete++ | |
} (symbol) | |
} | |
for numComplete < len(stockSymbols) { | |
time.Sleep(10 * time.Millisecond) | |
} | |
elapsed := time.Since(start) | |
fmt.Printf("Execution time: %s", elapsed) | |
} | |
type QuoteResponse struct { | |
Status string | |
Name string | |
LastPrice float32 | |
Change float32 | |
ChangePercent float32 | |
TimeStamp string | |
MSDate float32 | |
MarketCap int | |
Volume int | |
ChangeYTD float32 | |
ChangePercentYTD float32 | |
High float32 | |
Low float32 | |
Open float32 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment