Cannot get HTTP header - http

I don't understand why func (h Header) Get(key string) string in package http in file header.go doens't work as expected.
I want to get the header "SOAPAction" regardless of its casing, but I only get an empty string "". The direct access works as expected.
soapAction1 := r.Header.Get("SOAPAction")
soapAction2 := r.Header["SOAPAction"]
fmt.Println("soapAction1: ", soapAction1, " , soapAction2:", soapAction2)
// Got: soapAction: , soapAction2: [MySoapHeader]
// Expected: soapAction: MySoapHeader , soapAction2: [MySoapHeader]
// Get gets the first value associated with the given key. If
// there are no values associated with the key, Get returns "".
// It is case insensitive; textproto.CanonicalMIMEHeaderKey is
// used to canonicalize the provided key. To use non-canonical keys,
// access the map directly.
func (h Header) Get(key string) string {
return textproto.MIMEHeader(h).Get(key)
}

From the documentation (emphasis added):
Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. To use non-canonical keys, access the map directly.
Your header, SOAPAction, is not cannonical, so you have two choices:
Use the canonical version (Soapaction)
Use direct access, as the documentation explains, and as you have done.

http.Header.Get method relies on a string transformation to fetch the value for a given string.
The transformation is implemented by the textproto package
https://golang.org/pkg/net/textproto/#CanonicalMIMEHeaderKey
CanonicalMIMEHeaderKey returns the canonical format of the MIME header
key s. The canonicalization converts the first letter and any letter
following a hyphen to upper case; the rest are converted to lowercase.
You can try it yourself:
package main
import (
"fmt"
"net/textproto"
)
func main() {
fmt.Println(textproto.CanonicalMIMEHeaderKey("SOAPAction"))
}
It prints: Soapaction

Related

How To Copy data from String access to Ada.String

I have the following fragment of code
with GNAT.Command_Line; use GNAT.Command_Line;
with GNAT.Strings; use GNAT.Strings;
....
Define_Switch
(Config => Config, Output => File_Name'Access,
Long_Switch => "--file=", Switch => "-f=",
Help => "File with Composition");
....
Getopt
After parsing command line via Getopt I have access object that points to actual file name
I would like to copy this name to Ada.String.Fixed string that definded as
File_Name : String(1 .. 256);
I can print to console data from File_Name'Access as
Put_Line(File_Name.all);
I think I should provide something like copy operation then free access object.
How can I do it?
Thanks.
Alex
I guess File_Name in the code snippet defined as 'aliased GNAT.Strings.String_Access'. This is a "fat pointer" to the string object. "Fat" means it is not an address only, it is range of indices of the string. C-style Nil terminator is not used in Ada, and Nil is valid character.
You can copy data inside this string object into the another standard String object playing with indexes computations, but usually you must not do this: there is no Nil terminator, you will need to pass length of the actual data; destination string object may be smaller than necessary, and data will be truncated or exception raised; etc.
There are two right ways to do this. First one is to declare unconstrained string object and assign value to it.
declare
Fixed_File_Name : String := File_Name.all;
begin
Free (File_Name);
or use variable length string (bounded or unbounded):
declare
Unbounded_File_Name : Ada.Strings.Unbounded.Unbounded_String;
begin
Unbounded_File_Name :=
Ada.Strings.Unbounded.To_Unbounded_String (File_Name.all);
Free (File_Name.all);
Use of fixed string has important restriction: string object must be initialized exactly at the point of declaration of the object, and available only inside corresponding block/subprogram. Use of variable length string allows to declare string object outside of the scope of particular block/subprogram.

Swiftui: how do you assign the value in a "String?" object to a "String" object?

Swiftui dictionaries have the feature that the value returned by using key access is always of type "optional". For example, a dictionary that has type String keys and type String values is tricky to access because each returned value is of type optional.
An obvious need is to assign x=myDictionary[key] where you are trying to get the String of the dictionary "value" into the String variable x.
Well this is tricky because the String value is always returned as an Optional String, usually identified as type String?.
So how is it possible to convert the String?-type value returned by the dictionary access into a plain String-type that can be assigned to a plain String-type variable?
I guess the problem is that there is no way to know for sure that there exists a dictionary value for the key. The key used to access the dictionary could be anything so somehow you have to deal with that.
As described in #jnpdx answer to this SO question (How do you assign a String?-type object to a String-type variable?), there are at least three ways to convert a String? to a String:
import SwiftUI
var x: Double? = 6.0
var a = 2.0
if x != nil {
a = x!
}
if let b = x {
a = x!
}
a = x ?? 0.0
Two key concepts:
Check the optional to see if it is nil
if the optional is not equal to nil, then go ahead
In the first method above, "if x != nil" explicitly checks to make sure x is not nil be fore the closure is executed.
In the second method above, "if let a = b" will execute the closure as long as b is not equal to nil.
In the third method above, the "nil-coalescing" operator ?? is employed. If x=nil, then the default value after ?? is assigned to a.
The above code will run in a playground.
Besides the three methods above, there is at least one other method using "guard let" but I am uncertain of the syntax.
I believe that the three above methods also apply to variables other than String? and String.

How do I handle optional query parameters for a Go using Mux properly?

I'm making an API server using GoLang and I am using Mux as the HTTP router. I have one endpoint in my app, /tasks. When I hit that endpoint, I get back an array of results, which is as expected. Now, I want to build upon that and add an optional query parameter into the URL to only return N results, like so: /tasks?num=5 which would only return 5 results. I have accomplished this using the handler below:
vars := r.URL.Query()
t := task{}
if numOfTasksParam, ok := vars["num"]; ok {
fmt.Printf("%+v", numOfTasksParam[0])
numOfTasks, err := strconv.Atoi(vars.Get("num"))
//return only n number of results
} else {
//return the entire result set
}
I devised this solution because I discovered that URL.Query() returns a map of the query parameters and therefore, I can just check to see if that map contained the key of "num". If so, the client wants N number of results. If not, the client must want the whole result set.
The main issue I have with this approach is that when I go to check if the keys exists, I make a temporary variable called numOfTasksParam which holds the query parameter value, but it holds the value as a string and I need a int. Therefore, I must use the numOfTasksParam somehow and then create another variable to convert that to an integer value.
Is there more succinct or convenient way of checking if a query parameter exists in the request URL?
This is probably the most succinct, and works because Get returns an empty string if the parameter isn't set, which Atoi will fail to parse:
vars := r.URL.Query()
t := task{}
if numOfTasks, err := strconv.Atoi(vars.Get("num")); err == nil {
//return only numOfTasks number of results
} else {
//return the entire result set
}
The price you pay for having less code is that if a user passes an invalid value like ?num=taco, it will be treated as if they passed nothing, rather than telling the user they passed something unusable. This may or may not be what you want. It is also slightly less efficient, because it will run Atoi even if the value is known to be empty.

If the type of a parameter is interface{} how do you know whether you pass by pointer or by value?

Given any function that takes a parameter of type interface{} how would I know whether or not to pass that parameter with or without & without navigating the source code of the function.
For example if I had a function with this type signature given to me:
func foo(x interface{}, y int) int
Would there be any way to figure out if x was supposed to be passed by value or by pointer?
Here is the snippet from the source:
// DecodeElement works like Unmarshal except that it takes
// a pointer to the start XML element to decode into v.
// It is useful when a client reads some raw XML tokens itself
// but also wants to defer to Unmarshal for some elements.
func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error {
val := reflect.ValueOf(v)
if val.Kind() != reflect.Ptr {
return errors.New("non-pointer passed to Unmarshal")
}
return d.unmarshal(val.Elem(), start)
}
It is checking val.Kind() != reflect.Ptr Which means you have to pass the pointer i.e &v.
Its entirely depend on the person who wrote the method or function, so interface{} could be either *ptr or anything but u ve to check that inside your function using reflect.ValueOf(v).Kind() whether the value is a pointer or not and proceeds accordingly.
And little bit about empty interface:
The interface type that specifies zero methods is known as the empty interface:
interface{}
An empty interface may hold values of any type. (Every type implements at least zero methods.)
Empty interfaces are used by code that handles values of unknown type. For example, fmt.Print takes any number of arguments of type interface{}.
Another useful discussion: docs
DecodeElement() and friends have a formal v interface{} whose type is documented in the Unmarshal() function documentation:
Unmarshal parses the XML-encoded data and stores the result in the
value pointed to by v, which must be an arbitrary struct, slice, or
string.
So to literally answer your question, no, you cannot know without reading the source - if the value you want to pass is a struct proper, you need to indirect. If it is already a pointer to that struct, you do not.
For example:
type Result struct {
XMLName xml.Name `xml:"Person"`
Name string `xml:"FullName"`
Phone string
Email []Email
Groups []string `xml:"Group>Value"`
Address
}
var (
a Result
b *Result
c string
)
xmlDecoder.DecodeElement(&a, startElement)
xmlDecoder.DecodeElement(&c, startElement)
but
xmlDecoder.DecodeElement(b, startElement)

Convert Value type to Map in Golang?

I'm getting this return value from a function call in the "reflect" package:
< map[string]string Value >.
Wondering if I can access the actual map inside the return value and if so, how?
EDIT:
So this is where I'm making the call which returns the Value object.
It returns [< map[string]string Value >] to which I grab the first object in that array. However, I'm not sure how to convert [< map[string]string Value >] into a regular map.
view_args := reflect.ValueOf(&controller_ref).MethodByName(action_name).Call(in)
Most reflect Value objects can be converted back to a interface{} value using the .Interface() method.
After obtaining this value, you can assert it back to the map you want. Example (play):
m := map[string]int{"foo": 1, "bar": 3}
v := reflect.ValueOf(m)
i := v.Interface()
a := i.(map[string]int)
println(a["foo"]) // 1
In the example above, m is your original map and v is the reflected value. The interface value i, acquired by the Interface method is asserted to be of type map[string]int and this value is used as such in the last line.
To turn the value in a reflect.Value into an interface{}, you use iface := v.Interface(). Then, to access that, you use a type assertion or type switch.
If you know you're getting a map[string]string the assertion is simply m := iface.(map[string]string). If there's a handful of possibilities, the type switch to handle them all looks like:
switch item := iface.(type) {
case map[string]string:
fmt.Println("it's a map, and key \"key\" is", item["key"])
case string:
fmt.Println("it's a string:", item)
default:
// optional--code that runs if it's none of the above types
// could use reflect to access the object if that makes sense
// or could do an error return or panic if appropriate
fmt.Println("unknown type")
}
Of course, that only works if you can write out all the concrete types you're interested out in the code. If you don't know the possible types at compile time, you have to use methods like v.MapKeys() and v.MapIndex(key) to work more with the reflect.Value, and, in my experience, that involves a long time looking at the reflect docs and is often verbose and pretty tricky.

Resources