Skip to content

Instantly share code, notes, and snippets.

@jouyouyun
Created February 17, 2014 08:09
Show Gist options
  • Save jouyouyun/9046641 to your computer and use it in GitHub Desktop.
Save jouyouyun/9046641 to your computer and use it in GitHub Desktop.
Golang Post Test
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
const (
MAP_GOOGLE_GEOCODE = "http://maps.googleapis.com/maps/api/geocode/json"
MAP_GOOGLE_TIMEZONE = "https://maps.googleapis.com/maps/api/timezone/json"
)
type geocodeInfo struct {
results struct {
formatted_address string
geometry struct {
location struct {
lat float64
lng float64
}
}
}
}
func parseGeocode(city, lan string) {
datas := make(map[string][]string)
datas["address"] = []string{city}
datas["sensor"] = []string{"false"}
datas["language"] = []string{lan}
values := url.Values(datas)
fmt.Println("Geocode values:", values)
rets := clientPostRequest(MAP_GOOGLE_GEOCODE, values)
fmt.Println("Geocode post ret:\n", string(rets))
info := &geocodeInfo{}
err := json.Unmarshal(rets, info)
if err != nil {
fmt.Println("Parse geocode json failed:", err)
panic(err)
}
fmt.Println("Address:", info.results.formatted_address)
fmt.Println("Location:", info.results.geometry.location.lat,
" , ", info.results.geometry.location.lng)
}
func parseTimezone(lat, lng string) {
datas := make(map[string][]string)
datas["location"] = []string{lat + "," + lng}
datas["timestamp"] = []string{"1331161200"}
datas["sensor"] = []string{"false"}
values := url.Values(datas)
fmt.Println("Timezone values:", values)
rets := clientPostRequest(MAP_GOOGLE_TIMEZONE, values)
fmt.Println("Timezone post ret:", string(rets))
}
func clientPostRequest(api string, datas url.Values) []byte {
client := &http.Client{
CheckRedirect: nil,
}
response, err := client.PostForm(api, datas)
if err != nil {
fmt.Println("client post failed:", err)
panic(err)
}
if response.StatusCode != 200 {
fmt.Println("response failed, status:", response.StatusCode)
panic(response.StatusCode)
}
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
return body
}
func main() {
parseGeocode("Shanghai", "en")
parseTimezone("37.77492950", "-122.41941550")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment