GO Lang降价应用

I have a very simple markdown app in go which works great but I am really struggling to sort the order of the index posts on the page and would like a neat way in the file to do this. Any help appreciated.

html is

<section>
{{range .}}
<a href="/{{.File}}"><h2 class="h2_home">{{.Title}} ({{.Date}})</h2></a>
<p>{{.Summary}}</p>
{{end}}
 </section>

and the go stuff for the index page is as follows

func getPosts() []Post {
a := []Post{}
files, _ := filepath.Glob("posts/*")
for _, f := range files {
    file := strings.Replace(f, "posts/", "", -1)
    file = strings.Replace(file, ".md", "", -1)
    fileread, _ := ioutil.ReadFile(f)
    lines := strings.Split(string(fileread), "
")
    title := string(lines[0])
    date := string(lines[1])
    summary := string(lines[2])
    body := strings.Join(lines[3:len(lines)], "
")
    htmlBody := template.HTML(blackfriday.MarkdownCommon([]byte(body)))

    a = append(a, Post{title, date, summary, htmlBody, file, nil})
}
return a
}

Ive not looked at it for a while as it just works but I really want to put something into the file to support ordering. The .md file is formatted

Hello Go lang markdown blog generator!
12th Jan 2015
This is a basic start to my own hosted go lang  markdown static blog/ web generator.
### Here I am...

This entry is a no whistles Hello ... etc

See sort.Slice in the sort package. Here is an example of usage.

For your particular problem, you have a slice a []Post, so just call sort.Slice on it like this:

sort.Slice(a, func(i, j int) bool { return a[i].title < a[j].title })

This is just sorting all members of the slice a based on their title (assuming you can access this private field of a Post in this package, if not you'd need to add a function).

If you do that your slice a of posts will be sorted by title (or any other criteria you wish, perhaps you could give the user a choice of title or date?). You don't need to adjust your markdown files.

If you want to sort on dates obviously your Post should parse the dates with the time package first so that you have real dates, not just a string.

So something like this (assuming time.Time on the Post):

// parse dates
date,err := time.Parse("2nd Jan 2006",string(lines[1]))
if err != nil {
 // deal with it
}   

// later, sort the slice 
sort.Slice(a, func(i, j int) bool { return a[i].date.Before(a[j].date)})