This question already has an answer here:
Unable to decode gob data
(1 answer)
Closed 5 years ago.
Here is my playground where I am trying to serialize a list of structures and read back from the file.
https://play.golang.org/p/8x0uciOd1Sq
I was expecting the object to be decoded successfully. What am I doing wrong?
Export the field names by capitalizing the first letter.
type REntry struct {
Key string
Value []string
}
The gob package and other similar packages ignore unexported fields.
Related
This question already has an answer here:
Convert byte slice to int slice
(1 answer)
Closed 4 months ago.
The community reviewed whether to reopen this question 4 months ago and left it closed:
Original close reason(s) were not resolved
I have written a LZW decoder algorithm in Go for a programming task required as part of a job application. A LZW code is a sequence of integers which can be decoded as a string. I have basically written a function that looks like this:
func LZWdecoder(code []int) string {
// * perform decoding *
return decodedString
}
They have provided me with a .z file which is encoded using LZW encoding so I can test my algorithm on it (it decodes to human readable text).
However, I don't know how to "load" that file into an integer slice that I can run through my function. Any help would be greatly appreciated.
Use import os then os.ReadFile("filename.z") should return a slice of bytes, which you can then convert to a slice of int using the method described here: Convert byte slice to int slice
This question already has answers here:
Get output of template to a variable instead to STDOUT [duplicate]
(1 answer)
Assign result of executing text/template template into a variable [duplicate]
(1 answer)
Closed 5 months ago.
I'm using Go HTML templates and when you run this function it sends the data to the client, but I would like to store that data in a variable and send it to the client later. How can this be achieved?
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error
This is for use in an AJAX response. I know on the client side I could simply parse the xhr.responseText, but I need to send some other variables with it.
Use a buffer:
buf:=bytes.Buffer{}
t.ExecuteTemplate(&buf,"name",data)
Then you can use buf.Bytes(), or buf.String().
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Needs details or clarity Add details and clarify the problem by editing this post.
Improve this question
How do I convert a string to a structure?
The line looks like this: Name[data1] Name2[data1 data2 data3] Name3[data1 data2] ...
The data can be of type Int, String, or Float. In general, this is not important, you can write everything as string.
Data in brackets is separated by a space
What I got using regexp:
func Parse() {
str := "Version[2f0] Terminal[10002] Machine[10.1.1.1] DH[0.137%] Temp[45] Fan[0] Vo[4074 4042 4058 4098] CRC[0 0 0 0]"
j := make(map[string][]string)
re, err := regexp.Compile(`(?P<Name>[^ \[]*)\[(?P<Value>[^\]]*)`)
if err != nil {
log.Fatal(err)
}
res := re.FindAllSubmatch([]byte(str), -1)
for _, match := range res {
j[string(match[1])] = strings.Split(string(match[2]), " ")
}
log.Printf("%+v", j)
}
Could there be a more elegant way using json.Unmarshal?
You need to define a specific format for the serializing the data. A key part of that will be how to encode specific special characters, such as the [ and ]. You generally do not want to do this.
If you want to use any string as a temporary textual representation of your data and the format doesn't matter, you can just use JSON and use json.Marshal() and json.Unmarshal().
I'm not sure what you are trying to achieve (what's this struct data? what generated it? why are you trying to decode it into a struct?) but it seems that going through the fundamentals might be helpful:
https://en.wikipedia.org/wiki/Serialization will tell you what that is
https://betterprogramming.pub/serialization-and-deserialization-ba12fc3fbe23 is a very short guide that will give you the very basics (in JavaScript)
I already mentioned json.Marshal and json.Unmarshal - reading their docs in the standard library will be helpful as well.
I'm sure you can google the more in-depth articles when you identify what you need to know for your specific purposes.
If you're free to use any tool you like, a regular expression might make this fairly easy.
(?P<Name>\[^\[\]*)\[(?P<Values>\[^\]\]*)\]
That matches each of the named value sets.
and then you could split the Values group at the spaces with string.Split
To create a dynamic struct you'd need to use reflection. Avoid reflection, though, as you learn Go. A struct in Go is unlike an object in say Javascript or Python, where fields are dynamic at runtime. Go structs are meant to have static fields.
For this purpose, a map[string][]string would be a more appropriate type. The key would be the Name fields, and the value would be the data fields.
This question already has answers here:
How do I convert a String object into a Hash object?
(16 answers)
Closed 4 years ago.
I stored my nested hash in a file, and while retrieving it, I want to it back in a hash form instead of string. When I read a file it will give me a string and then how can I parse it back to a hash.
This is the string hash in the file:
{"SONGS"=>{1=>["2018-05-29 18:19:14 +0530", "HAPPY", "Meri Sapnon Ki Rani"]}}
Already in SO.
WARNING SECURITY RISK!
For your string you need to pass to eval, but this is a SECURITY RISK
string = '{"SONGS"=>{1=>["2018-05-29 18:19:14 +0530", "HAPPY", "Meri Sapnon Ki Rani"]}}'
p eval(string).class
If you need to store data structures in files, I suggest you to take a look at YAML module. Look at this post, for example.
As suggested in comments:
Consider also security concerns, look this post.
Consider to change a little bit the string syntax to use a JSON structure. See below.
Use of JSON:
require 'json'
json_string = '{"songs":{"1":{"date": "2018-05-29 18:19:14 +0530", "title":"HAPPY", "name":"Meri Sapnon Ki Rani"}}}'
p JSON::parse(json_string).class
For testing, I often see go code read byte slices, which are parsed into structs using yaml, for example here:
https://github.com/kubernetes/kubernetes/blob/master/pkg/util/strategicpatch/patch_test.go#L74m
I just got bitten by not exporting my field names, resulting in an empty list which I iterated over in my test cases, thus assuming that all tests were passing (in hindsight, that should have been a red flag :)). There are other errors which are silently ignored by yaml unmarshaling, such as a key being misspelled and not matching a struct field exactly.
Is there a way to ensure that all the data in the byte slice was actually parsed into the struct returned by yaml.Unmarshal? If not, how do others handle this situation?
go-yaml/yaml
For anyone searching for a solution to this problem, the yaml.v2 library has an UnmarshalStrict method that returns an error if there are keys in the yaml document that have no corresponding fields in the go struct.
import yaml "gopkg.in/yaml.v2"
err := yaml.UnmarshalStrict(data, destinationStruct)
BurntSushi/toml
It's not part of the question, but I'd just like to document how to achieve something similar in toml:
You can find if there were any keys in the toml file that could not be decoded by using the metadata returned by the toml.decode function.
import "github.com/BurntSushi/toml"
metadata, err := toml.Decode(data, destinationStruct)
undecodedKeys := metadata.Undecoded()
Note that metadata.Undecoded() also returns keys that have not been decoded because of a Primitive value. You can read more about it here.
Json
The default go json library does not support this currently, but there is a proposal ready to be merged. It seems that it will be a part of go 1.10.