http.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package sitemap
  2. import (
  3. "net/http"
  4. )
  5. type contextKey string
  6. const hostWithSchemeKey contextKey = "HostWithScheme"
  7. func (site *SiteMapBuilder) MountTo(mux *http.ServeMux) {
  8. mux.Handle(site.pathName, site)
  9. }
  10. func (index *SiteMapIndexBuilder) MountTo(mux *http.ServeMux) {
  11. mux.Handle(index.pathName, index)
  12. for _, site := range index.siteMaps {
  13. mux.Handle(site.pathName, site)
  14. }
  15. }
  16. func (robot *RobotsBuilder) MountTo(mux *http.ServeMux) {
  17. mux.Handle("/robots.txt", robot)
  18. }
  19. func (site *SiteMapBuilder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  20. w.Header().Set("Content-Type", "application/xml;charset=UTF-8")
  21. w.WriteHeader(http.StatusOK)
  22. w.Write([]byte(EncodeToXmlByRequest(r, site)))
  23. }
  24. func (index *SiteMapIndexBuilder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  25. w.Header().Set("Content-Type", "application/xml;charset=UTF-8")
  26. w.WriteHeader(http.StatusOK)
  27. w.Write([]byte(EncodeToXmlByRequest(r, index)))
  28. }
  29. func (robot *RobotsBuilder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  30. w.Header().Set("Content-Type", "text/plain;charset=UTF-8")
  31. w.WriteHeader(http.StatusOK)
  32. w.Write([]byte(robot.ToTxt()))
  33. }
  34. func EncodeToXmlByRequest(r *http.Request, encoder EncodeToXmlInterface) string {
  35. var host string
  36. if r.URL.Host != "" {
  37. host = r.URL.Scheme + "://" + r.URL.Host
  38. }
  39. return encoder.EncodeToXml(WithHost(host, r.Context()))
  40. }