Skip to content

Instantly share code, notes, and snippets.

@floydkots
Created June 4, 2018 14:35
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 floydkots/ec681ca61b38611de1e26e51cd139b71 to your computer and use it in GitHub Desktop.
Save floydkots/ec681ca61b38611de1e26e51cd139b71 to your computer and use it in GitHub Desktop.
Go Asynchronous Web Service Calls
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, &quote)
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