commit e6cf6ea
uint
·
2026-02-01 01:03:34 +0000 UTC
parent b10c515
gorados: add basic /library handling
3 files changed,
+103,
-1
+5,
-0
1@@ -0,0 +1,5 @@
2+### gorados
3+_gorados_ is a Go implementation of a _parados_ protocol
4+compliant client. It serves a HTML website and is designed
5+to be used as a home media server.
6+
+0,
-0
+98,
-1
1@@ -1,5 +1,102 @@
2 package main
3
4+import (
5+ "encoding/json"
6+ "flag"
7+ "fmt"
8+ "net/http"
9+ "os"
10+ "time"
11+)
12+
13+// library item
14+type item struct {
15+ ID string `json:"id"`
16+ Path string `json:"path"`
17+}
18+
19+// upstream response
20+type library_resp struct {
21+ Proto int `json:"proto"`
22+ Items []item `json:"items"`
23+}
24+
25+// app state
26+type handler struct {
27+ parados string
28+ user string
29+ pass string
30+ httpc* http.Client
31+}
32+
33+func (h* handler) library(w http.ResponseWriter, r *http.Request) {
34+ // build upstream req
35+ req, _ := http.NewRequest("GET", h.parados+"/library", nil)
36+ if h.user != "" {
37+ req.SetBasicAuth(h.user, h.pass)
38+ }
39+
40+ // call upstream
41+ resp, err := h.httpc.Do(req)
42+ if err != nil {
43+ http.Error(w, "Upstream Error", 502)
44+ return
45+ }
46+ defer resp.Body.Close()
47+
48+ if resp.StatusCode != 200 {
49+ http.Error(w, resp.Status, resp.StatusCode)
50+ return
51+ }
52+
53+ // decode json
54+ var lr library_resp
55+ if err := json.NewDecoder(resp.Body).Decode(&lr); err != nil {
56+ http.Error(w, "Bad JSON", 502)
57+ return
58+ }
59+ if lr.Proto != 1 {
60+ http.Error(w, "Unknown Proto Version", 502)
61+ return
62+ }
63+
64+ // tmp html
65+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
66+ fmt.Fprintf(w, "<!doctype html><meta charset=utf-8><title>parados</title>")
67+ fmt.Fprintf(w, "<h1>parados</h1><p>items: %d</p><ul>", len(lr.Items))
68+ for _, it := range lr.Items {
69+ fmt.Fprintf(w, `<li><a href="/item/%s">%s</a></li>`, it.ID, it.Path)
70+ }
71+ fmt.Fprintf(w, "</ul>")
72+}
73+
74 func main() {
75- print("Gorados")
76+ listen := flag.String("listen", "127.0.0.1:8808", "Listen Addr")
77+ par := flag.String("parados", "http://127.0.0.1:8088", "Parados Base URL")
78+ flag.Parse()
79+
80+ user := "admin"
81+ pass := "123"
82+
83+ h := &handler{
84+ parados: *par,
85+ user: user,
86+ pass: pass,
87+ httpc: &http.Client{Timeout: 15 * time.Second},
88+ }
89+
90+ // routes
91+ mux := http.NewServeMux()
92+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
93+ http.Redirect(w, r, "/library", http.StatusSeeOther)
94+ })
95+ mux.HandleFunc("/library", h.library)
96+
97+ // start server
98+ fmt.Fprintf(os.Stderr, "gorados: listening on %s\n", *listen)
99+ if err := http.ListenAndServe(*listen, mux); err != nil {
100+ fmt.Fprintln(os.Stderr, err)
101+ os.Exit(1)
102+ }
103 }
104+