main.go 7.5 KB

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