1
0

search.go 2.2 KB

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