package archive import ( "fmt" "html/template" "io/ioutil" "math" "net/http" "strings" ) const ( pageNotSet int = -1 ) type ArchiveState struct { svr *ArchiveServer log *LogSource logBestSlug string query string queryIsRegex bool ym YearMonth page int highestPage int } func NewArchiveState(svr *ArchiveServer) *ArchiveState { return &ArchiveState{ svr: svr, page: pageNotSet, } } func (this *ArchiveState) selectSource(log *LogSource, slug string) { this.log = log this.logBestSlug = slug } // renderView renders a single page of log entries. // - Mandatory: log, ym // - Optional: page func (this *ArchiveState) renderView(w http.ResponseWriter) { if this.log == nil { this.renderError(w, "Invalid log source selected") return } fname, err := this.svr.LogFile(this.log, this.ym) if err != nil { this.renderError(w, err.Error()) return } fc, err := ioutil.ReadFile(fname) if err != nil { this.renderError(w, err.Error()) return } lines := strings.Split(string(fc), "\n") this.highestPage = int(math.Ceil(float64(len(lines))/float64(this.svr.cfg.LinesPerPage))) - 1 if this.page == pageNotSet || this.page > this.highestPage { this.page = this.highestPage } if this.page < 0 { this.page = 0 } startLine := this.svr.cfg.LinesPerPage * this.page endLine := this.svr.cfg.LinesPerPage * (this.page + 1) if endLine > len(lines) { endLine = len(lines) } output := "" for i := startLine; i < endLine; i += 1 { output += template.HTMLEscapeString(lines[i]) + "
\n" } this.renderTemplate(w, []byte(output)) } func (this *ArchiveState) renderError(w http.ResponseWriter, msg string) { this.renderTemplate(w, []byte(template.HTMLEscapeString(msg))) } func (this *ArchiveState) renderTemplate(w http.ResponseWriter, body []byte) { this.renderTemplateHead(w) w.Write(body) this.renderTemplateFoot(w) } func (this *ArchiveState) renderTemplateHead(w http.ResponseWriter) { w.Header().Set(`Content-Type`, `text/html; charset=UTF-8`) w.Header().Set(`X-UA-Compatible`, `IE=Edge`) w.WriteHeader(200) title := `Archives` if this.log != nil { title = this.log.Description + ` Archives` } showPageURLs := (this.log != nil && len(this.query) == 0) w.Write([]byte(` ` + template.HTMLEscapeString(title) + `
`)) // Header ends } func (this *ArchiveState) renderTemplateFoot(w http.ResponseWriter) { w.Write([]byte(`
`)) }