How to encode url parameters in golang?

go
11,788

Solution 1

There is the one of method to get it.

package main

import (
    "fmt"
    "net/url"
    "encoding/json"
)

func main() {
    m := map[string]interface{}{"app_id": "you_api", "app_sign": "md5_base_16", "timestamp": "1473655478000"}
    json_str, _ := json.Marshal(m)
    fmt.Println(string(json_str[:]))

    values := url.Values{"para": {string(json_str[:])}}

    fmt.Println(values.Encode())

}

Solution 2

Here you can view how to urlencode a 'key-set' for send a request (like query params or form values)

import "net/url"
encoded := url.Values{}
encoded.Set("grant_type", "urn:ibm:params:oauth:grant-type:apikey")
encoded.Set("apikey", conf.Apikey)

For further information have a look here: https://github.com/alessiosavi/GoCloudant/blob/a8ad3a7990f04ea728bb327d6faea6af3e5455ca/cloudant.go#L117

Here a few-lines-library that wrap the builtin library for execute HTTP request used in the previous code: https://github.com/alessiosavi/Requests

Share:
11,788

Related videos on Youtube

shaidiren
Author by

shaidiren

Updated on May 25, 2022

Comments

  • shaidiren
    shaidiren almost 2 years

    Is there any go package to encode url?I need to encode a parameter(type in map[string]interface{}) before it was transfered in url.

    Maybe the parameter likes:map[string]interface{}{"app_id":"you_api","app_sign":"md5_base_16","timestamp":"1473655478000"} How to encode it and what the encoded result would be?

    • Roland Illig
      Roland Illig over 7 years
      Please add how the generated URL should look like. Currently the question is too vague.
    • shaidiren
      shaidiren over 7 years
      host:port/path?para={"key1": value1,"key2":"value2"}, I want to encode the parameter(in map structure) and transport it with json_encoded @RolandIllig