Пример #1
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
}
Пример #2
0
/*
添加管理员
*/
func (this *Model) AddUser(name, psw string) error {
	username := html.EscapeString(name)
	password := html.EscapeString(psw)
	db, err := sql.Open("mysql", "root:dumx@tcp(localhost:3306)/myblog?charset=utf8")
	if nil != err {
		logger.Errorln(err)
		return err
	}
	defer db.Close()
	querySql := "select 1 from myblog.users WHERE name = ' " + username + "'"
	rows, err := db.Query(querySql)
	if nil != err {
		logger.Errorln(err)
		return err
	}
	if rows.Next() {
		return errors.New("user " + username + "exsited")
	}

	insertSql := "INSERT myblog.users SET name=?, password=?"
	stmt, err := db.Prepare(insertSql)
	if nil != err {
		logger.Errorln(err)
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(username, password)
	if nil != err {
		logger.Errorln(err)
		return err
	}

	return nil
}
Пример #3
0
/*
添加博客
*/
func (this *Model) AddBlog(title, content string, tagId int) error {
	//防止SQL注入
	title = html.EscapeString(title)
	content = html.EscapeString(content)

	//连接MYSQL数据库
	db, err := sql.Open("mysql", "root:dumx@tcp(localhost:3306)/myblog?charset=utf8")
	if nil != err {
		logger.Errorln(err)
		return err
	}
	defer db.Close()

	//构建Sql语句
	insertSql := "INSERT myblog.blogs SET content=?, title=?, create_date=?, tag_id=?"
	stmt, err := db.Prepare(insertSql)
	if nil != err {
		logger.Errorln(err)
		return err
	}
	defer stmt.Close()

	//replacer := strings.NewReplacer(" ", "&nbsp", "\r", "<br/>")
	//content = replacer.Replace(content)
	//获取插入时间
	now := strings.Split(time.Now().String(), " ")[0]
	//执行SQL语句
	_, err = stmt.Exec(content, title, now, tagId)
	if nil != err {
		logger.Errorln(err)
		return err
	}

	return nil
}
Пример #4
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
}
Пример #5
0
/*
管理员注册
*/
func (this *Admin) RegisterHandler(rw http.ResponseWriter, req *http.Request) {
	logger.Infoln("entered Register()")
	switch req.Method {
	case "GET":
		t, err := template.ParseFiles("views/admin/register.html")
		if nil != err {
			logger.Errorln(err)
			return
		}
		if err = t.Execute(rw, nil); nil != err {
			logger.Errorln(err)
			return
		}
	case "POST":
		req.ParseForm()
		name := req.FormValue("username")
		psw := req.FormValue("password")
		confirmPsw := req.FormValue("confirm_password")
		if psw != confirmPsw {
			//TBD
		}
		model := models.Model{}
		model.AddUser(name, psw)
		http.Redirect(rw, req, "/", http.StatusFound)
	}
}
Пример #6
0
/*
管理员登录
*/
func (this *Admin) LoginHandler(rw http.ResponseWriter, req *http.Request) {
	logger.Infoln("entered Login()")
	switch req.Method {
	case "GET":
		t, err := template.ParseFiles("views/admin/login.html")
		if nil != err {
			logger.Errorln(err)
			return
		}
		if err = t.Execute(rw, nil); nil != err {
			logger.Errorln(err)
			return
		}
	case "POST":
		req.ParseForm()
		name := req.FormValue("username")
		psw := req.FormValue("password")
		if err := CheckNamePsw(name, psw); nil != err {
			logger.Errorln(err)
			http.Redirect(rw, req, "/login", http.StatusFound)
			return
		}
		SetCookie(rw, CreateSessionID(name))
		http.Redirect(rw, req, "/add", http.StatusFound)
	}
}
Пример #7
0
func NotFoundHandler(rw http.ResponseWriter, req *http.Request) {
	t, err := template.ParseFiles(utils.BaseHtmlTplFile, utils.Error404HtmlTplFile)
	if nil != err {
		logger.Errorln(err)
		return
	}
	err = t.Execute(rw, nil)
	if nil != err {
		logger.Errorln(err)
		return
	}
}
Пример #8
0
/*
联系界面
*/
func (this *Contact) ContactHandler(rw http.ResponseWriter, req *http.Request) {
	switch req.Method {
	case "GET":
		t, err := template.ParseFiles("views/contact/contact.html")
		if nil != err {
			logger.Errorln(err)
			return
		}
		if err = t.Execute(rw, nil); nil != err {
			logger.Errorln(err)
			return
		}
	case "POST":
	}
}
Пример #9
0
/*
根据用户选择的标题,获取具体博客
*/
func (this *Articles) ArticleByTitle(blogId int) (blog []models.Blog, err error) {
	//按照标题查找博客
	blog, err = new(models.Model).QueryByTitle(blogId)
	if nil != err {
		logger.Errorln(err)
	}
	return
}
Пример #10
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)
	}
}
Пример #11
0
/*
根据用户选择的tag,来显示具体哪些文章
*/
func (this *Articles) ArticlesByTag(tagId int) (blogs []models.Blog, err error) {
	//按照标签查找博客
	blogs, err = new(models.Model).QueryByTag(tagId)
	if nil != err {
		logger.Errorln(err)
		blogs = append(blogs, models.Blog{Title: "no article"})
	}
	return
}
Пример #12
0
/*
获取所有博客内容存储在@AllBlogs
*/
func (this *Articles) QueryAllBlogs() (err error) {
	if 0 < len(AllBlogs) {
		return //已经查询过,AllBlogs已经有数据
	}
	//提取所有博客
	AllBlogs, err = new(models.Model).QueryBlogs()
	if nil != err {
		logger.Errorln(err)
	}
	return
}
Пример #13
0
/*
检查用户名和密码
Return Value:nil:success
*/
func (this *Model) CheckNamePsw(name, psw string) error {
	username := html.EscapeString(name)
	password := html.EscapeString(psw)
	db, err := sql.Open("mysql", "root:dumx@tcp(localhost:3306)/myblog?charset=utf8")
	if nil != err {
		logger.Errorln(err)
		return err
	}
	defer db.Close()
	querySql := "select 1 from myblog.users WHERE name = '" + username + "' AND password = '******'"
	rows, err := db.Query(querySql)
	if nil != err {
		logger.Errorln(err)
		return err
	}
	if rows.Next() {
		return nil
	}

	return errors.New("Unkown error")
}
Пример #14
0
func GetId(title, blogType, username string) (titleId, typeId, userId int64) {
	title = html.EscapeString(title)
	blogType = html.EscapeString(blogType)
	username = html.EscapeString(username)
	db, err := sql.Open("mysql", "root:dumx@tcp(localhost:3306)/myblog?charset=utf8")
	if nil != err {
		logger.Errorln(err)
	}
	defer db.Close()
	sql := `SELECT id FROM myblog.title WHERE title = '` + title + `'`
	rows, err := db.Query(sql)
	if nil != err {
		logger.Errorln(err)
	}
	for rows.Next() {
		rows.Scan(&titleId)
	}

	sql = `SELECT id FROM myblog.blog_type WHERE blog_type = '` + blogType + `'`
	rows, err = db.Query(sql)
	if nil != err {
		logger.Errorln(err)
	}
	for rows.Next() {
		rows.Scan(&typeId)
	}

	sql = `SELECT userid FROM myblog.users WHERE name = '` + username + `'`
	rows, err = db.Query(sql)
	if nil != err {
		logger.Errorln(err)
	}
	for rows.Next() {
		rows.Scan(&userId)
	}
	return
}
Пример #15
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
}
Пример #16
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
}
Пример #17
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
	}
}