main.go 8.1 KB

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