-
Notifications
You must be signed in to change notification settings - Fork 1
/
root.go
82 lines (68 loc) · 2.21 KB
/
root.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
package api
import (
"encoding/json"
"fmt"
"github.com/danesparza/fxaudio/internal/data"
"github.com/danesparza/fxaudio/internal/media"
"github.com/danesparza/fxaudio/version"
"net/http"
"time"
)
// Service encapsulates API service operations
type Service struct {
DB *data.Manager
StartTime time.Time
HistoryTTL time.Duration
// PlayMedia signals a file should be played
PlayMedia chan media.PlayAudioRequest
// StopMedia signals a file should stop playing
StopMedia chan string
// StopAllMedia signals all audio should stop playing
StopAllMedia chan bool
}
// PlayAudioRequest represents a request to play an audio endpoint
type PlayAudioRequest struct {
Endpoint string `json:"endpoint"`
}
// SystemResponse is a response for a system request
type SystemResponse struct {
Message string `json:"message"`
Data interface{} `json:"data"`
}
// ErrorResponse represents an API response
type ErrorResponse struct {
Message string `json:"message"`
}
// Used to send back an error:
func sendErrorResponse(rw http.ResponseWriter, err error, code int) {
// Our return value
response := ErrorResponse{
Message: "Error: " + err.Error()}
// Serialize to JSON & return the response:
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
rw.WriteHeader(code)
json.NewEncoder(rw).Encode(response)
}
// ShowUI redirects to the /ui/ url path
func ShowUI(rw http.ResponseWriter, req *http.Request) {
// http.Redirect(rw, req, "/ui/", 301)
fmt.Fprintf(rw, "Hello, world - UI")
}
// GetIP gets a requests IP address by reading off the forwarded-for
// header (for proxies) and falls back to use the remote address.
func GetIP(r *http.Request) string {
forwarded := r.Header.Get("X-FORWARDED-FOR")
if forwarded != "" {
return forwarded
}
return r.RemoteAddr
}
// ApiVersionMiddleware adds the API version information to the response header
func ApiVersionMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// Include the version in the response headers:
rw.Header().Set(version.Header, version.String())
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(rw, r)
})
}