format gophermap lines

git-svn-id: file:///srv/svn/repo/tokiko/trunk@2 8f5ca974-a7f8-e144-9f80-d41d5039c194
This commit is contained in:
shokara 2021-12-23 17:29:28 +00:00
parent 0c323ed7f1
commit 43309deebe
2 changed files with 46 additions and 21 deletions

View File

@ -1,2 +1,2 @@
iGophermap test file Err localhost 7070
0Server source file /main.go localhost 7070
iGophermap test file
0Server source file /main.go

63
main.go
View File

@ -3,12 +3,47 @@ package main
import (
"bufio"
// "fmt"
"io/ioutil"
"log"
"net"
"os"
"strings"
)
const HOST = "0.0.0.0"
const PORT = "7070"
const HOSTNAME = "demiurge.shoko.home"
const DIR = "."
func formatLine(line string) string {
splitted := strings.Split(line, "\t")
if len(splitted) == 3 {
return line
} else if len(splitted) == 2 {
line += "\t" + HOSTNAME + "\t" + PORT
} else if len(splitted) == 1 {
line += "\tErr\t" + HOSTNAME + "\t" + PORT
}
return line
}
func printGophermap(c net.Conn, dir string) {
file, err := os.Open(dir + "Gophermap")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = file.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
c.Write([]byte(formatLine(scanner.Text()) + "\n"))
}
}
func connHandle(c net.Conn) {
data, err := bufio.NewReader(c).ReadString('\n')
if err != nil {
@ -16,30 +51,20 @@ func connHandle(c net.Conn) {
return
}
if string(data) == "\r\n" {
file, err := os.Open("Gophermap")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = file.Close(); err != nil {
log.Fatal(err)
}
}()
content, err := ioutil.ReadAll(file)
c.Write([]byte(content))
c.Write([]byte(".\r\n"))
if data == "\r\n" {
printGophermap(c, "./")
}
c.Write([]byte(".\r\n"))
c.Close()
}
func main() {
HOST := "0.0.0.0"
PORT := "7070"
ADDR := HOST + ":" + PORT
const ADDR = HOST + ":" + PORT
log.Printf("Starting thomomys on %s\n", ADDR)
os.Chdir(DIR)
l, err := net.Listen("tcp", ADDR)
if err != nil {
log.Fatal(err)