/* Build URL for an API method call. Note that when using GET, we will also append query parameter to URL */ func (api *Api) buildUrl(method string, option map[string]string) string { q := url.Values{} for k, v := range option { q.Add(k, v) } return api.config.Endpoint(method) + "?" + q.Encode() }
func (cli *HyperClient) GetPodInfo(podName string) (string, error) { // get the pod or container info before we start the exec v := url.Values{} v.Set("podName", podName) body, _, err := readBody(cli.call("GET", "/pod/info?"+v.Encode(), nil, nil)) if err != nil { fmt.Printf("Error: %s\n", err) return "", err } out := engine.NewOutput() remoteInfo, err := out.AddEnv() if err != nil { return "", err } if _, err := out.Write(body); err != nil { fmt.Printf("Error reading remote info: %s", err) return "", err } out.Close() if remoteInfo.Exists("hostname") { hostname := remoteInfo.Get("hostname") if hostname == "" { return "", nil } else { return hostname, nil } } return "", nil }
// GetBookmarkCounts call hatena bookmark count api. func GetBookmarkCounts(urls []string) (map[string]int, error) { query := neturl.Values{} for _, url := range urls { u, err := neturl.Parse(url) if err != nil { return map[string]int{}, err } query.Add("url", u.String()) } req, _ := neturl.Parse(EntryCountsAPIURL) req.RawQuery = query.Encode() res, err := http.Get(req.String()) if err != nil { return map[string]int{}, err } body, _ := ioutil.ReadAll(res.Body) defer res.Body.Close() counts := map[string]int{} json.Unmarshal(body, &counts) return counts, nil }
// Issue a request to exchange the current request token for an access token. func (c *UserConfig) GetAccessToken(token string, verifier string, service *Service, client *http.Client) error { // This code used to error out if RequestTokenKey were empty, but // in the interest of being able to operate in a stateless manner this // has been removed. If you want to make sure that the request token // is validated against what is being returned, populate the UserConfig // with a request token stored server-side somewhere, accessed by the // user's session. if c.RequestTokenKey != "" && c.RequestTokenKey != token { return fmt.Errorf("Returned token did not match request token") } c.Verifier = verifier data := url.Values{} if service.ClientConfig.CallbackURL != "" { data.Set("oauth_verifier", verifier) } body := strings.NewReader(data.Encode()) request, err := http.NewRequest("POST", service.AccessURL, body) if err != nil { return err } request.Header.Set("Content-Type", "application/x-www-form-urlencoded") response, err := c.send(request, service, client) if err != nil { return err } err = c.parseAccessToken(response) return err }
// GetBlobSASURI creates an URL to the specified blob which contains the Shared // Access Signature with specified permissions and expiration time. // // See https://msdn.microsoft.com/en-us/library/azure/ee395415.aspx func (b BlobStorageClient) GetBlobSASURI(container, name string, expiry time.Time, permissions string) (string, error) { var ( signedPermissions = permissions blobURL = b.GetBlobURL(container, name) ) canonicalizedResource, err := b.client.buildCanonicalizedResource(blobURL) if err != nil { return "", err } signedExpiry := expiry.UTC().Format(time.RFC3339) signedResource := "b" stringToSign, err := blobSASStringToSign(b.client.apiVersion, canonicalizedResource, signedExpiry, signedPermissions) if err != nil { return "", err } sig := b.client.computeHmac256(stringToSign) sasParams := url.Values{ "sv": {b.client.apiVersion}, "se": {signedExpiry}, "sr": {signedResource}, "sp": {signedPermissions}, "sig": {sig}, } sasURL, err := url.Parse(blobURL) if err != nil { return "", err } sasURL.RawQuery = sasParams.Encode() return sasURL.String(), nil }
func (a *ListVersions) query() string { u := url.Values{} if a.Delimiter != "" { u.Add("delimiter", a.Delimiter) } if a.EncodingType != "" { u.Add("encoding-type", a.EncodingType) } if a.KeyMarker != "" { u.Add("key-marker", a.KeyMarker) } if a.MaxKeys != "" { u.Add("max-keys", a.MaxKeys) } if a.Prefix != "" { u.Add("prefix", a.Prefix) } if a.VersionIdMarker != "" { u.Add("verdion-id-marker", a.VersionIdMarker) } if len(u) > 0 { return u.Encode() } return "" }
func (o *OKCoin) SendAuthenticatedHTTPRequest(method string, v url.Values) (err error) { v.Set("api_key", o.PartnerID) hasher := GetMD5([]byte(v.Encode() + "&secret_key=" + o.SecretKey)) v.Set("sign", strings.ToUpper(HexEncodeToString(hasher))) encoded := v.Encode() path := o.APIUrl + method if o.Verbose { log.Printf("Sending POST request to %s with params %s\n", path, encoded) } headers := make(map[string]string) headers["Content-Type"] = "application/x-www-form-urlencoded" resp, err := SendHTTPRequest("POST", path, headers, strings.NewReader(encoded)) if err != nil { return err } if o.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } return nil }
// GetGameList gets the game information from the DB. func GetGameList(req GGLReq) (*GGLResp, error) { u, err := url.Parse(GDBURL) u.Path = GGLPath q := url.Values{} if req.Name == "" { return nil, fmt.Errorf("must provide Name") } q.Set("name", req.Name) if req.Platform != "" { q.Set("platform", req.Platform) } if req.Genre != "" { q.Set("genre", req.Genre) } u.RawQuery = q.Encode() resp, err := http.Get(u.String()) if err != nil { return nil, fmt.Errorf("getting game list url:%s, error:%s", u, err) } defer resp.Body.Close() r := &GGLResp{} decoder := xml.NewDecoder(resp.Body) if err := decoder.Decode(r); err != nil { return nil, err } if r.XMLName.Local == "Error" { return nil, fmt.Errorf("GetGameList error: %s", r.err) } else { r.err = "" } return r, nil }
func (k *Kraken) SendAuthenticatedHTTPRequest(method string, values url.Values) (interface{}, error) { path := fmt.Sprintf("/%s/private/%s", KRAKEN_API_VERSION, method) values.Set("nonce", strconv.FormatInt(time.Now().UnixNano(), 10)) secret, err := Base64Decode(k.APISecret) if err != nil { return nil, err } shasum := GetSHA256([]byte(values.Get("nonce") + values.Encode())) signature := Base64Encode(GetHMAC(HASH_SHA512, append([]byte(path), shasum...), secret)) if k.Verbose { log.Printf("Sending POST request to %s, path: %s.", KRAKEN_API_URL, path) } headers := make(map[string]string) headers["API-Key"] = k.ClientKey headers["API-Sign"] = signature resp, err := SendHTTPRequest("POST", KRAKEN_API_URL+path, headers, strings.NewReader(values.Encode())) if err != nil { return nil, err } if k.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } return resp, nil }
func init() { storeBaseURI, err := url.Parse(cpiURL()) if err != nil { panic(err) } storeSearchURI, err = storeBaseURI.Parse("search") if err != nil { panic(err) } v := url.Values{} v.Set("fields", strings.Join(getStructFields(remote.Snap{}), ",")) storeSearchURI.RawQuery = v.Encode() storeDetailsURI, err = storeBaseURI.Parse("package/") if err != nil { panic(err) } storeBulkURI, err = storeBaseURI.Parse("click-metadata") if err != nil { panic(err) } storeBulkURI.RawQuery = v.Encode() }
func (f *Force) RefreshSession() (err error, emessages []ForceError) { attrs := url.Values{} attrs.Set("grant_type", "refresh_token") attrs.Set("refresh_token", f.Credentials.RefreshToken) attrs.Set("client_id", ClientId) attrs.Set("format", "json") postVars := attrs.Encode() req, err := httpRequest("POST", f.refreshTokenURL(), bytes.NewReader([]byte(postVars))) if err != nil { return } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") fmt.Println("Refreshing Session Token") res, err := doRequest(req) if err != nil { return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if res.StatusCode != 200 { ErrorAndExit("Failed to refresh session. Please run `force login`.") return } if err != nil { return } var result ForceCredentials json.Unmarshal(body, &result) f.UpdateCredentials(result) LogAuth() return }
func (c *Cryptsy) SendAuthenticatedHTTPRequest(method, path string, params url.Values) (err error) { nonce := strconv.FormatInt(time.Now().Unix(), 10) params.Set("nonce", nonce) encoded := params.Encode() hmac := GetHMAC(HASH_SHA512, []byte(encoded), []byte(c.APISecret)) readStr := "" if method == "GET" || method == "DELETE" { path += "?" + encoded } else if method == "POST" { readStr = encoded } if c.Verbose { log.Printf("Sending %s request to %s with params %s\n", method, path, encoded) } headers := make(map[string]string) headers["Key"] = c.APIKey headers["Sign"] = HexEncodeToString(hmac) headers["Content-Type"] = "application/x-www-form-urlencoded" resp, err := SendHTTPRequest(method, path, headers, strings.NewReader(readStr)) if err != nil { return err } if c.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } return nil }
func createRequest(v url.Values) *http.Request { body := strings.NewReader(v.Encode()) req, _ := http.NewRequest("POST", "http://localhost:8080/-/auth/password", body) req.Header.Set("Content-Type", "application/x-www-form-urlencoded;") return req }
func (self *ReportClient) Request(path string, params map[string]string) (ret interface{}, err error) { args := make(map[string]string, len(params)+3) for k, v := range params { args[k] = v } args["api_key"] = self.apiKey args["expire"] = fmt.Sprintf("%d", time.Now().Unix()+600) args["sig"] = hashArgs(self.apiSecret, args) query := url.Values{} for k, v := range args { query.Add(k, v) } url := fmt.Sprintf("%s/%s/%s/?%s", ENDPOINT, VERSION, path, query.Encode()) resp, urlerr := http.Get(url) if urlerr != nil { err = urlerr return } defer resp.Body.Close() body, httperr := ioutil.ReadAll(resp.Body) if httperr != nil { err = httperr return } jsonerr := json.Unmarshal(body, &ret) if jsonerr != nil { err = jsonerr return } return ret, nil }
// CmdRestart restarts one or more running containers. // // Usage: docker stop [OPTIONS] CONTAINER [CONTAINER...] func (cli *DockerCli) CmdRestart(args ...string) error { cmd := cli.Subcmd("restart", "CONTAINER [CONTAINER...]", "Restart a running container", true) nSeconds := cmd.Int([]string{"t", "-time"}, 10, "Seconds to wait for stop before killing the container") cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) v := url.Values{} v.Set("t", strconv.Itoa(*nSeconds)) var errNames []string for _, name := range cmd.Args() { _, _, err := readBody(cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil, nil)) if err != nil { fmt.Fprintf(cli.err, "%s\n", err) errNames = append(errNames, name) } else { fmt.Fprintf(cli.out, "%s\n", name) } } if len(errNames) > 0 { return fmt.Errorf("Error: failed to restart containers: %v", errNames) } return nil }
func postMessage(path, room, message string) ([]byte, error) { data := url.Values{} data.Set("room_id", room) data.Add("message", message) data.Add("from", "hcl") data.Add("notify", "1") data.Add("color", "green") req, err := http.NewRequest("POST", path, bytes.NewBufferString(data.Encode())) if err != nil { fmt.Println("postMessage ERROR: ", err) } // for v2 only //authHeader := fmt.Sprintf("Bearer %s", token) //req.Header.Add("Authentication", authHeader) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println("client do ERROR: ", err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Read body ERROR: ", err) } return body, nil }
func (client *DockerClient) CreateContainer(config *ContainerConfig, name string, auth *AuthConfig) (string, error) { data, err := json.Marshal(config) if err != nil { return "", err } uri := fmt.Sprintf("/%s/containers/create", APIVersion) if name != "" { v := url.Values{} v.Set("name", name) uri = fmt.Sprintf("%s?%s", uri, v.Encode()) } headers := map[string]string{} if auth != nil { encoded_auth, err := auth.encode() if err != nil { return "", err } headers["X-Registry-Auth"] = encoded_auth } data, err = client.doRequest("POST", uri, data, headers) if err != nil { return "", err } result := &RespContainersCreate{} err = json.Unmarshal(data, result) if err != nil { return "", fmt.Errorf(string(data)) } return result.Id, nil }
func searchTrack(context *echo.Context, song *SpotifySong) (*SpotifySong, error) { v := url.Values{} v.Set("type", "track") v.Set("q", song.Name+" artist:"+song.Artist) reqUrl := searchUrl + "?" + v.Encode() resp, err := getWithAuthToken(context, reqUrl) if err != nil { return song, err } defer resp.Body.Close() var result map[string]interface{} err = json.NewDecoder(resp.Body).Decode(&result) if err != nil { return song, err } if resp.StatusCode != http.StatusOK { return song, errors.New("Non-OK http status " + resp.Status) } tracks := result["tracks"].(map[string]interface{}) items := tracks["items"].([]interface{}) if len(items) > 0 { itemObj := items[0].(map[string]interface{}) id := itemObj["id"].(string) song.SpotifyTrackId = id } return song, nil }
func (client *DockerClient) PushImage(name string, tag string, auth *AuthConfig) error { v := url.Values{} if tag != "" { v.Set("tag", tag) } uri := fmt.Sprintf("/%s/images/%s/push?%s", APIVersion, url.QueryEscape(name), v.Encode()) req, err := http.NewRequest("POST", client.URL.String()+uri, nil) if auth != nil { if encodedAuth, err := auth.encode(); err != nil { return err } else { req.Header.Add("X-Registry-Auth", encodedAuth) } } resp, err := client.HTTPClient.Do(req) if err != nil { return err } defer resp.Body.Close() var finalObj map[string]interface{} for decoder := json.NewDecoder(resp.Body); err == nil; err = decoder.Decode(&finalObj) { } if err != io.EOF { return err } if err, ok := finalObj["error"]; ok { return fmt.Errorf("%v", err) } return nil }
func (c *Client) newAuthenticatedRequest(urlToken string, values url.Values) (*http.Request, error) { var req *http.Request var err error switch c.authMethod { case AuthMethodClientSecretPost: values.Set("client_secret", c.creds.Secret) req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode())) if err != nil { return nil, err } case AuthMethodClientSecretBasic: req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode())) if err != nil { return nil, err } encodedID := url.QueryEscape(c.creds.ID) encodedSecret := url.QueryEscape(c.creds.Secret) req.SetBasicAuth(encodedID, encodedSecret) default: panic("misconfigured client: auth method not supported") } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") return req, nil }
func HttpPost(u string, data url.Values) (re *http.Response, err error) { defer func() { if e := recover(); e != nil { err = e.(error) } }() //lg.Trace("\nPOST: URL: %v\nDATA: %v", u, data.Encode()) req, err := http.NewRequest("POST", u, strings.NewReader(data.Encode())) if nil != err { return nil, err } //ErrHandle(err, `p`) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") if client.Jar != nil { for _, cookie := range client.Jar.Cookies(req.URL) { req.AddCookie(cookie) } } req.Header.Add(`referer`, `http://d.web2.qq.com/proxy.html?v=20110331002&callback=2&id=3`) re, err = client.Do(req) if nil != err { return nil, err } //ErrHandle(err, `p`) client.Jar.SetCookies(req.URL, re.Cookies()) return re, nil }
func (f flowDockNotifier) Notify(repos map[string]time.Time) error { keys := make([]string, 0, len(repos)) for k := range repos { keys = append(keys, k) } sort.Strings(keys) var lines []string for _, k := range keys { line := fmt.Sprintf("Repo <https://github.com/%v|%v> was updated at %v", k, k, repos[k]) lines = append(lines, line) } form := url.Values{} form.Set("content", strings.Join(lines, "\n")) form.Set("event", "comment") form.Set("external_user_name", "ghnotify") resp, err := http.Post("https://api.flowdock.com/messages/chat/"+f.FlowToken, "application/x-www-form-urlencoded", strings.NewReader(form.Encode()), ) if err != nil { return fmt.Errorf("error performing POST request: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("unexpected status: %v", resp.Status) } return nil }
func searchAlbum(context *echo.Context, p *PipelineState, song *SpotifySong) (*SpotifySong, error) { if cachedId, ok := p.GetCachedAlbumId(song.Album, song.Artist); ok { song.SpotifyAlbumId = cachedId return song, nil } v := url.Values{} v.Set("type", "album") v.Set("q", song.Album+" artist:"+song.Artist) reqUrl := searchUrl + "?" + v.Encode() resp, err := getWithAuthToken(context, reqUrl) if err != nil { return song, err } defer resp.Body.Close() var result map[string]interface{} err = json.NewDecoder(resp.Body).Decode(&result) if err != nil { return song, err } if resp.StatusCode != http.StatusOK { return song, errors.New("Non-OK http status " + resp.Status) } albums := result["albums"].(map[string]interface{}) items := albums["items"].([]interface{}) if len(items) > 0 { itemObj := items[0].(map[string]interface{}) id := itemObj["id"].(string) song.SpotifyAlbumId = id p.CacheAlbumId(song.Album, song.Artist, id) } return song, nil }
// UploadSignedURL returns a signed URL that allows anyone holding the URL // to upload the object at path. The signature is valid until expires. // contenttype is a string like image/png // path is the resource name in s3 terminalogy like images/ali.png [obviously exclusing the bucket name itself] func (b *Bucket) UploadSignedURL(path, method, content_type string, expires time.Time) string { expire_date := expires.Unix() if method != "POST" { method = "PUT" } stringToSign := method + "\n\n" + content_type + "\n" + strconv.FormatInt(expire_date, 10) + "\n/" + b.Name + "/" + path fmt.Println("String to sign:\n", stringToSign) a := b.S3.Auth secretKey := a.SecretKey accessId := a.AccessKey mac := hmac.New(sha1.New, []byte(secretKey)) mac.Write([]byte(stringToSign)) macsum := mac.Sum(nil) signature := base64.StdEncoding.EncodeToString([]byte(macsum)) signature = strings.TrimSpace(signature) signedurl, err := url.Parse("https://" + b.Name + ".s3.amazonaws.com/") if err != nil { log.Println("ERROR sining url for S3 upload", err) return "" } signedurl.Path += path params := url.Values{} params.Add("AWSAccessKeyId", accessId) params.Add("Expires", strconv.FormatInt(expire_date, 10)) params.Add("Signature", signature) if a.Token() != "" { params.Add("token", a.Token()) } signedurl.RawQuery = params.Encode() return signedurl.String() }
// GetAlbumTracksOpt behaves like GetAlbumTracks, with the exception that it // allows you to specify extra parameters that limit the number of results returned. // The maximum number of results to return is specified by limit. // The offset argument can be used to specify the index of the first track to return. // It can be used along with limit to reqeust the next set of results. func (c *Client) GetAlbumTracksOpt(id ID, limit, offset int) (*SimpleTrackPage, error) { spotifyURL := fmt.Sprintf("%salbums/%s/tracks", baseAddress, id) v := url.Values{} if limit != -1 { v.Set("limit", strconv.Itoa(limit)) } if offset != -1 { v.Set("offset", strconv.Itoa(offset)) } optional := v.Encode() if optional != "" { spotifyURL = spotifyURL + "?" + optional } resp, err := c.http.Get(spotifyURL) if err != nil { return nil, err } defer resp.Body.Close() var result SimpleTrackPage err = json.NewDecoder(resp.Body).Decode(&result) if err != nil { return nil, err } return &result, nil }
func streamLocation(getter ResourceGetter, connInfo client.ConnectionInfoGetter, ctx api.Context, name string, opts runtime.Object, container, path string) (*url.URL, http.RoundTripper, error) { pod, err := getPod(getter, ctx, name) if err != nil { return nil, nil, err } // Try to figure out a container if container == "" { if len(pod.Spec.Containers) == 1 { container = pod.Spec.Containers[0].Name } else { return nil, nil, errors.NewBadRequest(fmt.Sprintf("a container name must be specified for pod %s", name)) } } nodeHost := pod.Spec.NodeName if len(nodeHost) == 0 { // If pod has not been assigned a host, return an empty location return nil, nil, errors.NewBadRequest(fmt.Sprintf("pod %s does not have a host assigned", name)) } nodeScheme, nodePort, nodeTransport, err := connInfo.GetConnectionInfo(nodeHost) if err != nil { return nil, nil, err } params := url.Values{} if err := streamParams(params, opts); err != nil { return nil, nil, err } loc := &url.URL{ Scheme: nodeScheme, Host: fmt.Sprintf("%s:%d", nodeHost, nodePort), Path: fmt.Sprintf("/%s/%s/%s/%s", path, pod.Namespace, name, container), RawQuery: params.Encode(), } return loc, nodeTransport, nil }
// validateToken returns true if token is valid func validateToken(p Provider, access_token string, header http.Header) bool { if access_token == "" || p.Data().ValidateUrl == nil { return false } endpoint := p.Data().ValidateUrl.String() if len(header) == 0 { params := url.Values{"access_token": {access_token}} endpoint = endpoint + "?" + params.Encode() } resp, err := api.RequestUnparsedResponse(endpoint, header) if err != nil { log.Printf("GET %s", endpoint) log.Printf("token validation request failed: %s", err) return false } body, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() log.Printf("%d GET %s %s", resp.StatusCode, endpoint, body) if resp.StatusCode == 200 { return true } log.Printf("token validation request failed: status %d - %s", resp.StatusCode, body) return false }
func (s *guiArchiveSuite) TestGUIArchivePostCurrent(c *gc.C) { // Add an existing GUI archive and set it as the current one. storage, err := s.State.GUIStorage() c.Assert(err, jc.ErrorIsNil) defer storage.Close() vers := version.MustParse("2.0.47") setupGUIArchive(c, storage, vers.String(), nil) err = s.State.GUISetVersion(vers) c.Assert(err, jc.ErrorIsNil) // Create a GUI archive to be uploaded. r, hash, _ := makeGUIArchive(c, vers.String(), map[string]string{"filename": "content"}) // Prepare and send the request to upload a new GUI archive. v := url.Values{} v.Set("version", vers.String()) v.Set("hash", hash) resp := s.authRequest(c, httpRequestParams{ method: "POST", url: s.guiURL(c) + "?" + v.Encode(), contentType: apiserver.BZMimeType, body: r, }) // Check that the response reflects a successful upload. body := assertResponse(c, resp, http.StatusOK, params.ContentTypeJSON) var jsonResponse params.GUIArchiveVersion err = json.Unmarshal(body, &jsonResponse) c.Assert(err, jc.ErrorIsNil, gc.Commentf("body: %s", body)) c.Assert(jsonResponse, jc.DeepEquals, params.GUIArchiveVersion{ Version: vers, SHA256: hash, Current: true, }) }
// GetGame gets the game information from the DB. func GetGame(req GGReq) (*GGResp, error) { u, err := url.Parse(GDBURL) u.Path = GGPath q := url.Values{} switch { case req.ID != "": q.Set("id", req.ID) case req.Name != "": q.Set("name", req.Name) if req.Platform != "" { q.Set("platform", req.Platform) } default: return nil, fmt.Errorf("must provide an ID or Name.") } u.RawQuery = q.Encode() resp, err := http.Get(u.String()) if err != nil { return nil, fmt.Errorf("getting game url:%s, error:%s", u, err) } defer resp.Body.Close() r := &GGResp{} decoder := xml.NewDecoder(resp.Body) if err := decoder.Decode(r); err != nil { return nil, err } if r.XMLName.Local == "Error" { return nil, fmt.Errorf("GetGame error: %s", r.err) } else { r.err = "" } return r, nil }
func Detect_language(q string) string { var Url *url.URL Url, err := url.Parse("https://www.googleapis.com") if err != nil { fmt.Println(err) } Url.Path += "/language/translate/v2/detect" parameters := url.Values{} parameters.Add("q", q) parameters.Add("key", Google_key()) Url.RawQuery = parameters.Encode() resp, err := http.Get(Url.String()) if err != nil { fmt.Println(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) var data gtresponse json.Unmarshal(body, &data) lang := data.Data.Detections[0][0].Language return lang }