prusa-connect-local/main.go

57 lines
1.4 KiB
Go

package main
import (
"bytes"
"flag"
"io"
"log"
"net/http"
"strings"
"time"
)
type Config struct {
PrinterHostname string
Port string
}
func main() {
var hostname string
flag.StringVar(&hostname, "hostname", "localhost", "Hostname the Prusa Connect API is available at (assumes http)")
var port string
flag.StringVar(&port, "port", "3000", "Local port to run server on")
flag.Parse()
config := Config{
PrinterHostname: "http://" + hostname,
Port: port,
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "index.html" || r.URL.Path == "/" {
http.ServeFile(w, r, "./static/")
} else if strings.HasSuffix(r.URL.Path, ".js") {
http.ServeFile(w, r, "./static/"+r.URL.Path)
} else if strings.HasSuffix(r.URL.Path, ".css") {
http.ServeFile(w, r, "./static/"+r.URL.Path)
} else if strings.HasSuffix(r.URL.Path, ".ico") {
http.ServeFile(w, r, "./static/"+r.URL.Path)
} else if strings.HasPrefix(r.URL.Path, "/api") {
resp, err := http.Get(config.PrinterHostname + r.URL.Path)
if err != nil {
log.Println(err)
http.NotFoundHandler().ServeHTTP(w, r)
} else {
b, err := io.ReadAll(resp.Body)
if err != nil {
log.Println(err)
http.NotFoundHandler().ServeHTTP(w, r)
}
http.ServeContent(w, r, "", time.Now(), bytes.NewReader(b))
}
} else {
http.NotFoundHandler().ServeHTTP(w, r)
}
})
http.ListenAndServe(":"+config.Port, nil)
}