main.go 7.8 KB

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