robots.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package sitemap
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type RobotsBuilder struct {
  7. userAgents []*userAgentBuilder
  8. }
  9. type userAgentBuilder struct {
  10. name string
  11. disallows []string
  12. allows []string
  13. sitemaps []string
  14. }
  15. const (
  16. // https://www.keycdn.com/blog/web-crawlers
  17. AllAgents = "*"
  18. GoogleAgent = "Googlebot"
  19. BingAgent = "Bingbot"
  20. YahooAgent = "Slurp"
  21. DuckDuckAgent = "DuckDuckBot"
  22. BaiduAgent = "Baiduspider"
  23. YandexAgent = "YandexBot"
  24. SogouAgent = "Sogou web spider/4.0"
  25. ExaleadAgent = "Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Exabot-Thumbnails)"
  26. FacebookAgent = "facebot"
  27. AlexaAgent = "ia_archiver"
  28. )
  29. func Robots() *RobotsBuilder {
  30. return &RobotsBuilder{}
  31. }
  32. func (r *RobotsBuilder) Agent(name string) *userAgentBuilder {
  33. agent := &userAgentBuilder{
  34. name: name,
  35. }
  36. r.userAgents = append(r.userAgents, agent)
  37. return agent
  38. }
  39. func (r *RobotsBuilder) ToTxt() string {
  40. b := strings.Builder{}
  41. for _, agent := range r.userAgents {
  42. b.WriteString(fmt.Sprintf("User-agent: %s\n", agent.name))
  43. for _, disallow := range agent.disallows {
  44. b.WriteString(fmt.Sprintf("Disallow: %s\n", disallow))
  45. }
  46. for _, allow := range agent.allows {
  47. b.WriteString(fmt.Sprintf("Allow: %s\n", allow))
  48. }
  49. for _, sitemap := range agent.sitemaps {
  50. b.WriteString(fmt.Sprintf("Sitemap: %s\n", sitemap))
  51. }
  52. b.WriteString("\n")
  53. }
  54. return b.String()
  55. }
  56. func (u *userAgentBuilder) AddSitemapUrl(sitemaps ...string) *userAgentBuilder {
  57. u.sitemaps = append(u.sitemaps, sitemaps...)
  58. return u
  59. }
  60. func (u *userAgentBuilder) Allow(allows ...string) *userAgentBuilder {
  61. u.allows = append(u.allows, allows...)
  62. return u
  63. }
  64. func (u *userAgentBuilder) Disallow(disallows ...string) *userAgentBuilder {
  65. u.disallows = append(u.disallows, disallows...)
  66. return u
  67. }