search.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package controllers
  2. import (
  3. "github.com/astaxie/beego"
  4. "github.com/lifei6671/mindoc/conf"
  5. "github.com/lifei6671/mindoc/models"
  6. "github.com/lifei6671/mindoc/utils"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. )
  11. type SearchController struct {
  12. BaseController
  13. }
  14. func (c *SearchController) Index() {
  15. c.Prepare()
  16. c.TplName = "search/index.tpl"
  17. //如果没有开启你们访问则跳转到登录
  18. if !c.EnableAnonymous && c.Member == nil {
  19. c.Redirect(beego.URLFor("AccountController.Login"), 302)
  20. return
  21. }
  22. keyword := c.GetString("keyword")
  23. pageIndex, _ := c.GetInt("page", 1)
  24. c.Data["BaseUrl"] = c.BaseUrl()
  25. if keyword != "" {
  26. c.Data["Keyword"] = keyword
  27. member_id := 0
  28. if c.Member != nil {
  29. member_id = c.Member.MemberId
  30. }
  31. search_result, totalCount, err := models.NewDocumentSearchResult().FindToPager(keyword, pageIndex, conf.PageSize, member_id)
  32. if err != nil {
  33. beego.Error(err)
  34. return
  35. }
  36. if totalCount > 0 {
  37. html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, conf.PageSize, totalCount)
  38. c.Data["PageHtml"] = html
  39. } else {
  40. c.Data["PageHtml"] = ""
  41. }
  42. if len(search_result) > 0 {
  43. for _, item := range search_result {
  44. item.DocumentName = strings.Replace(item.DocumentName, keyword, "<em>"+keyword+"</em>", -1)
  45. if item.Description != "" {
  46. src := item.Description
  47. //将HTML标签全转换成小写
  48. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  49. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  50. //去除STYLE
  51. re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
  52. src = re.ReplaceAllString(src, "")
  53. //去除SCRIPT
  54. re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
  55. src = re.ReplaceAllString(src, "")
  56. //去除所有尖括号内的HTML代码,并换成换行符
  57. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  58. src = re.ReplaceAllString(src, "\n")
  59. //去除连续的换行符
  60. re, _ = regexp.Compile("\\s{2,}")
  61. src = re.ReplaceAllString(src, "\n")
  62. r := []rune(src)
  63. if len(r) > 100 {
  64. src = string(r[:100])
  65. } else {
  66. src = string(r)
  67. }
  68. item.Description = strings.Replace(src, keyword, "<em>"+keyword+"</em>", -1)
  69. }
  70. if item.Identify == "" {
  71. item.Identify = strconv.Itoa(item.DocumentId)
  72. }
  73. if item.ModifyTime.IsZero() {
  74. item.ModifyTime = item.CreateTime
  75. }
  76. }
  77. }
  78. c.Data["Lists"] = search_result
  79. }
  80. }