Initial add

This commit is contained in:
Robert Anderberg
2023-10-21 21:31:49 -07:00
commit eb15d37527
7 changed files with 351 additions and 0 deletions

BIN
favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 198 B

15
index.html Normal file
View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Dandelion</title>
<script src="main.js"></script>
</head>
<body>
<div id="status"></div>
<div id="log" style="margin-bottom: 100px"></div>
<textarea cols="40" rows="8" id="textarea_post"></textarea>
<input type="button" value="post" id="button_post" />
<div id="content"></div>
</body>
</html>

BIN
main Executable file

Binary file not shown.

92
main.go Normal file
View File

@@ -0,0 +1,92 @@
package main
import (
"fmt"
"log"
"net"
"net/http"
"strconv"
)
// LoggingHandler is a custom http.Handler that logs requests and delegates them to the underlying handler.
type LoggingHandler struct {
handler http.Handler
}
func (lh *LoggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Printf("Serving file: %s", r.URL.Path)
lh.handler.ServeHTTP(w, r)
}
func getAddressString(portNumber int) string {
return (":" + strconv.Itoa(portNumber))
}
func portIsInUse(port int) bool {
addr := fmt.Sprintf(":%d", port)
conn, err := net.Listen("tcp", addr)
if err != nil {
return true
}
conn.Close()
return false
}
func main() {
dir := "./"
startPort := 8000
const maxAttempts = 10
fmt.Println("Starting...")
// Configure TLS with the self-signed certificate and private key
// tlsConfig := &tls.Config{
// MinVersion: tls.VersionTLS12,
// PreferServerCipherSuites: true,
// InsecureSkipVerify: true,
// Certificates: make([]tls.Certificate, 1),
// }
// Load the certificate and private key
// cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
// if err != nil {
// log.Fatalf("Failed to load certificate and key: %v", err)
// }
// tlsConfig.Certificates[0] = cert
port := startPort
for attempts := 0; attempts < maxAttempts; attempts++ {
fmt.Printf("Trying port %d", port)
if portIsInUse(port) {
fmt.Println("...port in use!")
port++
continue
}
// If the port is not in use, bind your server here
// For example:
addr := ":" + strconv.Itoa(port)
log.Printf("\nServing %s on %s using HTTP/2...", dir, addr)
// Configure the HTTP/2 server
server := &http.Server{
Addr: addr,
Handler: &LoggingHandler{http.FileServer(http.Dir(dir))},
// TLSConfig: tlsConfig,
}
fmt.Println("Configured...")
fmt.Println("Serving...")
// Start the server
server.ListenAndServe()
if err := server.ListenAndServeTLS("", ""); err != nil {
log.Fatalf("Server failed: %v", err)
}
fmt.Println("Server started on port:", port)
}
log.Fatalf("Could not find an open port after %d attempts", maxAttempts)
}

163
main.js Normal file

File diff suppressed because one or more lines are too long

29
mdns.sh Executable file
View File

@@ -0,0 +1,29 @@
#!/bin/bash
# Set the service type
service_type="_http._tcp"
# Begin script
echo "Starting script to search for $service_type services..."
# Browse for devices advertising the service
dns-sd -B $service_type | while read -r timestamp junk type instance more_junk; do
# Filter out non-relevant lines
if [[ ! $type == $service_type || -z $instance ]]; then
continue
fi
# Log the extracted instance name
echo "Found instance: $instance"
# Look up the instance details to get the hostname
hostname=$(dns-sd -L "$instance" $service_type 2>/dev/null | grep -Eo '[^ ]+\.local' | head -n 1)
if [ -z "$hostname" ]; then
echo "Hostname not found for instance: $instance"
else
echo "Hostname for $instance is: $hostname"
fi
done
echo "Script completed."

52
sw.js Normal file
View File

@@ -0,0 +1,52 @@
// Establish a cache name
const cacheName = 'dandelion_cache_v1';
const contentToCache = [
"/index.html",
"/main.js",
"/favicon.ico",
];
self.addEventListener('install', (e) => {
e.waitUntil(
(async () => {
const cache = await caches.open(cacheName);
console.log("[Service Worker] Caching all: app shell and content", contentToCache);
await cache.addAll(contentToCache);
})(),
);
});
self.addEventListener("fetch", (e) => {
e.respondWith(
(async () => {
const r = await caches.match(e.request);
console.log(`[Service Worker] Fetching resource: ${e.request.url}`);
if (r) {
return r;
}
try {
const response = await fetch(e.request);
} catch(e) {
console.warn(e);
}
const cache = await caches.open(cacheName);
console.log(`[Service Worker] Caching new resource: ${e.request.url}`);
cache.put(e.request, response.clone());
return response;
})(),
);
});
addEventListener("message", async (e) => {
console.log(`Message received: ${e.data}`);
switch (e.data.type) {
case "updateMain":
const cache = await caches.open(cacheName);
console.log(`[Service Worker] Caching new resource: main.js`);
cache.put("/main.js", new Response());
break;
}
});