I have a simple project in Golang which I use to learn this language. Main purpose of the "service" which I'm developing is to run a daemon to save URLs which are exposed as XML. This way I can "produce" my own read-later service. So far so good :). You can find the project here: https://github.com/rogierlommers/readinglist-golang
I'm using Gin-Gonic as the framework for serving html. I've already managed to read an xml file, unmarshal it but now I want to add some new data into this "thing". In other words: I think I need to convert it into a slice, but I don't know how to manage this.
F.e. the endpoint r.GET("/add/:url")
should use the function util.AddRecord to insert the new url into the slice. But how?
[edit] Basically my problem can be viewed in this go playground: http://play.golang.org/p/Vx0s02E12R
In a comment on your question you asked:
I first need to create a slice, right?
The answer is yes, but you already have a slice in your ReadingListRecords
struct:
type ReadingListRecords struct {
XMLName xml.Name `xml:"records"`
Records []Record `xml:"record"`
}
So, you can simply call append on that slice and pass in a new record struct:
records.Records = append(record.Records, Record{xml.Name{"", "record"}, 4, "url", "2015-03-09 00:00:00"})
You could also expand the API for your ReadingListRecords
structure to include a handy Append
function:
type RecordSet interface {
Append(record Record) error
}
func (records *ReadingListRecords) Append(record Record) error {
newRecords := append(records.Records, record)
if newRecords == nil {
return errors.New("Could not append record")
} else {
records.Records = newRecords
return nil
}
}
Adding an interface seems like a good idea since you would like to use this as a service in multiple applications.