support selectors for files and gophermaps in different directories

git-svn-id: file:///srv/svn/repo/tokiko/trunk@4 8f5ca974-a7f8-e144-9f80-d41d5039c194
This commit is contained in:
shokara 2021-12-23 18:58:34 +00:00
parent f5f9ba6e3e
commit 6041c607c1

59
main.go
View File

@ -3,6 +3,7 @@ package main
import (
"bufio"
// "fmt"
"io"
"log"
"net"
"os"
@ -12,7 +13,7 @@ import (
const HOST = "0.0.0.0"
const PORT = "7070"
const HOSTNAME = "demiurge.shoko.home"
const DIR = "."
const DIR = "./"
func formatLine(line string) string {
splitted := strings.Split(line, "\t")
@ -27,8 +28,12 @@ func formatLine(line string) string {
return line
}
func writeError(c net.Conn, msg string) {
c.Write([]byte(formatLine("3" + msg)))
}
func printGophermap(c net.Conn, dir string) {
file, err := os.Open(dir + "Gophermap")
file, err := os.Open(dir + "/Gophermap")
if err != nil {
log.Fatal(err)
}
@ -42,6 +47,36 @@ func printGophermap(c net.Conn, dir string) {
for scanner.Scan() {
c.Write([]byte(formatLine(scanner.Text()) + "\n"))
}
c.Write([]byte(".\r\n"))
}
func printFile(c net.Conn, path string) {
file, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
defer func() {
if err = file.Close(); err != nil {
log.Fatal(err)
}
}()
// 1024 bytes or 1K for buffer
const bufSz = 1024
b := make([]byte, bufSz)
for {
readSz, err := file.Read(b)
if err != nil {
if err != io.EOF {
log.Fatal(err)
}
break
}
c.Write(b[:readSz])
}
}
func connHandle(c net.Conn) {
@ -51,11 +86,27 @@ func connHandle(c net.Conn) {
return
}
if strings.TrimRight(data, "\r\n") == "" {
selector := strings.TrimRight(data, "\r\n")
log.Println(selector)
if selector == "" {
printGophermap(c, "./")
} else if selector[0] == '/' {
info, err := os.Stat(selector[1:])
if err != nil {
log.Fatal(err)
}
if info.IsDir() {
printGophermap(c, selector[1:])
} else {
printFile(c, selector[1:])
}
} else {
writeError(c, "Selector doesn't start with a / or it contains a ..")
}
c.Write([]byte(".\r\n"))
c.Close()
}