all repos — flounder @ d6be68418a350fc835a86dd82bba9935d7a609ba

A small site builder for the Gemini protocol

main.go (view raw)

  1package main
  2
  3import (
  4	"flag"
  5	"fmt"
  6	"io/ioutil"
  7	"log"
  8	"os"
  9	"path"
 10	"path/filepath"
 11	"sort"
 12	"strings"
 13	"sync"
 14	"time"
 15)
 16
 17var c Config // global var to hold static configuration
 18
 19const ( // todo make configurable
 20	userFilesPath = "./files"
 21)
 22
 23type File struct {
 24	Creator     string
 25	Name        string
 26	UpdatedTime time.Time
 27}
 28
 29func getUsers() ([]string, error) {
 30	return []string{"me", "other guy"}, nil
 31}
 32
 33/// Perform some checks to make sure the file is OK
 34func checkIfValidFile(filename string, fileBytes []byte) error {
 35	ext := strings.ToLower(path.Ext(filename))
 36	found := false
 37	for _, mimetype := range c.OkExtensions {
 38		if ext == mimetype {
 39			found = true
 40		}
 41	}
 42	if !found {
 43		return fmt.Errorf("Invalid file extension: %s", ext)
 44	}
 45	if len(fileBytes) > c.MaxFileSize {
 46		return fmt.Errorf("File too large. File was %s bytes, Max file size is %s", len(fileBytes), c.MaxFileSize)
 47	}
 48	return nil
 49}
 50
 51func getIndexFiles() ([]*File, error) { // cache this function
 52	result := []*File{}
 53	err := filepath.Walk(userFilesPath, func(path string, info os.FileInfo, err error) error {
 54		if err != nil {
 55			log.Printf("Failure accessing a path %q: %v\n", path, err)
 56			return err // think about
 57		}
 58		// make this do what it should
 59		result = append(result, &File{
 60			Name:        info.Name(),
 61			Creator:     "alex",
 62			UpdatedTime: info.ModTime(),
 63		})
 64		return nil
 65	})
 66	if err != nil {
 67		return nil, err
 68	}
 69	// sort
 70	// truncate
 71	sort.Slice(result, func(i, j int) bool {
 72		return result[i].UpdatedTime.Before(result[j].UpdatedTime)
 73	})
 74	if len(result) > 50 {
 75		result = result[:50]
 76	}
 77	return result, nil
 78} // todo clean up paths
 79
 80func getUserFiles(user string) ([]*File, error) {
 81	result := []*File{}
 82	files, err := ioutil.ReadDir(path.Join(userFilesPath, user))
 83	if err != nil {
 84		return nil, err
 85	}
 86	for _, file := range files {
 87		result = append(result, &File{
 88			Name:        file.Name(),
 89			Creator:     user,
 90			UpdatedTime: file.ModTime(),
 91		})
 92	}
 93	return result, nil
 94}
 95
 96func main() {
 97	configPath := flag.String("c", "flounder.toml", "path to config file")
 98	var err error
 99	c, err = getConfig(*configPath)
100	if err != nil {
101		log.Fatal(err)
102	}
103
104	wg := new(sync.WaitGroup)
105	wg.Add(2)
106	go func() {
107		runHTTPServer()
108		wg.Done()
109	}()
110	go func() {
111		runGeminiServer()
112		wg.Done()
113	}()
114	wg.Wait()
115}