-
-
Save nilium/2ce96b86aba257d52a84376fb3b314e8 to your computer and use it in GitHub Desktop.
Helping kevinburke
This file contains hidden or 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" | |
"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