I’ve got a real-life work project that I use to learn the language, and within the last 2 days I’ve learned a ton of new stuff. I’m, however, struggling with a specific subject; unmarshaling a custom time attribute from XML files. So far, I’ve implemented the following:
This all makes sense, but I don’t want that object, I just want the timestamp as the value of the first timestamp. I’ve been reading a lot, but I can’t find the documentation I need to achieve this.
I’m a beginner in Go too, so I may not be as helpful as I’d like to be, but I think I have an idea that could help.
Instead of making your customTime a struct, if you just made it a time.Time, maybe that would remove the extra wrapping object when you’re storing it in MongoDB.
I’m thinking something like this
type Program struct {
Timestamp customTime `xml:"timestamp,attr"`
}
type customTime time.Time
func (c *customTime) UnmarshalXMLAttr(attr xml.Attr) error {
date := attr.Value
fmt.Println("DATE", date)
location, _ := time.LoadLocation("MST")
parse, err := time.ParseInLocation("2006-01-02", date, location)
if err != nil {
panic(err)
}
fmt.Println("PARSE", parse)
*c = customTime(parse)
return nil
}
func main() {
testXML := []byte(`<Program timestamp="2021-05-15"></Program>`)
var v Program
if err := xml.Unmarshal(testXML, &v); err != nil {
panic(err)
}
fmt.Println(v.Timestamp)
}