main.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "flag"
  6. "fmt"
  7. "net/http"
  8. "os"
  9. "strings"
  10. "time"
  11. "golang-fave/assets"
  12. "golang-fave/cblocks"
  13. "golang-fave/consts"
  14. "golang-fave/domains"
  15. "golang-fave/engine"
  16. "golang-fave/engine/basket"
  17. "golang-fave/engine/mysqlpool"
  18. "golang-fave/logger"
  19. "golang-fave/modules"
  20. "golang-fave/support"
  21. "golang-fave/utils"
  22. "github.com/vladimirok5959/golang-server-bootstrap/bootstrap"
  23. "github.com/vladimirok5959/golang-server-resources/resource"
  24. "github.com/vladimirok5959/golang-server-sessions/session"
  25. "github.com/vladimirok5959/golang-server-static/static"
  26. )
  27. func init() {
  28. flag.StringVar(&consts.ParamHost, "host", "0.0.0.0", "server host")
  29. flag.IntVar(&consts.ParamPort, "port", 8080, "server port")
  30. flag.StringVar(&consts.ParamWwwDir, "dir", "", "virtual hosts directory")
  31. flag.BoolVar(&consts.ParamDebug, "debug", false, "debug mode with ignoring log files")
  32. flag.BoolVar(&consts.ParamKeepAlive, "keepalive", false, "enable/disable server keep alive")
  33. flag.Parse()
  34. }
  35. func main() {
  36. // Params from env vars
  37. read_env_params()
  38. // Check www dir
  39. consts.ParamWwwDir = utils.FixPath(consts.ParamWwwDir)
  40. if !utils.IsDirExists(consts.ParamWwwDir) {
  41. fmt.Printf("Virtual hosts directory is not exists\n")
  42. fmt.Printf("Example: ./fave -host 127.0.0.1 -port 80 -dir ./hosts\n")
  43. return
  44. }
  45. // Run database migration
  46. if err := support.New().Migration(consts.ParamWwwDir); err != nil {
  47. fmt.Printf("[ERROR] MIGRATION FAILED: %s\n", err)
  48. }
  49. // Init logger
  50. lg := logger.New()
  51. // Attach www dir to logger
  52. lg.SetWwwDir(consts.ParamWwwDir)
  53. // Session cleaner
  54. sess_cl_ch, sess_cl_stop := session_clean_start(consts.ParamWwwDir)
  55. defer session_clean_stop(sess_cl_ch, sess_cl_stop)
  56. // Image processing
  57. imgs_cl_ch, imgs_cl_stop := image_start(consts.ParamWwwDir)
  58. defer image_stop(imgs_cl_ch, imgs_cl_stop)
  59. // Init mounted resources
  60. res := resource.New()
  61. assets.PopulateResources(res)
  62. // Init static files helper
  63. stat := static.New(consts.DirIndexFile)
  64. // Init modules
  65. mods := modules.New()
  66. // MySQL connections pool
  67. mpool := mysqlpool.New()
  68. // Xml generation
  69. xml_cl_ch, xml_cl_stop := xml_start(consts.ParamWwwDir, mpool)
  70. defer xml_stop(xml_cl_ch, xml_cl_stop)
  71. // SMTP sender
  72. smtp_cl_ch, smtp_cl_stop := smtp_start(consts.ParamWwwDir, mpool)
  73. defer smtp_stop(smtp_cl_ch, smtp_cl_stop)
  74. // Shop basket
  75. sb := basket.New()
  76. sb_cl_ch, sb_cl_stop := basket_clean_start(sb)
  77. defer basket_clean_stop(sb_cl_ch, sb_cl_stop)
  78. // Init cache blocks
  79. cbs := cblocks.New()
  80. // Init and start web server
  81. server_address := fmt.Sprintf("%s:%d", consts.ParamHost, consts.ParamPort)
  82. // Server params
  83. server_params := func(s *http.Server) {
  84. s.SetKeepAlivesEnabled(consts.ParamKeepAlive)
  85. }
  86. // Before callback
  87. before := func(
  88. ctx context.Context,
  89. w http.ResponseWriter,
  90. r *http.Request,
  91. o *[]bootstrap.Iface,
  92. ) {
  93. w.Header().Set("Server", "fave.pro/"+consts.ServerVersion)
  94. }
  95. // After callback
  96. after := func(
  97. ctx context.Context,
  98. w http.ResponseWriter,
  99. r *http.Request,
  100. o *[]bootstrap.Iface,
  101. ) {
  102. // Schema
  103. r.URL.Scheme = "http"
  104. // Mounted assets
  105. if res.Response(
  106. w,
  107. r,
  108. func(
  109. w http.ResponseWriter,
  110. r *http.Request,
  111. i *resource.OneResource,
  112. ) {
  113. w.Header().Set("Cache-Control", "public, max-age=31536000")
  114. if consts.ParamDebug && i.Path == "assets/cp/scripts.js" {
  115. w.Write([]byte("window.fave_debug=true;"))
  116. }
  117. },
  118. nil,
  119. ) {
  120. return
  121. }
  122. // Host and port
  123. host, port := utils.ExtractHostPort(r.Host, false)
  124. curr_host := host
  125. // Domain bindings
  126. doms := domains.New(consts.ParamWwwDir)
  127. if mhost := doms.GetHost(host); mhost != "" {
  128. curr_host = mhost
  129. }
  130. vhost_dir := consts.ParamWwwDir + string(os.PathSeparator) + curr_host
  131. if !utils.IsDirExists(vhost_dir) {
  132. curr_host = "localhost"
  133. vhost_dir = consts.ParamWwwDir + string(os.PathSeparator) + "localhost"
  134. }
  135. // Check for minimal dirs structure
  136. vhost_dir_config := vhost_dir + string(os.PathSeparator) + "config"
  137. vhost_dir_htdocs := vhost_dir + string(os.PathSeparator) + "htdocs"
  138. vhost_dir_logs := vhost_dir + string(os.PathSeparator) + "logs"
  139. vhost_dir_template := vhost_dir + string(os.PathSeparator) + "template"
  140. vhost_dir_tmp := vhost_dir + string(os.PathSeparator) + "tmp"
  141. if !utils.IsDirExists(vhost_dir_config) {
  142. utils.SystemErrorPageEngine(
  143. w,
  144. errors.New("Folder "+vhost_dir_config+" is not found"),
  145. )
  146. return
  147. }
  148. if !utils.IsDirExists(vhost_dir_htdocs) {
  149. utils.SystemErrorPageEngine(
  150. w,
  151. errors.New("Folder "+vhost_dir_htdocs+" is not found"),
  152. )
  153. return
  154. }
  155. if !utils.IsDirExists(vhost_dir_logs) {
  156. utils.SystemErrorPageEngine(
  157. w,
  158. errors.New("Folder "+vhost_dir_logs+" is not found"),
  159. )
  160. return
  161. }
  162. if !utils.IsDirExists(vhost_dir_template) {
  163. utils.SystemErrorPageEngine(
  164. w,
  165. errors.New("Folder "+vhost_dir_template+" is not found"),
  166. )
  167. return
  168. }
  169. if !utils.IsDirExists(vhost_dir_tmp) {
  170. utils.SystemErrorPageEngine(
  171. w,
  172. errors.New("Folder "+vhost_dir_tmp+" is not found"),
  173. )
  174. return
  175. }
  176. // Static files
  177. if stat.Response(vhost_dir_htdocs, w, r, nil, nil) {
  178. return
  179. }
  180. // Robots.txt and styles.css from template dir
  181. if ServeTemplateFile(w, r, "robots.txt", "", vhost_dir_template) {
  182. return
  183. }
  184. if ServeTemplateFile(w, r, "styles.css", "assets/theme/", vhost_dir_template) {
  185. return
  186. }
  187. if ServeTemplateFile(w, r, "scripts.js", "assets/theme/", vhost_dir_template) {
  188. return
  189. }
  190. // Session
  191. sess := session.New(w, r, vhost_dir_tmp)
  192. defer sess.Close()
  193. // Convert
  194. var lg *logger.Logger
  195. if v, ok := (*o)[0].(*logger.Logger); ok {
  196. lg = v
  197. }
  198. var mpool *mysqlpool.MySqlPool
  199. if v, ok := (*o)[1].(*mysqlpool.MySqlPool); ok {
  200. mpool = v
  201. }
  202. // ---
  203. // Logic
  204. if mpool != nil {
  205. if engine.Response(
  206. mpool,
  207. sb,
  208. lg,
  209. mods,
  210. w,
  211. r,
  212. sess,
  213. cbs,
  214. host,
  215. port,
  216. curr_host,
  217. vhost_dir_config,
  218. vhost_dir_htdocs,
  219. vhost_dir_logs,
  220. vhost_dir_template,
  221. vhost_dir_tmp,
  222. ) {
  223. return
  224. }
  225. }
  226. // Error 404
  227. utils.SystemErrorPage404(w)
  228. }
  229. // Shutdown callback
  230. shutdown := func(
  231. ctx context.Context,
  232. o *[]bootstrap.Iface,
  233. ) error {
  234. var errs []string
  235. // ---
  236. if mpool, ok := (*o)[1].(*mysqlpool.MySqlPool); ok {
  237. if err := mpool.Close(); err != nil {
  238. errs = append(errs, err.Error())
  239. }
  240. }
  241. if lg, ok := (*o)[0].(*logger.Logger); ok {
  242. lg.Close()
  243. }
  244. // ---
  245. if len(errs) > 0 {
  246. return errors.New("Shutdown callback: " + strings.Join(errs, ", "))
  247. }
  248. return nil
  249. }
  250. // Start server
  251. bootstrap.Start(
  252. &bootstrap.Opts{
  253. Handle: lg.Handler,
  254. Host: server_address,
  255. Path: consts.AssetsPath,
  256. Cbserv: server_params,
  257. Before: before,
  258. After: after,
  259. Timeout: 8 * time.Second,
  260. Shutdown: shutdown,
  261. Objects: &[]bootstrap.Iface{
  262. lg,
  263. mpool,
  264. },
  265. },
  266. )
  267. }
  268. func ServeTemplateFile(
  269. w http.ResponseWriter,
  270. r *http.Request,
  271. file string,
  272. path string,
  273. dir string,
  274. ) bool {
  275. if r.URL.Path == "/"+path+file {
  276. f, err := os.Open(dir + string(os.PathSeparator) + file)
  277. if err == nil {
  278. defer f.Close()
  279. st, err := os.Stat(dir + string(os.PathSeparator) + file)
  280. if err == nil {
  281. if !st.Mode().IsDir() {
  282. http.ServeFile(w, r, dir+string(os.PathSeparator)+file)
  283. return true
  284. }
  285. }
  286. }
  287. }
  288. return false
  289. }