How to parse string into url.Values in golang? - parsing

Let's suppose i have the following string
honeypot=&name=Zelalem+Mekonen&email=zola%40programmer.net&message=Hello+And+this+is+a+test+message...
and i want to convert it into url.Values struct and i have the following
data := url.Values{}
parameters := strings.Split(request.Body, "&")
for _, parameter := range parameters {
parts := strings.Split(parameter, "=")
data.Add(parts[0], parts[1])
}
which does convert it into url.Values but the problem is that it doesn't convert url encoded values like + into space, so first is there a better way to parse this? then if not how do i convert url encoded string to normal string first?
Thank's For Your Help...o

You could use url.ParseQuery to convert the raw query to url.Values with unescaping
package main
import (
"fmt"
"net/url"
)
func main() {
t := "honeypot=&name=Zelalem+Mekonen&email=zola%40programmer.net&message=Hello+And+this+is+a+test+message..."
v, err := url.ParseQuery(t)
if err != nil {
panic(err)
}
fmt.Println(v)
}
Result:
map[honeypot:[] name:[Zelalem Mekonen] email:[zola#programmer.net] message:[Hello And this is a test message...]]

You could first decode the URL with net/url/QueryUnescape.
It does converts '+' into '' (space).
Then you can start splitting the decoded string, or use net/url/#ParseRequestURI and get the URL.Query.

You can also use URL.Query:
package main
import (
"fmt"
"net/url"
)
func main() {
get := url.URL{
RawQuery: "honeypot=&name=Zelalem+Mekonen&email=zola%40programmer.net",
}
query := get.Query()
// map[email:[zola#programmer.net] honeypot:[] name:[Zelalem Mekonen]]
fmt.Println(query)
}
https://golang.org/pkg/net/url#URL.Query

Related

How do I convert an json string into list in dart?

My string is in the from of "['Curry Me Up','Curry Culture']"
and I want to convert it in ['Curry Me Up','Curry Culture']
I have tried doing json.decode("['Curry Me Up','Curry Culture']")
but its giving me error FormatException: SyntaxError: Unexpected token ' in JSON at position 1
The string you are trying to parse does not contain valid JSON since you must encapsulate strings with " in JSON and not '. So if you instead do this it will work:
import 'dart:convert';
void main() {
final list = json.decode('["Curry Me Up","Curry Culture"]') as List;
print(list); // [Curry Me Up, Curry Culture]
}

Dart and Flutter: How can I substitute invisible control characters in a String with e.g. \n?

I download an XML file in my flutter app and convert it into Dart Objects that I later want to serialize with JSON. Since JSON does not accept any invisible carriage return characters, I am looking for a way to substitute those with \n.
From your question why don't you use dart String replaceAll method.
With a simple regExp you could replace all the return carriages.
You can pass a String to the jsonEncode() function from the dart:convert library, and it will automatically replace newlines with a \, n sequence (and will quote the string).
You can pass string to json by using jsonEncode() or jsonDecode(), and you might declare variable with var
import 'dart:convert';
void main() {
var string = {
'a': 'Indication\n',
'b': 'Indication\t',
'c': 1
};
var enCode = json.encode(string);
print(enCode); // {"a":Indication\n,"b":Indication\t,"c":1}
print(jsonDecode(enCode)); // {"a":Indication
// ,"b":Indication ,"c":3}
}

How to parse an input string, like a calculator, to grab the operator and operands?

I am brand new to the Go programming language and I am trying to build a very simple calculator. The issues I am running into is if someone enters in 4+2 or 5/10 or 100-25 to the command line how do I grab the operator and operands out of this string in order to perform the equation?
This is what I have so far, but this just grabs the entire string
package main
import (
"bufio"
"fmt"
"os"
"stack" //stack code works perfectly
)
func main() {
// Read a line from stdin.
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
// fmt.Println(line)
//Separate the string based on operator and operands
// Push all of the characters onto the stack.
s := stack.New()
for i := 0; i < len(line); i++ {
if err := s.Push(line[i]); err != nil {
panic("Push failed")
}
}
Some pointers for you.
To get operands from your line try strings.FieldsFunc().
Convert your operands to float64 try strconv.ParseFloat() or fmt.Sscanf().
Figure out what operation +, -, /, * you have. Perhaps with strings.ContainsRune().
Perform operation on operands and present results.
Have fun!

How to pass multiple data objects to HTML templates in Golang

I am returing all rows of a table as json to the variable pdata and unmarshaling it into an interface object.
I have an instance of the user struct which I would like to pass along with the unmarshalled json data to the render function and access it using field arguments {{.fieldname}} in the html template.
if uuid != "" {
pdata, err := getProduct()
if err != nil {
fmt.Println(err)
}
type Prdata struct {
Puid string `json:"puid"`
Pname string `json:"pname"`
Quantity string `json:"quantity"`
Price string `json:"price"`
Image string `json:"image"`
}
// Obj:= make(map[Prdata]string)
var Pr Prdata
err = json.Unmarshal(pdata , &Pr)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(pdata))
fmt.Println(Pr)
fmt.Println(u)
render(w, "internal", Pr)
}
fmt.Println(string(pdata)) gives this output
[{"image":"1Appleiphone7.jpeg","pname":"iphone7","price":"70000","puid":"d6742e4e-2ad6-43c5-97f4-e8a7b00684e2","quantity":"100"}]
I have only been successful to unmarshal the data into an interface{} object. Trying to make maps with keys of the type interface{} and values of type string but it throws the error:
"json: cannot unmarshal array into Go value of type map[interface {}]string"
The render function takes an argument of the type interface{}
func render(w http.ResponseWriter, name string, data interface{})
fmt.Println(Pr) gives this output:
[map[quantity:100 image:1Appleiphone7.jpeg pname:iphone7 price:70000 puid:d6742e4e-2ad6-43c5-97f4-e8a7b00684e2]]
u is an instance of struct User
var u = &User{}
type User struct {
Uuid string
Username string
Password string
Fname string
Email string
}
I can see the output on the html page using the pipeline {{.}}. However I am not able to access any data using the fieldname.
There must be a way of doing this. But I am not sure how?
When I pass of a json of the type below, I am able to pass it to the struct type and reference it by the key values using pipelines in my template.
str := `{
"image": "1Appleiphone7.jpeg",
"pname": "iphone7",
"price": "70000",
"puid": "d6742e4e-2ad6-43c5-97f4-e8a7b00684e2",
"quantity": "100"
}`
unmarshal function
err = json.Unmarshal([]byte(str), &Pr)
The difference in the json data of the DB record pdata and the one above str is in the use of backticks "`". It seems that though the json data shows key value pairs, it is actually a json array and not a json object. Is there a way to get around this?
You don't need a map[interface{}]string to unmarshal the json obj. Your json is equivalent to slice of maps:
[
{
"image":"1Appleiphone7.jpeg",
"pname":"iphone7",
"price":"70000",
"puid":"d6742e4e-2ad6-43c5-97f4-e8a7b00684e2",
"quantity":"100"
}
]
The object to unmarshal should be a slice of maps with string keys and values:
var Pr []map[string]string
Playground
BTW, I believe misunderstanding is hidden there:
The render function takes an argument of the type interface{}
I means not that you must pass a variable of interface{} type there but it means you CAN pass a variable of any type to render function.
I am posting a working example of unmarshalling json as bytes into a struct type which then can be referenced using the {{.}} in the template.
package main
import (
"encoding/json"
"fmt"
)
type Usrdata struct {
Uuid string
Fname string
}
type Prdata struct {
Puid string `json:"puid"`
Pname string `json:"pname"`
Quantity string `json:"quantity"`
Price string `json:"price"`
Image string `json:"image"`
}
type Data struct {
U Usrdata
P []Prdata
}
func main() {
Ur := Usrdata{Uuid: "xyz", Fname: "Somename"}
Pr := make([]Prdata, 0)
var Dt Data
Dt.U = Ur
pdata := `[{"image":"1Appleiphone7.jpeg","pname":"iphone7","price":"70000","puid":"d6742e4e-2ad6-43c5-97f4-e8a7b00684e2","quantity":"100"}]`
err := json.Unmarshal([]byte(pdata), &Pr)
if err != nil {
fmt.Println(err)
}
Dt.P = Pr
fmt.Println(Pr[0].Pname)
fmt.Println(Pr)
fmt.Println(Dt)
}

Multiple-types decoder in golang

I have an XML document. Some fields have custom format. Example:
<document>
<title>hello world</title>
<lines>
line 1
line 2
line 3
</lines>
</document>
I want to import it into structure like:
type Document struct {
Title string `xml:"title"`
Lines []string `xml:"lines"`
}
Is there some way how to implement custom decoder, which will split lines string into array of lines (["line 1", "line 2", "line 3"])?
Its possible to make Lines field a string type and make split after xml import, but it doesn't seems to be very elegant solution. Is there any way i can define custom decoder for line spliting and combine it with xml decoder?
You can achieve this by defining a new type that conforms to the xml.Unmarshaler interface. So rather than making Lines a []string, declare a new type with an appropriate UnmarshalXML method. For instance:
type Lines []string
func (l *Lines) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var content string
if err := d.DecodeElement(&content, &start); err != nil {
return err
}
*l = strings.Split(content, "\n")
return nil
}
You can see a full example here: http://play.golang.org/p/3SBu3bOGjR
If you want to support encoding this type too, you can implement the MarshalXML method in a similar fashion (construct the string content you want and pass that to the encoder).
Here is a spelled out example of what CSE is suggesting:
type Document struct {
Title string `xml:"title"`
LineData string `xml:"lines"`
}
func (d *Document)Lines() []string {
return strings.Split(d.LineData, '\n')
}
This is similar to what net/http Request does: read the data into a struct, and then provide accessors to interpret that struct.
If you really don't want to do that, then another approach that I have used is to create two structs. Read the raw data into the first and then use that to construct the second.
If you are planning on shipping this out as JSON or some other wire format, the second struct could just be a map.
func (d *Document) Map() map[string]interface{} {
m := make(map[string]interface{})
m["lines"] = strings.Split(d.LineData, '\n')
m["title"] = d.Title
return m
}

Resources