~sfr/artemis

26953fafd6d294aa3c4c29dab583b9e8ab96b4ce — Sol Fisher Romanoff 4 months ago d155ebf
Add support for non-gemini files

all non-gmi files will be sent with a text/plain header

Implements: https://todo.sr.ht/~sfr/artemis/1
1 files changed, 20 insertions(+), 14 deletions(-)

M main.go
M main.go => main.go +20 -14
@@ 3,7 3,6 @@ package main
import (
	"bufio"
	"crypto/tls"
	"errors"
	"fmt"
	"io"
	"log"


@@ 114,9 113,19 @@ func route(conn io.ReadWriteCloser) {
		}
	}

	// add index.gmi if path is a directory
	if !strings.HasSuffix(path, ".gmi") {
	// add index.gmi if path not found and index exists
	if exists(path) {
		if strings.HasSuffix(path, ".gmi") {
			sendResponseHeader(conn, 20, "text/gemini; lang=en; charset=utf-8")
		} else {
			sendResponseHeader(conn, 20, "text/plain")
		}
	} else if exists(path + "/index.gmi") {
		path += "/index.gmi"
		sendResponseHeader(conn, 20, "text/gemini; lang=en; charset=utf-8")
	} else {
		sendResponseHeader(conn, 51, "not found")
		return
	}

	log.Println("serving file:", path)


@@ 124,17 133,14 @@ func route(conn io.ReadWriteCloser) {
	// load file
	content, err := os.ReadFile(path)

	// check if file exists
	if errors.Is(err, os.ErrNotExist) {
		sendResponseHeader(conn, 51, "not found")
		return
	} else if err != nil {
		sendResponseHeader(conn, 40, "internal server error")
		log.Println("error while loading file:", err)
		return
	}

	sendResponseHeader(conn, 20, "text/gemini; lang=en; charset=utf-8")
	sendResponseContent(conn, content)
	return
}

// check if file exists
func exists(path string) bool {
	if _, err := os.ReadFile(path); err != nil {
		return false
	}
	return true
}