module_api.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package modules
  2. import (
  3. "net/http"
  4. "os"
  5. "golang-fave/assets"
  6. "golang-fave/engine/fetdata"
  7. "golang-fave/engine/wrapper"
  8. "golang-fave/utils"
  9. )
  10. func (this *Modules) RegisterModule_Api() *Module {
  11. return this.newModule(MInfo{
  12. WantDB: true,
  13. Mount: "api",
  14. Name: "Api",
  15. Order: 803,
  16. System: true,
  17. Icon: assets.SysSvgIconPage,
  18. Sub: &[]MISub{},
  19. }, func(wrap *wrapper.Wrapper) {
  20. if len(wrap.UrlArgs) == 2 && wrap.UrlArgs[0] == "api" && wrap.UrlArgs[1] == "products" {
  21. if (*wrap.Config).API.XML.Enabled == 1 {
  22. // Fix url
  23. if wrap.R.URL.Path[len(wrap.R.URL.Path)-1] != '/' {
  24. http.Redirect(wrap.W, wrap.R, wrap.R.URL.Path+"/"+utils.ExtractGetParams(wrap.R.RequestURI), 301)
  25. return
  26. }
  27. target_file := wrap.DHtdocs + string(os.PathSeparator) + "products.xml"
  28. if !utils.IsFileExists(target_file) {
  29. data := []byte(this.api_GenerateEmptyXml(wrap))
  30. // Make empty file
  31. if file, err := os.Create(target_file); err == nil {
  32. file.Write(data)
  33. file.Close()
  34. }
  35. // Make regular XML
  36. data = []byte(this.api_GenerateXml(wrap))
  37. // Save file
  38. wrap.RemoveProductXmlCacheFile()
  39. if file, err := os.Create(target_file); err == nil {
  40. file.Write(data)
  41. file.Close()
  42. }
  43. wrap.W.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  44. wrap.W.Header().Set("Content-Type", "text/xml; charset=utf-8")
  45. wrap.W.WriteHeader(http.StatusOK)
  46. wrap.W.Write(data)
  47. } else {
  48. http.ServeFile(wrap.W, wrap.R, target_file)
  49. }
  50. } else {
  51. wrap.W.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  52. wrap.W.WriteHeader(http.StatusNotFound)
  53. wrap.W.Write([]byte("Disabled!"))
  54. }
  55. } else if len(wrap.UrlArgs) == 1 {
  56. // Fix url
  57. if wrap.R.URL.Path[len(wrap.R.URL.Path)-1] != '/' {
  58. http.Redirect(wrap.W, wrap.R, wrap.R.URL.Path+"/"+utils.ExtractGetParams(wrap.R.RequestURI), 301)
  59. return
  60. }
  61. // Some info
  62. wrap.W.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  63. wrap.W.WriteHeader(http.StatusOK)
  64. wrap.W.Write([]byte("Fave engine API mount point!"))
  65. } else {
  66. // User error 404 page
  67. wrap.RenderFrontEnd("404", fetdata.New(wrap, true, nil, nil), http.StatusNotFound)
  68. return
  69. }
  70. }, func(wrap *wrapper.Wrapper) (string, string, string) {
  71. // No any page for back-end
  72. return "", "", ""
  73. })
  74. }