localhost stuff works

This commit is contained in:
Simon Kellet 2024-07-06 19:52:58 +01:00
parent 5ac8ece038
commit 0ccd06b3ad
4 changed files with 80 additions and 9 deletions

View File

@ -3,13 +3,16 @@ package main
import (
"crypto/tls"
"fmt"
"io"
"log"
"net/url"
"strings"
)
type Responce struct {
Status string
Meta string
Body string
}
type Request struct {
@ -42,7 +45,13 @@ func Fetch(args ...string) {
func (c Client) Fetch(URL string, port string) {
conn := c.connect(URL, port)
defer conn.Close()
c.sendRequest(conn, URL)
resp, err := c.getResponse(conn, URL)
if err != nil {
log.Fatal(err)
}
//fmt.Printf("resp: %s, %s\n", resp.Status, resp.Meta)
fmt.Printf("----------\n%s", resp.Body)
}
func (c Client) connect(URL string, port string) *tls.Conn {
@ -58,11 +67,55 @@ func (c Client) connect(URL string, port string) *tls.Conn {
return conn
}
func (c Client) sendRequest(connection *tls.Conn, requestURL string) {
CRLF := "\r\n"
reqSize, err := connection.Write([]byte(requestURL + CRLF))
// func (c Client) getResponse(connection *tls.Conn, URL string) {
func (c Client) getResponse(connection *tls.Conn, URL string) (Responce, error) {
err := c.sendRequest(connection, URL)
if err != nil {
log.Fatal(err)
return Responce{}, err
}
fmt.Printf("request (%d bytes) sent...\n", reqSize)
body := handleBody(connection)
first, second := getFirstTwoWords(body)
return Responce{
Status: first,
Meta: second,
Body: body[(len(first) + len(second)):],
}, nil
}
func getFirstTwoWords(input string) (string, string) {
reply := strings.Split(strings.Split(input, "\n")[0], " ")
return reply[0], reply[1]
}
func handleBody(connection *tls.Conn) string {
buf := make([]byte, 4096)
var body []byte
for {
n, err := connection.Read(buf)
if err != nil {
//handle EOF
if err == io.EOF {
break
}
log.Fatal(err)
}
body = append(body, buf[:n]...)
}
return string(body)
}
func (c Client) sendRequest(connection *tls.Conn, requestURL string) error {
CRLF := "\r\n"
_, err := connection.Write([]byte(requestURL + CRLF))
if err != nil {
log.Fatal(err)
return err
}
//fmt.Printf("request (%d bytes) sent...\n", reqSize)
return nil
}

Binary file not shown.

24
main.go
View File

@ -1,7 +1,25 @@
package main
func main() {
fullUrl := "gemini://localhost/test.gmi"
Fetch(fullUrl)
import (
"fmt"
"os"
)
func usage() {
fmt.Printf("%s: url port[OPTIONAL]\n", os.Args[0])
}
func main() {
if len(os.Args) == 1 {
usage()
os.Exit(1)
}
if len(os.Args) == 2 {
//defualt port
Fetch(os.Args[1])
}
if len(os.Args) == 3 {
//custom port
Fetch(os.Args[1], os.Args[2])
}
}

View File

@ -2,4 +2,4 @@
set -xe
./agate --content ./content
./agate --content ./content --addr 0.0.0.0:1967