Beispiel #1
0
/*
query all tags
*/
func (this *Model) QueryTags() (tags []Tag, err error) {
	db, err := sql.Open("mysql", "root:dumx@tcp(localhost:3306)/myblog?charset=utf8")
	if nil != err {
		logger.Errorln(err)
		return
	}
	defer db.Close()
	querySql := "select * from myblog.tags"
	rows, err := db.Query(querySql)
	if nil != err {
		logger.Errorln(err)
	}

	for rows.Next() {
		var id int
		var tag string
		rows.Scan(&id, &tag)
		tags = append(tags, Tag{id, tag})
	}
	logger.Debugln("Tags table :", tags)
	if 0 == len(tags) {
		err = errors.New("not found")
	}
	return
}
Beispiel #2
0
/*
对所有的URL进行注册
*/
func router(rw http.ResponseWriter, req *http.Request) {
	urlPath := req.URL.Path
	log.Println(urlPath)
	logger.Debugln(urlPath)
	switch {
	case rootUrl == urlPath || strings.HasPrefix(urlPath, articlesUrl):
		friends := controllers.NewArticles()
		friends.Handler(rw, req)
	case strings.HasPrefix(urlPath, adminUrl):
		admin := controllers.NewAdmin()
		admin.Handler(rw, req)
	case strings.HasPrefix(urlPath, wsUrl):
		ws := controllers.NewWS()
		ws.Handler(rw, req)
	case strings.HasPrefix(urlPath, contactUrl):
		contact := controllers.NewContact()
		contact.Handler(rw, req)
	case strings.HasPrefix(urlPath, aboutUrl):
		//about := controllers.NewAbout()
		//about.Handler(rw, req)
	case strings.HasPrefix(urlPath, "/bootstrap"): //static files
		http.ServeFile(rw, req, "libs"+urlPath)
	case strings.HasPrefix(urlPath, "public/"): //static files
		http.ServeFile(rw, req, urlPath)
	case urlPath == "/favicon.ico": //the request which browser send automatically
		http.ServeFile(rw, req, "public/images/favicon.ico")
	default:
		controllers.NotFoundHandler(rw, req)
	}
}
Beispiel #3
0
/*
根据标签检索博客
*/
func (this *Model) QueryByTag(tagId int) (blogs []Blog, err error) {
	//TODO
	db, err := sql.Open("mysql", "root:dumx@tcp(localhost:3306)/myblog?charset=utf8")
	if nil != err {
		logger.Errorln(err)
		return
	}
	defer db.Close()
	querySql := "select * from myblog.blogs WHERE tag_id="
	tmp := strconv.FormatInt(int64(tagId), 10)
	querySql += tmp
	rows, err := db.Query(querySql)
	if nil != err {
		logger.Errorln(err)
	}

	for rows.Next() {
		var id, tagId int
		var content, title, createDate string
		rows.Scan(&id, &content, &title, &createDate, &tagId)
		blogs = append(blogs, Blog{Id: id, Content: content, Title: title, CreateDate: createDate, TagId: tagId})
	}
	logger.Debugln("Blogs table :", blogs)
	if 0 == len(blogs) {
		err = errors.New("not found")
	}
	return
}
Beispiel #4
0
func (this *Admin) AddBlogHandler(rw http.ResponseWriter, req *http.Request) {
	logger.Infoln("entered AddBlogHandler()")
	req.ParseForm()
	//name,err :=CheckCookie(r)
	//if err != nil{
	//	log.Println(err)
	//	http.Redirect(w,r,"/", http.StatusFound)
	//	return
	//	}
	switch req.Method {
	case "GET":
		t, err := template.ParseFiles("views/admin/add_blog.html")
		if nil != err {
			logger.Errorln(err)
			return
		}
		//查询博客标签
		m := models.Model{}
		tags, err := m.QueryTags()
		if nil != err {
			logger.Errorln(err)
		}
		//为了使用查询出来的博客标签,格式化查询结果
		type tmp struct {
			Tags []models.Tag
		}
		tmp2 := tmp{tags}
		if err = t.Execute(rw, tmp2); nil != err {
			logger.Errorln(err)
			return
		}
	case "POST":
		title := req.FormValue("title")
		content := req.FormValue("content")
		tag := req.FormValue("tag")
		tagId, _ := strconv.Atoi(tag) //从前端返回的是tag的ID
		logger.Debugln("title: ", title)
		logger.Debugln("content: ", content)
		logger.Debugln("arcticleTag: ", tag)

		model := models.Model{}
		model.AddBlog(title, content, tagId)
		http.Redirect(rw, req, "/", http.StatusFound)
	}
}
Beispiel #5
0
/*
根据用户选择的page,来显示具体哪些文章
*/
func (this *Articles) ArticleByPage(pageId int) (blogs []models.Blog, err error) {
	err = this.QueryAllBlogs()
	if nil != err {
		logger.Errorln(err)
		return
	}
	println(pageId)
	//访问的page没有超出
	if pageId <= 0 || len(AllBlogs) < pageId*MaxPageNum+MaxPageNum {
		blogs = AllBlogs[0:MaxPageNum : MaxPageNum+1]
	} else {
		println(pageId * MaxPageNum)
		println(pageId*MaxPageNum + MaxPageNum)
		logger.Debugln(len(AllBlogs))
		blogs = AllBlogs[pageId*MaxPageNum : pageId*MaxPageNum+MaxPageNum]
	}

	return
}
Beispiel #6
0
/*
query all blogs
*/
func (this *Model) QueryBlogs() (blogs []Blog, err error) {
	//连接数据库
	db, err := sql.Open(config.Config["driver_name"], config.Config["dsn"])
	if nil != err {
		logger.Errorln(err)
		return
	}
	defer db.Close()

	//sql := `SELECT * FROM myblog.blogs LIMIT `
	//因为博客文章不多,所以一次性的把所有博客都读取到内存中。
	//数据库更新频率很低,所以也没有内存和数据之间的同步
	sql := `SELECT * FROM myblog.blogs`

	//执行SQL语句
	rows, err := db.Query(sql)
	if nil != err {
		logger.Errorln(err)
		return
	}

	//把查询到的数据格式化
	for rows.Next() {
		var id, tagId int
		var content, title, createDate string
		rows.Scan(&id, &content, &title, &createDate, &tagId)
		blogs = append(blogs, Blog{Id: id, Content: content, Title: title, CreateDate: createDate, TagId: tagId})
	}
	logger.Debugln("Blogs table :", blogs)

	//没有查询到博客,设置err值
	if 0 == len(blogs) {
		err = errors.New("not found")
	}
	return
}
Beispiel #7
0
/*
显示所有文章
*/
func (this *Articles) ArticlesHandler(rw http.ResponseWriter, req *http.Request) {
	logger.Infoln("entered ArticlesHandler()")
	//username,err := CheckCookie(r)
	//if err != nil{
	//	log.Println(err)
	//http.Redirect(w,r,"/", http.StatusFound)
	//	}
	var blogs []models.Blog
	var err error
	var pageId int = 0
	switch req.Method {
	case "GET":
		switch {
		case "" != req.FormValue("title"):
			strTitle := req.FormValue("title")
			logger.Debugln(strTitle)
			titleId, _ := strconv.Atoi(strTitle)
			blogs, err = this.ArticleByTitle(titleId)
		case "" != req.FormValue("tag"):
			strTag := req.FormValue("tag")
			logger.Debugln(strTag)
			tagId, _ := strconv.Atoi(strTag)
			blogs, err = this.ArticleByTitle(tagId)
		case "" != req.FormValue("page"):
			strPage := req.FormValue("page")
			logger.Debugln(strPage)
			pageId, _ = strconv.Atoi(strPage)
			blogs, err = this.ArticleByPage(pageId)
		default:
			err = this.QueryAllBlogs()
			if nil != err {
				logger.Errorln(err)
				return
			}
			blogs = AllBlogs
		}
		//获取所有标签
		var tags []models.Tag
		tags, err = new(models.Model).QueryTags()
		if nil != err {
			logger.Errorln(err)
			return
		}

		//格式化所有博客和标签,以便template包使用
		type tmp struct {
			Blgs    []models.Blog
			Tags    []models.Tag
			Page    []int //多少页博客
			CurPage int   //现在显示哪一页
		}
		//为了在前端显示分页信息,make一个数组
		pageNum := 0
		if len(AllBlogs)%MaxPageNum == 0 {
			pageNum = len(AllBlogs) / MaxPageNum
		} else {
			pageNum = len(AllBlogs)/MaxPageNum + 1
		}
		var pages = make([]int, pageNum, pageNum)
		for i := 0; i < pageNum; i++ {
			pages[i] = i + 1
		}
		if 0 == pageId {
			pageId = pageId + 1
		}
		tmp2 := tmp{blogs, tags, pages, pageId}
		t := template.New("")
		t = t.Funcs(template.FuncMap{"plus": utils.Plus})
		//ParseFiles uses the filename as the template name inside of the template object.
		t, err = t.ParseFiles("views/articles/index.html")
		if nil != err {
			logger.Errorln(err)
			log.Println(err)
			return
		}

		//显示内容
		//ParseFiles uses the filename as the template name inside of the template object.
		//So, Have to use ExecuteTemplate() instead fo Execute(),
		//and use index.html as the name of t
		if err = t.ExecuteTemplate(rw, "index.html", tmp2); nil != err {
			logger.Errorln(err)
			log.Println(err)
			return
		}
	case "POST":
		//TODO
	}
}