I'm new to Go. My question is how to get URL encoded string on stdout.
Below is the URL string I am using to hit an api.
schooltubeapi/v1/channeldetails?channelName=long%20division%20.
Below is the code that I am using to get RawQuery
url1 := ChannelName
u, _ := url.Parse(url1)
log.Println(u)
u.RawQuery = u.Query().Encode()
log.Println(u)
[Output]
long division
[Expected]
long%20division%20
I have searched alot But cannot found a similar problem with a solution.
For url encoded string use URL struct of url package to get RawQuery as passed in the URI:
package main
import (
"fmt"
"net/url"
)
func main() {
stringValue := "long division "
t := &url.URL{Path: stringValue}
encodedString := t.String()
fmt.Println(encodedString)
}
Playground Example
In Golang spec for URL. It is stated:-
that the Path field is stored in decoded form: /%47%6f%2f becomes
/Go/. A consequence is that it is impossible to tell which slashes in
the Path were slashes in the raw URL and which were %2f. This
distinction is rarely important, but when it is, code must not use
Path directly. The Parse function sets both Path and RawPath in the
URL it returns, and URL's String method uses RawPath if it is a valid
encoding of Path, by calling the EscapedPath method.
type URL struct {
Scheme string
Opaque string // encoded opaque data
User *Userinfo // username and password information
Host string // host or host:port
Path string // path (relative paths may omit leading slash)
RawPath string // encoded path hint (see EscapedPath method)
ForceQuery bool // append a query ('?') even if RawQuery is empty
RawQuery string // encoded query values, without '?'
Fragment string // fragment for references, without '#'
}
For more information Check Golang spec for URL
Related
I'm trying to use the baseX REST API with python's requests post method, using a saved .xq file which contains a query with an &.
When running this saved query directly on baseX, there's no problem.
The request as presented in the response also includes the & as it is and not as an &, but I still get the following error (response code is 400):
" Stopped at C:/Program Files (x86)/BaseX/webapp, 37/37:\n[XPST0003] Invalid entity: '&&", "||", "!")) the...'.' "
The relevant part of the request's body is:
<rest:query xmlns:rest="http://basex.org/rest"> <rest:text>declare function local:enrich_node($attr, $supertype) {
$attr, attribute {"supertype"} {$supertype}
};
declare function local:enrich($n as node()) as node() {
typeswitch($n)
...
case $e as element(operator)
return
...
else if ($e/text()=("&&", "||", "!")) then
element {name($e)}
{local:enrich_node($e/#*, "boolop"), for $c in $e/(* | text())
return local:enrich($c) }
else
...
};
declare variable $assign_id as xs:string external;
declare variable $submission_id as xs:string external;
for $node in db:open($assign_id, $submission_id)
return local:enrich($node)</rest:text><variable name="assign_id" value="val1"/><variable name="submission_id" value="val2"/></rest:query>
When I remove the && part from the query it works.
I tried to look for relevant questions but didn't find anything, other then a suggestion to "escape" it with another & which I tried but then the returned error was with 4 &s.
Any ideas?
As the content of rest:text has to be evaluated as XQuery code but should not be parsed as XML it should help to wrap the XQuery code inside of rest:text in a CDATA section.
To decode API response string to JSON, json.decode() works fine.
This will parse a JSON string similar to
{ "Response" : {"Responsecode" : "1" , "Response" : "Success"}}
But in my case, the response comes in the serialized form like:
{\"Response\" : {\"Responsecode\" : \"0\" , \"Response\" : \"Success\"}}
json.decode() won’t work.
In Java, I used StringEscapeUtils.unescapeJson() for the same problem.
I searched for Dart but couldn’t find how to unescape characters in a string.
Edit:
Suppose, the value of key data is abc"de
So, its corresponding JSON would be {"data":"abc\"de"}
And hence during serialization, this json string is escaped to give {\"data\":\"abc\\\"de\"} as the response, which is sent by the API.
So, my intention is to remove the escape sequences, so that I can get the string {"data":"abc\"de"}, which would later be decoded using json.decode(). Removing the escape sequences was done using StringEscapeUtils.unescapeJson() in java.
json.decode can decode single strings too, so you should be able to just call it twice. The first time it'll return you a string (where the escape characters have been decoded) and the second time it'll decode that string into the map:
import 'dart:convert';
void main() {
var a = r'''"{\"Response\" : {\"Responsecode\" : \"0\" , \"Response\" : \"Success\"}}"''';
var b = json.decode(json.decode(a));
print(b['Response']['Responsecode']); // 0
print(b['Response']['Response']); // Success
}
I am trying to extract the case-insensitive query parameter /staging/ec/23463/front-view-72768.jpg?angle=90&or=0x0&wd=400&ht=200 from the URL. When I try to convert the whole URL in lowercase it throws the following exception :
cannot use r.URL (type *url.URL) as type string in argument to strings.ToLower
I printed the value of URL which says underlying it stores all the query strings as map i.e. map[angle:[90] or:[0x0] wd:[400] ht:[200]]. Hence I will get the correct value using this r.URL.Query().Get("or") But if query string comes out Or. It will fail.
*URL.Query() returns a value of type url.Values, which is just a map[string][]string with a few extra methods.
Since URL values are by definition case-sensitive, you will have to access the map directly.
var query url.Values
for k, vs := range query {
if strings.ToLower(k) == "ok" {
// do something with vs
}
}
Try it on the playground: https://play.golang.org/p/7YVuxI3GO6X
cannot use r.URL (type *url.URL) as type string in argument to strings.ToLower
This is because you are passing ur.URL instead of string. Get the string from url through String() function.
url.String()
In golang How to split a URL and encode back to URL from decoded components. Any packages that do the job?
net/url helps only in decoding the URL. I want to modify the HOST and PORT and recreate the URL. My problem originates from the case where I receive IPV6:port without square brackets. Let us say I get IPV6:port in the format as:
aaa:abbb:cccc:dddd:0000:0000:00aa:bbbb:8080/static/silly.html
I want to reconstruct the URL with brackets arround IPV6 address.
I think that would not be possible. For instance, if you get:
2001:db8::1:80
How could you tell if the IP address is
2001:db8::1
Or:
2001:db8::1:80
That is the reason why RFC 5952 recommands to use brackets (or some other characters) to distinguish the IP address from the port number.
Consequently, if possible, I recommand you to ignore this ambiguous formatting.
UPDATE
Actually, you can do what you want if you are sure to be able to distinguish the two parts, which is when you can count exatcly 8 occurences of the character :.
if strings.Count(url, ":") == 8 {
split := strings.Split(url, ":")
url = "[" + strings.Join(split[:8], ":") + "]:" + split[8]
}
But this is probably not the best idea to process this kind of url formatting anyway...
You can use the standard net package to help in the process [Playground][http://play.golang.org/p/wz0g7rgdU4]
I use the net.ParseIP and net.JoinHostPort
package main
import (
"fmt"
"net"
"strings"
)
func splitLastColumn(host string) (string, string, string) {
idx := strings.Index(host, "/")
col_idx := strings.LastIndex(host[:idx], ":")
return host[:col_idx], host[col_idx+1 : idx], host[idx:]
}
func main() {
ipstr := "aaa:abbb:cccc:dddd:0000:0000:00aa:bbbb:8080/static/silly.html"
host, port, path := splitLastColumn(ipstr)
ip := net.ParseIP(host)
if ip == nil {
fmt.Println("invalid addr ")
}
fmt.Println(ip, host, port, path)
fmt.Println(net.JoinHostPort(host, port))
}
I am supplied the following RSA private key in the format
<RSAKeyValue>
<Modulus>XXXXXXXX</Modulus>
<Exponent>XXXXXXXX</Exponent>
<P>XXXXXXXX</P>
<Q>XXXXXXXX</Q>
<DP>XXXXXXXX</DP>
<DQ>XXXXXXXX</DQ>
<InverseQ>XXXXXXXXXX/InverseQ>
<D>XXXXXXXX</D>
</RSAKeyValue>
The XXXX are in Base64 format.
I want to know how to combine it all the XXXXXX bits to a single Base64 string.
With this single Base64 string i do the following:
1. Feed it to a TMemorStream
2. use Indy's TIdDecoderMIME class to decode Base64 from the MemoryStream
3. The decoded MemoryStream is then feed into CryptDecrypt function from wcrypt2.pas (a delphi wrapper of Microsoft's Cryptographic API) from Jedi
I know the solution for public key in the same format
<RSAKeyValue>
<Modulus>xqiYKv0umaLdmrKPyBfYmAfzZYVsvsOJyS4c1lBPjqpn7zh+XyxPXK7MxJkAlenQJM33M+ZYfmlPLya7JWXXTPviylEEtlmul9GshpX2caxWu2YO9vNIHRZYYau4ccbkm95iMyJi8KN2ANtqDwiJv55vcXZDqjPSDE4ap49xmog==</Modulus>
<Exponent>AAQC</Exponent>
</RSAKeyValue>
The solution is to add "BgIAAACkAABSU0ExAAQAAAE" + Exponent + Modulus
The result is:
BgIAAACkAABSU0ExAAQAAAEAAQCxqiYKv0umaLdmrKPyBfYmAfzZYVsvsOJyS4c1lBPjqpn7zh+XyxPXK7MxJkAlenQJM33M+ZYfmlPLya7JWXXTPviylEEtlmul9GshpX2caxWu2YO9vNIHRZYYau4ccbkm95iMyJi8KN2ANtqDwiJv55vcXZDqjPSDE4ap49xmog==
With the private key how do we combine it? I know it starts off like this:
"BwIAAACkAABSU0ExAAQAAAE" + Exponent + Modulus + ???????
The XXXX in the RSAKeyValue XML are in base64, just that i do not want to expose the details there. I want to know how do i combine all the XXXX base64 codes into a single base64 private key.
I suspect that this means that you are performing the base64 encoding line by line. It's much simpler to perform the encoding on the entire file.
For example you might do this as follows:
Load the file into a TStringList.
Extract a single string representing the file using the Text property of the string list.
Base64 encode that string.
Send it over the wire.
At the receiving end, decode the string.
Assign the string to the Text property of a string list.