I want to send a reverse order of a list of books that are stored in a map and send this to a model instead of the map in its current order.
I need to display a list in reverse order of date entered which is pubDate so that the webpage (model) displays the most recently added books instead of the books added first.
I have tried many various sort methods listed but I do not know how I would send this to the model. For example, I tried import "sort"
var m map[int]string
var keys []int
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
I also tried sort.Slice(ad, func(i, j int) bool {
return ad[i].date.Before(ad[j].date)})
there are many others but I can not seem to get any working.
type Book struct {
ID int64 `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
pubDate time.Time `json:"pubDate"`
}
var bookModels = map[string]*Book{}
s := res.NewService("library")
// Add handlers for "library.book.$id" models
s.Handle(
"book.$id",
res.Access(res.AccessGranted),
res.GetModel(getBookHandler),
res.Set(setBookHandler),
)
// Add handlers for "library.books" collection
s.Handle(
"books",
res.Access(res.AccessGranted),
res.GetCollection(getBooksHandler),
res.New(newBookHandler),
res.Call("delete", deleteBookHandler),
)
func getBookHandler(r res.ModelRequest) {
book := bookModels[r.ResourceName()]
if book == nil {
r.NotFound()
return
}
r.Model(book)
}
Mainly I get errors that the map does not allow indexing, or the wrong type, or cant access the fields, etc... How can you use a map and send it to a model and ensure that you have the most recent items listed first on the web page?