http.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package http
  2. import (
  3. "crypto/sha1"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "go-common/app/interface/openplatform/seo/conf"
  8. "go-common/app/interface/openplatform/seo/service"
  9. "go-common/library/log"
  10. bm "go-common/library/net/http/blademaster"
  11. "go-common/library/net/http/blademaster/middleware/verify"
  12. )
  13. var (
  14. srv *service.Service
  15. vfy *verify.Verify
  16. )
  17. // Init init seo service
  18. func Init(c *conf.Config) {
  19. srv = service.New(c)
  20. vfy = verify.New(c.Verify)
  21. engine := bm.DefaultServer(c.BM)
  22. router(engine)
  23. if err := engine.Start(); err != nil {
  24. log.Error("innerEngine.Start() error(%v)", err)
  25. panic(err)
  26. }
  27. }
  28. func router(e *bm.Engine) {
  29. e.Ping(ping)
  30. e.Register(register)
  31. g := e.Group("/platform")
  32. {
  33. g.GET("/home.html", proList)
  34. g.GET("/detail.html", proInfo)
  35. }
  36. e.GET("/detail.html", itemInfo)
  37. e.GET("/sitemap.xml", sitemap)
  38. }
  39. func ping(c *bm.Context) {
  40. if err := srv.Ping(c); err != nil {
  41. log.Error("ping error(%v)", err)
  42. c.AbortWithStatus(http.StatusServiceUnavailable)
  43. }
  44. }
  45. func register(c *bm.Context) {
  46. c.JSON(map[string]interface{}{}, nil)
  47. }
  48. // isBot check if user-agent is bot
  49. func isBot(c *bm.Context) bool {
  50. ua := c.Request.Header.Get("User-Agent")
  51. ua = strings.ToLower(ua)
  52. for _, bot := range conf.Conf.Seo.BotList {
  53. if strings.Contains(ua, strings.ToLower(bot)) {
  54. return true
  55. }
  56. }
  57. return false
  58. }
  59. // FullUrl get request full url
  60. func FullUrl(c *bm.Context) string {
  61. return c.Request.Host + c.Request.RequestURI
  62. }
  63. func setCache(c *bm.Context, res []byte) bool {
  64. h := c.Writer.Header()
  65. h.Set("Content-Type", "text/html; charset=utf8")
  66. h.Set("Cache-Control", fmt.Sprintf("max-age=%d", conf.Conf.Seo.MaxAge))
  67. etag := ETag(res)
  68. h.Set("ETag", etag)
  69. if etag == c.Request.Header.Get("If-None-Match") {
  70. c.Writer.WriteHeader(http.StatusNotModified)
  71. return true
  72. }
  73. return false
  74. }
  75. // ETag get etag for cache
  76. func ETag(res []byte) string {
  77. return fmt.Sprintf(`W/"%x-%x"`, len(res), sha1.Sum(res))
  78. }
  79. // logUA log User-Agent and Url
  80. func logUA(c *bm.Context) {
  81. log.Infov(c,
  82. log.KV("ua", c.Request.Header.Get("User-Agent")),
  83. log.KV("url", fmt.Sprintf("%s%s", c.Request.Host, c.Request.URL)),
  84. )
  85. }