-
Notifications
You must be signed in to change notification settings - Fork 0
/
blueberry.go
113 lines (88 loc) · 2.09 KB
/
blueberry.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"github.com/literatesnow/scgi"
"github.com/literatesnow/xmlrpc"
"github.com/julienschmidt/httprouter"
"encoding/json"
"errors"
"log"
"net/http"
"os"
)
type rtorrent struct {
scgi *scgi.Client
rtNetwork string
rtAddress string
httpAddress string
}
var rt rtorrent
func main() {
rt = rtorrent{}
if err := readConfig(); err != nil {
log.Fatalf("Fatal error: %s\n", err)
return
}
log.Printf("rtorrent: %s@%s, http: %s\n",
rt.rtNetwork,
rt.rtAddress,
rt.httpAddress)
rt.scgi = scgi.NewClient(rt.rtNetwork, rt.rtAddress)
router := httprouter.New()
router.POST("/rtorrent/request", rtRequest)
router.ServeFiles("/public/*filepath", http.Dir("./www/public"))
log.Fatal(http.ListenAndServe(rt.httpAddress, router))
}
func rtRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
methodName, params, err := xmlrpc.ParseJsonRequest(r.Body)
if err != nil {
fatalErrorResponse(w, 0, err)
return
}
doc := xmlrpc.CreateRequest(methodName, params)
response, err := rt.scgi.Request(doc)
if err != nil {
fatalErrorResponse(w, http.StatusBadGateway, err)
return
}
value, err := xmlrpc.ParseResponse(response)
if err != nil {
fatalErrorResponse(w, 0, err)
}
buf, err := json.Marshal(value)
if err != nil {
fatalErrorResponse(w, 0, err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(buf)
}
func fatalErrorResponse(w http.ResponseWriter, code int, err error) {
w.Header().Set("Content-Type", "text/plain")
if code == 0 {
code = http.StatusInternalServerError
}
w.WriteHeader(code)
if err != nil {
log.Printf("Error: %s\n", err.Error())
w.Write([]byte(err.Error()))
}
}
func readConfig() (err error) {
var str string
str = os.Getenv("RTORRENT_NETWORK")
if str == "" {
return errors.New("Missing value for RTORRENT_NETWORK")
}
rt.rtNetwork = str
str = os.Getenv("RTORRENT_ADDRESS")
if str == "" {
return errors.New("Missing value for RTORRENT_ADDRESS")
}
rt.rtAddress = str
str = os.Getenv("HTTP_ADDRESS")
if str == "" {
str = "localhost:8080"
}
rt.httpAddress = str
return nil
}