Healthcheck/news.go
2024-09-01 22:05:49 -03:00

85 lines
2.0 KiB
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
)
type NewsItem struct {
Timestamp time.Time `json:"timestamp"`
Title string `json:"title"`
Content string `json:"content"`
Author string `json:"author"`
}
// Função para listar e ordenar arquivos .md
func getMarkdownFiles() ([]NewsItem, error) {
dirPath := "./news" // Assumindo que os arquivos .md estão na pasta 'news'
var newsItems []NewsItem
err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && strings.HasSuffix(info.Name(), ".md") {
parts := strings.Split(info.Name(), "-")
if len(parts) < 7 {
return nil // Ignora arquivos que não estão no formato esperado
}
year, month, day := parts[0], parts[1], parts[2]
hour, minute := parts[3], parts[4]
author := strings.ReplaceAll(parts[5], "_", " ")
title := strings.TrimSuffix(strings.ReplaceAll(parts[6], "_", " "), ".md")
timestamp, err := time.Parse("2006-01-02T15:04", fmt.Sprintf("%s-%s-%sT%s:%s", year, month, day, hour, minute))
if err != nil {
return err
}
content, err := os.ReadFile(path)
if err != nil {
return err
}
newsItems = append(newsItems, NewsItem{
Timestamp: timestamp,
Title: title,
Content: string(content),
Author: author,
})
}
return nil
})
if err != nil {
return nil, err
}
// Ordena os arquivos por timestamp em ordem decrescente
sort.Slice(newsItems, func(i, j int) bool {
return newsItems[i].Timestamp.After(newsItems[j].Timestamp)
})
return newsItems, nil
}
// Endpoint para retornar a lista de arquivos .md como JSON
func newsHandler(w http.ResponseWriter, r *http.Request) {
newsItems, err := getMarkdownFiles()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(newsItems)
}