Skip to content

Instantly share code, notes, and snippets.

@nilium
Forked from kevinburke/concurrency.go
Last active May 3, 2016 22:41
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 nilium/2ce96b86aba257d52a84376fb3b314e8 to your computer and use it in GitHub Desktop.
Save nilium/2ce96b86aba257d52a84376fb3b314e8 to your computer and use it in GitHub Desktop.
Helping kevinburke
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
)
func getjson(loc string, dst interface{}) error {
req, err := http.NewRequest("GET", loc, nil)
req.Header.Set("Accept", "application/json")
if err != nil {
return err
}
resp, err := http.Get(loc)
if err != nil {
return err
}
defer func() {
if _, ce := io.Copy(ioutil.Discard, resp.Body); ce != nil {
log.Print("Error discarding response body for ", loc, ": ", ce)
}
if ce := resp.Body.Close(); ce != nil {
log.Print("Unable to close response for ", loc, ": ", ce)
}
}()
return json.NewDecoder(resp.Body).Decode(dst)
}
type jsonIP struct {
IP net.IP
loc string
err error
}
func main() {
ipch := make(chan jsonIP, 1)
getip := func(loc string) {
ip := jsonIP{loc: loc}
ip.err = getjson(loc, &ip)
ipch <- ip
}
go getip("http://ipinfo.io/json")
go getip("http://jsonip.com")
lhs := <-ipch
if lhs.err != nil {
log.Print("Error requesting IP from ", lhs.loc, ":", lhs.err)
}
rhs := <-ipch
if rhs.err != nil {
log.Print("Error requesting IP from ", rhs.loc, ":", rhs.err)
}
fmt.Print(rhs.loc, " IP result: ", rhs.IP, "\n")
fmt.Print(lhs.loc, " IP result: ", lhs.IP, "\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment