main.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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/engine"
  12. "golang-fave/engine/assets"
  13. "golang-fave/engine/basket"
  14. "golang-fave/engine/cblocks"
  15. "golang-fave/engine/consts"
  16. "golang-fave/engine/domains"
  17. "golang-fave/engine/logger"
  18. "golang-fave/engine/modules"
  19. "golang-fave/engine/mysqlpool"
  20. "golang-fave/engine/utils"
  21. "golang-fave/engine/workers"
  22. "golang-fave/support"
  23. "github.com/vladimirok5959/golang-server-bootstrap/bootstrap"
  24. "github.com/vladimirok5959/golang-server-resources/resource"
  25. "github.com/vladimirok5959/golang-server-sessions/session"
  26. "github.com/vladimirok5959/golang-server-static/static"
  27. "github.com/vladimirok5959/golang-worker/worker"
  28. )
  29. func init() {
  30. flag.StringVar(&consts.ParamHost, "host", "0.0.0.0", "server host")
  31. flag.IntVar(&consts.ParamPort, "port", 8080, "server port")
  32. flag.StringVar(&consts.ParamWwwDir, "dir", "", "virtual hosts directory")
  33. flag.BoolVar(&consts.ParamDebug, "debug", false, "debug mode with ignoring log files")
  34. flag.BoolVar(&consts.ParamKeepAlive, "keepalive", false, "enable/disable server keep alive")
  35. flag.Parse()
  36. }
  37. func main() {
  38. // Params from env vars
  39. read_env_params()
  40. // Check www dir
  41. consts.ParamWwwDir = utils.FixPath(consts.ParamWwwDir)
  42. if !utils.IsDirExists(consts.ParamWwwDir) {
  43. fmt.Printf("Virtual hosts directory is not exists\n")
  44. fmt.Printf("Example: ./fave -host 127.0.0.1 -port 80 -dir ./hosts\n")
  45. return
  46. }
  47. // Run database migration
  48. if err := support.New().
  49. Migration(context.Background(), consts.ParamWwwDir); err != nil {
  50. fmt.Printf("[MIGRATION] FAILED: %s\n", err)
  51. } else {
  52. fmt.Printf("[MIGRATION] DONE!\n")
  53. }
  54. // Init logger
  55. logs := logger.New()
  56. // Attach www dir to logger
  57. logs.SetWwwDir(consts.ParamWwwDir)
  58. // MySQL connections pool
  59. mpool := mysqlpool.New()
  60. // Session cleaner
  61. wSessCl := workers.SessionCleaner(consts.ParamWwwDir)
  62. // Image processing
  63. wImageGen := workers.ImageGenerator(consts.ParamWwwDir)
  64. // Xml generation
  65. wXmlGen := workers.XmlGenerator(consts.ParamWwwDir, mpool)
  66. // SMTP sender
  67. wSmtpSnd := workers.SmtpSender(consts.ParamWwwDir, mpool)
  68. // Init mounted resources
  69. res := resource.New()
  70. assets.PopulateResources(res)
  71. // Init static files helper
  72. stat := static.New(consts.DirIndexFile)
  73. // Init modules
  74. mods := modules.New()
  75. // Shop basket
  76. shopBasket := basket.New()
  77. wBasketCl := workers.BasketCleaner(shopBasket)
  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. // Convert
  105. var logs *logger.Logger
  106. if v, ok := (*o)[0].(*logger.Logger); ok {
  107. logs = v
  108. }
  109. var mpool *mysqlpool.MySqlPool
  110. if v, ok := (*o)[1].(*mysqlpool.MySqlPool); ok {
  111. mpool = v
  112. }
  113. var res *resource.Resource
  114. if v, ok := (*o)[6].(*resource.Resource); ok {
  115. res = v
  116. }
  117. var stat *static.Static
  118. if v, ok := (*o)[7].(*static.Static); ok {
  119. stat = v
  120. }
  121. var mods *modules.Modules
  122. if v, ok := (*o)[8].(*modules.Modules); ok {
  123. mods = v
  124. }
  125. var shopBasket *basket.Basket
  126. if v, ok := (*o)[9].(*basket.Basket); ok {
  127. shopBasket = v
  128. }
  129. // Mounted assets
  130. if res.Response(
  131. w,
  132. r,
  133. func(
  134. w http.ResponseWriter,
  135. r *http.Request,
  136. i *resource.OneResource,
  137. ) {
  138. if consts.ParamDebug && i.Path == "assets/cp/scripts.js" {
  139. w.Write([]byte("window.fave_debug=true;"))
  140. }
  141. },
  142. nil,
  143. ) {
  144. return
  145. }
  146. // Host and port
  147. host, port := utils.ExtractHostPort(r.Host, false)
  148. curr_host := host
  149. // Domain bindings
  150. doms := domains.New(consts.ParamWwwDir)
  151. if mhost := doms.GetHost(host); mhost != "" {
  152. curr_host = mhost
  153. }
  154. vhost_dir := consts.ParamWwwDir + string(os.PathSeparator) + curr_host
  155. if !utils.IsDirExists(vhost_dir) {
  156. curr_host = "localhost"
  157. vhost_dir = consts.ParamWwwDir + string(os.PathSeparator) + "localhost"
  158. }
  159. // Check for minimal dirs structure
  160. vhost_dir_config := vhost_dir + string(os.PathSeparator) + "config"
  161. vhost_dir_htdocs := vhost_dir + string(os.PathSeparator) + "htdocs"
  162. vhost_dir_logs := vhost_dir + string(os.PathSeparator) + "logs"
  163. vhost_dir_template := vhost_dir + string(os.PathSeparator) + "template"
  164. vhost_dir_tmp := vhost_dir + string(os.PathSeparator) + "tmp"
  165. if !utils.IsDirExists(vhost_dir_config) {
  166. utils.SystemErrorPageEngine(
  167. w,
  168. errors.New("Folder "+vhost_dir_config+" is not found"),
  169. )
  170. return
  171. }
  172. if !utils.IsDirExists(vhost_dir_htdocs) {
  173. utils.SystemErrorPageEngine(
  174. w,
  175. errors.New("Folder "+vhost_dir_htdocs+" is not found"),
  176. )
  177. return
  178. }
  179. if !utils.IsDirExists(vhost_dir_logs) {
  180. utils.SystemErrorPageEngine(
  181. w,
  182. errors.New("Folder "+vhost_dir_logs+" is not found"),
  183. )
  184. return
  185. }
  186. if !utils.IsDirExists(vhost_dir_template) {
  187. utils.SystemErrorPageEngine(
  188. w,
  189. errors.New("Folder "+vhost_dir_template+" is not found"),
  190. )
  191. return
  192. }
  193. if !utils.IsDirExists(vhost_dir_tmp) {
  194. utils.SystemErrorPageEngine(
  195. w,
  196. errors.New("Folder "+vhost_dir_tmp+" is not found"),
  197. )
  198. return
  199. }
  200. // Static files
  201. if stat.Response(vhost_dir_htdocs, w, r, nil, nil) {
  202. return
  203. }
  204. // robots.txt, styles.css and scripts.js from templates dir
  205. if ServeTemplateFile(w, r, "robots.txt", "", vhost_dir_template) {
  206. return
  207. }
  208. if ServeTemplateFile(w, r, "styles.css", "assets/theme/", vhost_dir_template) {
  209. return
  210. }
  211. if ServeTemplateFile(w, r, "scripts.js", "assets/theme/", vhost_dir_template) {
  212. return
  213. }
  214. // Session
  215. sess := session.New(w, r, vhost_dir_tmp)
  216. defer sess.Close()
  217. // Logic
  218. if mpool != nil {
  219. if engine.Response(
  220. mpool,
  221. shopBasket,
  222. logs,
  223. mods,
  224. w,
  225. r,
  226. sess,
  227. cbs,
  228. host,
  229. port,
  230. curr_host,
  231. vhost_dir_config,
  232. vhost_dir_htdocs,
  233. vhost_dir_logs,
  234. vhost_dir_template,
  235. vhost_dir_tmp,
  236. ) {
  237. return
  238. }
  239. }
  240. // Error 404
  241. utils.SystemErrorPage404(w)
  242. }
  243. // Shutdown callback
  244. shutdown := func(
  245. ctx context.Context,
  246. o *[]bootstrap.Iface,
  247. ) error {
  248. var errs []string
  249. if wBasketCl, ok := (*o)[10].(*worker.Worker); ok {
  250. if err := wBasketCl.Shutdown(ctx); err != nil {
  251. errs = append(errs, fmt.Sprintf("(%T): %s", wBasketCl, err.Error()))
  252. }
  253. }
  254. if wSmtpSnd, ok := (*o)[5].(*worker.Worker); ok {
  255. if err := wSmtpSnd.Shutdown(ctx); err != nil {
  256. errs = append(errs, fmt.Sprintf("(%T): %s", wSmtpSnd, err.Error()))
  257. }
  258. }
  259. if wXmlGen, ok := (*o)[4].(*worker.Worker); ok {
  260. if err := wXmlGen.Shutdown(ctx); err != nil {
  261. errs = append(errs, fmt.Sprintf("(%T): %s", wXmlGen, err.Error()))
  262. }
  263. }
  264. if wImageGen, ok := (*o)[3].(*worker.Worker); ok {
  265. if err := wImageGen.Shutdown(ctx); err != nil {
  266. errs = append(errs, fmt.Sprintf("(%T): %s", wImageGen, err.Error()))
  267. }
  268. }
  269. if wSessCl, ok := (*o)[2].(*worker.Worker); ok {
  270. if err := wSessCl.Shutdown(ctx); err != nil {
  271. errs = append(errs, fmt.Sprintf("(%T): %s", wSessCl, err.Error()))
  272. }
  273. }
  274. if mpool, ok := (*o)[1].(*mysqlpool.MySqlPool); ok {
  275. if err := mpool.Close(); err != nil {
  276. errs = append(errs, fmt.Sprintf("(%T): %s", mpool, err.Error()))
  277. }
  278. }
  279. if logs, ok := (*o)[0].(*logger.Logger); ok {
  280. logs.Close()
  281. }
  282. if len(errs) > 0 {
  283. return errors.New("Shutdown callback: " + strings.Join(errs, ", "))
  284. }
  285. return nil
  286. }
  287. // Start server
  288. bootstrap.Start(
  289. &bootstrap.Opts{
  290. Handle: logs.Handler,
  291. Host: server_address,
  292. Path: consts.AssetsPath,
  293. Cbserv: server_params,
  294. Before: before,
  295. After: after,
  296. Timeout: 8 * time.Second,
  297. Shutdown: shutdown,
  298. Objects: &[]bootstrap.Iface{
  299. logs,
  300. mpool,
  301. wSessCl,
  302. wImageGen,
  303. wXmlGen,
  304. wSmtpSnd,
  305. res,
  306. stat,
  307. mods,
  308. shopBasket,
  309. wBasketCl,
  310. },
  311. },
  312. )
  313. }
  314. func read_env_params() {
  315. if consts.ParamHost == "0.0.0.0" {
  316. if os.Getenv("FAVE_HOST") != "" {
  317. consts.ParamHost = os.Getenv("FAVE_HOST")
  318. }
  319. }
  320. if consts.ParamPort == 8080 {
  321. if os.Getenv("FAVE_PORT") != "" {
  322. consts.ParamPort = utils.StrToInt(os.Getenv("FAVE_PORT"))
  323. }
  324. }
  325. if consts.ParamWwwDir == "" {
  326. if os.Getenv("FAVE_DIR") != "" {
  327. consts.ParamWwwDir = os.Getenv("FAVE_DIR")
  328. }
  329. }
  330. if consts.ParamDebug == false {
  331. if os.Getenv("FAVE_DEBUG") == "true" {
  332. consts.ParamDebug = true
  333. }
  334. }
  335. if consts.ParamKeepAlive == false {
  336. if os.Getenv("FAVE_KEEPALIVE") == "true" {
  337. consts.ParamKeepAlive = true
  338. }
  339. }
  340. }
  341. func ServeTemplateFile(
  342. w http.ResponseWriter,
  343. r *http.Request,
  344. file string,
  345. path string,
  346. dir string,
  347. ) bool {
  348. if r.URL.Path == "/"+path+file {
  349. if utils.IsRegularFileExists(dir + string(os.PathSeparator) + file) {
  350. http.ServeFile(w, r, dir+string(os.PathSeparator)+file)
  351. return true
  352. }
  353. }
  354. return false
  355. }