Extract case-insensitive query parameter from URL - url

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()

Related

Why jsonDecode in Dart has no type and no documentation?

As you can see in https://api.dart.dev/stable/2.7.1/dart-convert/jsonDecode.html, it has no type and no documentation. I don't know which methods I can invoke on the result neither I don't know which type to but on a parameter that should be a json object.
Why is Dart like this? And what are the advantages?
It does have documentation, and you are linking to it.
If you want it to have more documentation, then that is reasonable. The returned value is admittedly not documented very well.
The function jsonDecode is a shorthand for json.decode, which again forwards to JsonDecoder.convert.
It returns a "JSON value" object which depends on the JSON source that it decodes.
A "JSON value" can be any of:
* null
* an int
* a double
* a String
* a bool (true or false)
* a List<dynamic> containing zero or more JSON values.
* a Map<String, dynamic> mapping keys to JSON values.
Those are also the same values that are accepted by the JsonEncoder which converts object structures to JSON strings.
Since these types have no common superclass other than Object, the function cannot have a return type which is more specific than dynamic or Object.
The chosen return type is dynamic because the dynamic type allows the receiver to optimistically call any member on the value. They might know that the value will always be a map, so they can just do jsonParse(jsonSource)["key"] to look up a value. Obviously, if the source was not a JSON object, that call will fail.
If you don't know which type the result is, you have to check:
var data = jsonDecode(jsonSource);
if (data is Map<String, dynamic>) {
something something data["key"] something
} else if (data is List<dynamic>) {
something something list[2] something
} else ... etc ...
A valid JSON file is actually a valid Dart expression too. The value returned by jsonDecode is similar to the value you would get if you wrote the JSON code directly as Dart code (in Dart 1 it was exactly the same, in Dart 2, the Dart code might infer a more precise type for maps and lists).

Get string value out of a KeySym value

Is there a way to get the string value out of a KeySym value?
For example, out of keyPrintable("a").
If you know the KeySym value is a keyPrintable, you can just get it using the key property. For instance
KeySym kv = ... // something that yields a KeySym
str s = kv.key;
If you don't know it's a keyPrintable you can either check to see if it was built using that constructor, or use pattern matching. So, either
if (kv is keyPrintable) {
// code that uses kv.key to get back the value
}
or
if (keyPrintable(str s) := kv) {
// code that can now use s, which is the key
}
You can also ask if kv has that field, and then use it:
if (kv has key) {
// code that uses kv.key
}
Once you introduce a field name in a constructor, and it has a specific type, you know that same field name has that same type in any additional constructors for the same datatype. So, once we know field key is type str, field key has to be str in any value of type KeySym. That is why it's fine to see if kv has field key and then treat it as a str, nobody could come along later and add a new constructor for KeySym where key has a different type.

Get Query string as it is passed

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

NSUTF8StringEncoding result encoded string with 'Optional' string

I'm using NSUTF8StringEncoding to encode some text inputs, the inputs get encoded and the resulting string contain a 'Optional'. An example worked out is available here.
What does that encoded string with 'optional' really mean?
Does that have any significant role?
The thing you have to understand is that an optional is a different data type than the required object it contains. An optional "wraps" or contains some other object. The optional can either be empty, represented by nil, or it can contain another object.
Internally an optional is an enum that has 2 values, Some and None. The Some case has an associated value. Optionals are generics. The associated value stored in the Some case (non empty) can be any type, and that determines the type of the optional.
If you print an optional, you see the container AND the value stored inside, or you see nil (since a nil optional does not contain anything.)
let aString:String? = "Foo"
println("aString = \(aString)")
Displays something like
optional("Foo")
That's because aString is not a String optional, it is an optional that contains a string.
optional variables are variables that can may or may not have a value.
Looking at your example here
we can see data has type NSData?
unlike objective-c where we can happily send messages to nil values we need to make sure the 'data' definitely has a value before we can use it
if you are sure it will have a value you can unwrap it explicitly like this
let myString = "encode me"
let data : NSData? = myString.dataUsingEncoding(NSUTF8StringEncoding)
data!.someNSDataFunction()
This will crash if data is nil.To safely unwrap it you can can do this
if let actualData = data
{
actualData.someNSDataFunction()
}
else
{
println("data has not been set")
}

how to to find a string in groovy list

question from a groovy newbie:
sql is initiated as follows
final Binding binding = new Binding();
binding.setProperty("sql", sql);
final groovy.sql.Sql sql = Sql.newInstance(dbConfig.getUrl(), dbConfig.getUserName(), dbConfig.getPasswd(),"oracle.jdbc.OracleDriver");
I am running a query in groovy like this
def listOfRows = sql.rows (select column1 from table1);
listOfRows when printed shows contents like [[column1_name:value1], [column1_name:value2], [column1_name:value3]]
I want to check if value2 (a String) exists in the returned list of values from the above query.
I have tried doing listOfRows.contains('value2') and listOfRows.find('value2'),
it complains that the method does not exist for lists..
what's the best way of doing this ?
EDITED: I have corrected the list of printed values. What's being returned is List<GroovyResultSet>
and I have also added the definition of sql.
I would suggest you to take a look at groovy documentation, and particularly to collections documentation (both tutorial and JDK/GDK).
in that case, the most specifically adapted solution would be to use Collection#find() ... with something like
listOfRows.find { it.contains(':value2') }
Which can be translated into human-readable
find the first element in this collection which string contains ":value2".
You probably want
listOfRows.column1.contains( 'value2' )
You are probably invoking this method which takes a GString (note that GString != String) as an argument. According to this question, a string in single quotes is a standard java string, and a string in double quotes is a templatable string.
'hello' //java.lang.String
"hello" //groovy.lang.GString
Try this:
listOfRows.contains("value2")
what i ended up doing is following :
iterate the listOfRows, get all the values for column1 from each GroovyResultSet into a listOfValues ,then check for my values in that list.
def listOfValues=[];
listOfRows.collect(listOfValues){it.getAt('column1')};
if(listOfValues.size()==3){
println('success');
}

Resources