arns-lt-gemini/main.go
Arnas Udovicius fcb49aa38c
All checks were successful
continuous-integration/drone/push Build is passing
favicon.txt
2022-08-18 02:49:38 +03:00

111 lines
2.7 KiB
Go

package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"strings"
"time"
"git.sr.ht/~adnano/go-gemini"
"git.sr.ht/~adnano/go-gemini/certificate"
)
var (
hostname string
port string
fileSrvHost string
fileSrvPort string
certificatePath string
)
func init() {
flag.StringVar(&hostname, "hostname", "", "capsule hostname")
flag.StringVar(&port, "port", "1965", "capsule port")
flag.StringVar(&certificatePath, "certificatePath", "", "capsule certificate path")
flag.StringVar(&fileSrvHost, "fileSrvHost", "", "file push server host")
flag.StringVar(&fileSrvPort, "fileSrvPort", "", "file push server port")
flag.Parse()
}
func main() {
certificates := &certificate.Store{}
certificates.Register(hostname)
if err := certificates.Load(certificatePath); err != nil {
panic(err)
}
mux := &gemini.Mux{}
mux.HandleFunc("/favicon.txt", processFavicon)
mux.HandleFunc("/", process)
server := &gemini.Server{
Handler: mux,
ReadTimeout: 30 * time.Second,
WriteTimeout: 1 * time.Minute,
GetCertificate: certificates.Get,
}
ctx := context.Background()
if err := server.ListenAndServe(ctx); err != nil {
log.Fatal(err)
}
}
func processFavicon(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprintf(w, "\u263d")
}
func process(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
fmt.Println(ctx, r, r.URL, r.Host)
renderIndex("en", w)
}
func renderIndex(lang string, w gemini.ResponseWriter) {
langPath := lang + "/"
if lang == "sgs" {
langPath = ""
}
w.SetMediaType("text/gemini")
content, err := os.ReadFile(fmt.Sprintf("templates/%s/index.gmi", lang))
if err != nil {
w.WriteHeader(gemini.StatusTemporaryFailure, "Internal server error")
return
}
page := string(content)
summery := GetSummery()
fmt.Println(summery)
tree := TSummery{}
err = json.Unmarshal([]byte(summery), &tree)
if err != nil {
w.WriteHeader(gemini.StatusTemporaryFailure, "Internal server error")
return
}
fmt.Println(tree)
categories := ""
for c, count := range tree.Categories {
fmt.Println(c, count)
categories = categories + fmt.Sprintf("=> /%s%s/%s %s (%d)\n", langPath, "tree/path", c, c, count)
}
page = strings.Replace(page, "{{categories}}", categories, 1)
tags := ""
for t, count := range tree.Tags {
tags = tags + fmt.Sprintf("=> /t/%s %s (%d)\n", t, t, count)
}
page = strings.Replace(page, "{{tags}}", tags, 1)
lastFiles := ""
for _, f := range GetLastFiles(tree.Files) {
lastFiles = lastFiles + fmt.Sprintf("=> /%s/%s %s (%s)\n", strings.Join(f.Category, "/"), f.Id, f.Description, f.Created)
}
page = strings.Replace(page, "{{last_posts}}", lastFiles, 1)
fmt.Fprintf(w, page)
}