Skip to content

Commit

Permalink
添加按照时间归档功能
Browse files Browse the repository at this point in the history
  • Loading branch information
z8 committed May 30, 2013
1 parent e9963b5 commit d76029e
Show file tree
Hide file tree
Showing 8 changed files with 333 additions and 17 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

Example Site: [zhanglin.org](https://zhanglin.org)

### 小工具
备份 post 数据为 markdown 文件

go run utility/sql2md.go

### License
[ZHANG lin](https://zhanglin.org) - A Developer
基于 MIT License 开源,使用代码只需说明来源,或者引用 [license.txt](/license.txt)即可。
65 changes: 53 additions & 12 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type Config struct {
DbName string
DbConfig string
}

type Category struct {
Id int
Name string
Expand Down Expand Up @@ -113,20 +114,36 @@ func (post Post) Render(s string) (r Post, err error) {
return r, err
}

func List(categoryName string, pageId int) *[]Post {
func List(year int, categoryName string, pageId int) *[]Post {
posts := []Post{}

// Connect database
db, err := sql.Open(conf.DbName, conf.DbConfig)
checkErr(err)
defer db.Close()

categorySql := ""
categorySQL := ""
if categoryName != "" {
categorySql += " WHERE category='" + categoryName + "'"
categorySQL = " AND category='" + categoryName + "' "
} else {
categorySQL = " "
}

dateSQL := ""
if year != 0 {
dateSQL = " AND TO_CHAR(TO_TIMESTAMP(time), 'YYYY')='" + strconv.Itoa(year) + "' "
} else {
dateSQL = " "
}

pageSQL := ""
if pageId != 0 {
pageSQL = " OFFSET " + strconv.Itoa((pageId-1)*10) + " LIMIT 10 "
} else {
pageSQL = " "
}

sql := "SELECT id, title, time FROM post" + categorySql + " ORDER BY time DESC OFFSET " + strconv.Itoa((pageId-1)*10) + " LIMIT 10"
sql := "SELECT id, title, time FROM post WHERE 1=1" + categorySQL + dateSQL + "ORDER BY time DESC" + pageSQL

//rows, err := db.Query("SELECT id, title, time FROM post ORDER BY time DESC OFFSET 0 LIMIT 10")
rows, err := db.Query(sql)
Expand Down Expand Up @@ -238,14 +255,14 @@ func tmpTimeFormat(unixTime int64) string {
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
var posts = List("", 1)
var posts = List(0, "", 1)

t, err := template.New("").Funcs(template.FuncMap{"tmpTimeFormat": tmpTimeFormat}).ParseFiles("views/list.html", "views/header.html", "views/footer.html")
checkErr(err)

var templateData struct {
CategoryName string
Posts *[]Post
PageName string
Posts *[]Post
}

templateData.Posts = posts
Expand All @@ -263,22 +280,44 @@ func CategoryHandler(w http.ResponseWriter, r *http.Request) {
p, _ = strconv.Atoi(pageId)
}

var posts = List(categoryName, p)
var posts = List(0, categoryName, p)

t, err := template.New("").Funcs(template.FuncMap{"tmpTimeFormat": tmpTimeFormat}).ParseFiles("views/list.html", "views/header.html", "views/footer.html")
checkErr(err)

var templateData struct {
CategoryName string
Posts *[]Post
PageName string
Posts *[]Post
}

templateData.CategoryName = strings.ToUpper(categoryName)
templateData.PageName = strings.ToUpper(categoryName)
templateData.Posts = posts

t.ExecuteTemplate(w, "content", &templateData)
}

func DateHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
date := vars["date"]

d, _ := strconv.Atoi(date)
var posts = List(d, "", 0)

t, err := template.New("").Funcs(template.FuncMap{"tmpTimeFormat": tmpTimeFormat}).ParseFiles("views/list.html", "views/header.html", "views/footer.html")
checkErr(err)

var templateData struct {
PageName string
Posts *[]Post
}

templateData.PageName = strings.ToUpper(date)
templateData.Posts = posts

t.ExecuteTemplate(w, "content", &templateData)

}

func RecentHandler(w http.ResponseWriter, r *http.Request) {
pageId := r.FormValue("p")

Expand All @@ -287,7 +326,7 @@ func RecentHandler(w http.ResponseWriter, r *http.Request) {
p, _ = strconv.Atoi(pageId)
}

var posts = List("", p)
var posts = List(0, "", p)

t, err := template.New("").Funcs(template.FuncMap{"tmpTimeFormat": tmpTimeFormat}).ParseFiles("views/list.html", "views/header.html", "views/footer.html")

Expand Down Expand Up @@ -454,6 +493,8 @@ func main() {
r.HandleFunc("/{id:[0-9]+}/update", UpdateHandler).Methods("GET", "POST")
// Category
r.HandleFunc("/go/{categoryName}", CategoryHandler).Methods("GET")
// Date
r.HandleFunc("/date/{date}", DateHandler).Methods("GET")
// Auth
r.HandleFunc("/login", LoginHandler).Methods("GET", "POST")
// Home
Expand Down
4 changes: 3 additions & 1 deletion statics/scripts/script.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/*
$("section").eq(0).after($("<div id='disqus_thread'><a href='#'>comments?</a></div>"))
$("#disqus_thread").click(function(e){
e.preventDefault()
Expand All @@ -10,4 +11,5 @@ $("#disqus_thread").click(function(e){
+ "})();"
+ "</script>"
$(this).append($(disqus))
})
})
*/
18 changes: 17 additions & 1 deletion statics/styles/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ header ul span {
color: #999;
}

header .page-name {
padding: 0 3px;
display: inline-block;
vertical-align: text-top;
border-radius: 3px;
background: #000;
color: #fff;
font: 500 12px/1.6 Lucida,Verdana,Hiragino Sans GB,WenQuanYi Micro Hei,sans-serif
}

.main {
margin: 0 0 30px;
}
Expand Down Expand Up @@ -153,5 +163,11 @@ footer {
}

#disqus_thread {
font-size: 12px;
padding: 20px;
border-radius: 3px;
background: #eee;
}

#global-nav li, #global-nav h4 {
font-size: 14px !important;
}
154 changes: 154 additions & 0 deletions utility/md2sql.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
package main

import (
"bytes"
"encoding/json"
"github.com/russross/blackfriday"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)

const (
PATH = "utility/posts"
)

const CONFIG_NAME = "config.json"

type Config struct {
Password string
DbName string
DbConfig string
}

type Category struct {
Id int
Name string
}

type Post struct {
Id int64
Title string
Category string
CategoryId int
Time int64
Content string
Origin string
}

type Data struct {
Title string
Category string
Time int64
Content string
Origin string
}

func getConfig() Config {
var config Config

configFile, err := ioutil.ReadFile(CONFIG_NAME)
checkErr(err)

json.Unmarshal(configFile, &config)
return config
}

var conf = getConfig()

/** Render
* 将 string 转为 Data
*/
func Render(s string) (d Data, e error) {

lines := strings.Split(s, "\n")
recording := true
c := bytes.Buffer{}

for i := 0; i < len(lines); i++ {
if recording && strings.Index(lines[i], "---") == 0 {
recording = false
} else if recording {
if strings.Index(lines[i], "#") == 0 {
d.Title = strings.Trim(strings.Split(lines[i], "#")[1], " \r\n")
} else if strings.Index(lines[i], "- category:") == 0 {
d.Category = strings.Trim(strings.Split(lines[i], ":")[1], " \r\n")
} else if strings.Index(lines[i], "- time:") == 0 {
s := strings.Trim(strings.Split(lines[i], ":")[1], " \r\n")
t, err := time.Parse(`2006-01-02`, s) // 字符串格式化方式
if err != nil {
e = err
}
d.Time = t.Unix()
}
} else {
c.WriteString(lines[i])
c.WriteString("\n")
}
}

content := c.String()
d.Content = string(blackfriday.MarkdownCommon([]byte(content)))

d.Origin = s

return d, e
}

/** Post Render
* 将 Data 转为 Post
*/
func (post Post) Render(s string) (r Post, err error) {
data, err := Render(s)
r.Title = data.Title
r.Category = data.Category
r.Time = data.Time
r.Content = data.Content
r.Origin = data.Origin
return r, err
}

func main() {
var wg sync.WaitGroup
tokens := make(chan int, runtime.NumCPU())

err := filepath.Walk(PATH, func(path string, info os.FileInfo, err error) error {
tokens <- 1 // 获取令牌
wg.Add(1)

go func() {
if strings.HasSuffix(info.Name(), ".md") {
fileData, err := ioutil.ReadFile(path)
checkErr(err)
//defer fileData.Close()

origin := string(fileData)

var p Post
p, err = p.Render(origin)
checkErr(err)

log.Println(p.Title)
}

wg.Done()
<-tokens
}()

wg.Wait()
return nil
})

checkErr(err)
}

func checkErr(err error) {
if err != nil {
log.Println(err)
}
}
Loading

0 comments on commit d76029e

Please sign in to comment.