main.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. if consts.ParamDebug && i.Path == "assets/cp/scripts.js" {
  114. w.Write([]byte("window.fave_debug=true;"))
  115. }
  116. },
  117. nil,
  118. ) {
  119. return
  120. }
  121. // Host and port
  122. host, port := utils.ExtractHostPort(r.Host, false)
  123. curr_host := host
  124. // Domain bindings
  125. doms := domains.New(consts.ParamWwwDir)
  126. if mhost := doms.GetHost(host); mhost != "" {
  127. curr_host = mhost
  128. }
  129. vhost_dir := consts.ParamWwwDir + string(os.PathSeparator) + curr_host
  130. if !utils.IsDirExists(vhost_dir) {
  131. curr_host = "localhost"
  132. vhost_dir = consts.ParamWwwDir + string(os.PathSeparator) + "localhost"
  133. }
  134. // Check for minimal dirs structure
  135. vhost_dir_config := vhost_dir + string(os.PathSeparator) + "config"
  136. vhost_dir_htdocs := vhost_dir + string(os.PathSeparator) + "htdocs"
  137. vhost_dir_logs := vhost_dir + string(os.PathSeparator) + "logs"
  138. vhost_dir_template := vhost_dir + string(os.PathSeparator) + "template"
  139. vhost_dir_tmp := vhost_dir + string(os.PathSeparator) + "tmp"
  140. if !utils.IsDirExists(vhost_dir_config) {
  141. utils.SystemErrorPageEngine(
  142. w,
  143. errors.New("Folder "+vhost_dir_config+" is not found"),
  144. )
  145. return
  146. }
  147. if !utils.IsDirExists(vhost_dir_htdocs) {
  148. utils.SystemErrorPageEngine(
  149. w,
  150. errors.New("Folder "+vhost_dir_htdocs+" is not found"),
  151. )
  152. return
  153. }
  154. if !utils.IsDirExists(vhost_dir_logs) {
  155. utils.SystemErrorPageEngine(
  156. w,
  157. errors.New("Folder "+vhost_dir_logs+" is not found"),
  158. )
  159. return
  160. }
  161. if !utils.IsDirExists(vhost_dir_template) {
  162. utils.SystemErrorPageEngine(
  163. w,
  164. errors.New("Folder "+vhost_dir_template+" is not found"),
  165. )
  166. return
  167. }
  168. if !utils.IsDirExists(vhost_dir_tmp) {
  169. utils.SystemErrorPageEngine(
  170. w,
  171. errors.New("Folder "+vhost_dir_tmp+" is not found"),
  172. )
  173. return
  174. }
  175. // Static files
  176. if stat.Response(vhost_dir_htdocs, w, r, nil, nil) {
  177. return
  178. }
  179. // Robots.txt and styles.css from template dir
  180. if ServeTemplateFile(w, r, "robots.txt", "", vhost_dir_template) {
  181. return
  182. }
  183. if ServeTemplateFile(w, r, "styles.css", "assets/theme/", vhost_dir_template) {
  184. return
  185. }
  186. if ServeTemplateFile(w, r, "scripts.js", "assets/theme/", vhost_dir_template) {
  187. return
  188. }
  189. // Session
  190. sess := session.New(w, r, vhost_dir_tmp)
  191. defer sess.Close()
  192. // Convert
  193. var lg *logger.Logger
  194. if v, ok := (*o)[0].(*logger.Logger); ok {
  195. lg = v
  196. }
  197. var mpool *mysqlpool.MySqlPool
  198. if v, ok := (*o)[1].(*mysqlpool.MySqlPool); ok {
  199. mpool = v
  200. }
  201. // ---
  202. // Logic
  203. if mpool != nil {
  204. if engine.Response(
  205. mpool,
  206. sb,
  207. lg,
  208. mods,
  209. w,
  210. r,
  211. sess,
  212. cbs,
  213. host,
  214. port,
  215. curr_host,
  216. vhost_dir_config,
  217. vhost_dir_htdocs,
  218. vhost_dir_logs,
  219. vhost_dir_template,
  220. vhost_dir_tmp,
  221. ) {
  222. return
  223. }
  224. }
  225. // Error 404
  226. utils.SystemErrorPage404(w)
  227. }
  228. // Shutdown callback
  229. shutdown := func(
  230. ctx context.Context,
  231. o *[]bootstrap.Iface,
  232. ) error {
  233. var errs []string
  234. // ---
  235. if mpool, ok := (*o)[1].(*mysqlpool.MySqlPool); ok {
  236. if err := mpool.Close(); err != nil {
  237. errs = append(errs, err.Error())
  238. }
  239. }
  240. if lg, ok := (*o)[0].(*logger.Logger); ok {
  241. lg.Close()
  242. }
  243. // ---
  244. if len(errs) > 0 {
  245. return errors.New("Shutdown callback: " + strings.Join(errs, ", "))
  246. }
  247. return nil
  248. }
  249. // Start server
  250. bootstrap.Start(
  251. &bootstrap.Opts{
  252. Handle: lg.Handler,
  253. Host: server_address,
  254. Path: consts.AssetsPath,
  255. Cbserv: server_params,
  256. Before: before,
  257. After: after,
  258. Timeout: 8 * time.Second,
  259. Shutdown: shutdown,
  260. Objects: &[]bootstrap.Iface{
  261. lg,
  262. mpool,
  263. },
  264. },
  265. )
  266. }
  267. func ServeTemplateFile(
  268. w http.ResponseWriter,
  269. r *http.Request,
  270. file string,
  271. path string,
  272. dir string,
  273. ) bool {
  274. if r.URL.Path == "/"+path+file {
  275. if utils.IsRegularFileExists(dir + string(os.PathSeparator) + file) {
  276. http.ServeFile(w, r, dir+string(os.PathSeparator)+file)
  277. return true
  278. }
  279. }
  280. return false
  281. }