main.go 8.9 KB

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