main.go 8.9 KB

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