package controllers import ( "log" "main/mvc/models" models_pages "main/mvc/models/pages" "main/tools" "net/http" "time" "unicode/utf8" ) // Обработчик главной страницы func MainPageHandler(a *models.App) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var err error // Количество запросов, обработанных сервером за 24ч if r.Method == "COUNT" { var count []byte if count, err = tools.GetJournalctlLogs("server", a.Config.ServerDomain, 24); err != nil { log.Printf("%s", err.Error()) } SendCount(w, count) return } // Пасхалка if r.Method == "LOVE" { SendLove(w) return } // Пасхалка 2 if r.Method == "LIMINAL" { SendLiminal(w) return } // Страничка рендерится только если ее нет в кэше pageData, ok := a.Cache.Get(models_pages.MainPageTmplName) if !ok { pageData, err = models_pages.RenderMainPage(a.Templates, a.Version) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } a.Cache.Set(models_pages.MainPageTmplName, pageData) } SendMainPage(w, pageData.([]byte)) }) } // Отправляет страницу func SendMainPage(w http.ResponseWriter, data []byte) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusOK) w.Write(data) } // Ответ на метод COUNT func SendCount(w http.ResponseWriter, data []byte) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusOK) w.Write(data) } // Ответ на метод LOVE func SendLove(w http.ResponseWriter) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusOK) w.Write([]byte("13.01.2005")) } // Ответ на метод LIMINAL func SendLiminal(w http.ResponseWriter) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("X-Accel-Buffering", "no") // важно для nginx w.WriteHeader(http.StatusOK) text := "If you're not careful and you slip out of reality in the wrong place, you'll end up in the Backstage, where there's nothing but the stench of old damp carpet, yellow-colored madness, the endless unbearable hum of fluorescent lights, and roughly six hundred million square miles of randomly arranged empty rooms." flusher, ok := w.(http.Flusher) if !ok { w.Write([]byte(text)) return } // Корректно работает с любыми UTF-8 символами! buf := make([]byte, 4) // Максимальный размер руны - 4 байта for _, char := range text { n := utf8.EncodeRune(buf, char) // руну байтами записываем в buf if _, err := w.Write(buf[:n]); err != nil { // [:n] потому что руной заняты только столько байт, сколько вернула EncodeRune return } if flusher != nil { flusher.Flush() } time.Sleep(50 * time.Millisecond) } }