hikan.ru/main.go

74 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"log"
"main/mvc/controllers"
controllers_pages "main/mvc/controllers/pages"
"main/mvc/models"
"main/tools"
"net/http"
)
func init() {
log.SetPrefix("hikan.ru | ")
}
func main() {
var app *models.App
var err error
// Инициализация приложения
if app, err = models.AppInit("config.json"); err != nil {
log.Fatal(err)
}
// Настройка маршрутов и запуск
if setupRoutesAndRun(app) != nil {
log.Fatal(err)
}
}
func setupRoutesAndRun(a *models.App) error {
// Настройка маршрутов
router := setupRoutes(a)
// Запуск сервера
if ok, err := tools.IsIPInUse(a.Config.ServerIP); err != nil {
return err
} else if ok {
runServer(a.Config.ServerIP, a.Config.Port, router)
} else {
runServer(a.Config.LocalIP, a.Config.Port, router)
}
return nil
}
// Настраивает маршруты
func setupRoutes(a *models.App) *http.ServeMux {
router := http.NewServeMux()
// Цепочка обработчиков, которые сработают до отдачи страницы юзеру
m := controllers.MiddlewaresChain
// Обработка статических файлов с кэшированием
router.Handle(a.Config.AssetsPath, m(controllers.StaticHandler()))
// Странички
{
// Обработка главной страницы (русская версия)
router.Handle("/ru/", m(controllers_pages.MainRuPageHandler(a)))
// Обработка главной страницы
router.Handle("/", m(controllers_pages.MainPageHandler(a)))
}
return router
}
// Обертка над ListenAndServe, запускает сервер на указанном IP, PORT
func runServer(ip, port string, router http.Handler) {
addr := ip + port
log.Println("Run on", addr)
log.Fatal(http.ListenAndServe(addr, router))
}