init
This commit is contained in:
44
subsonic/http.go
Normal file
44
subsonic/http.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package subsonic
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func sendJSON(w http.ResponseWriter, data any, status int) error {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
return json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func sendXML(w http.ResponseWriter, data any, status int) error {
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
w.WriteHeader(status)
|
||||
return xml.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func SendHTTPResponse(w http.ResponseWriter, r *http.Request, data any, status int) error {
|
||||
format := r.URL.Query().Get("f")
|
||||
if format == "" {
|
||||
format = "json"
|
||||
}
|
||||
|
||||
resp := struct {
|
||||
SubsonicResponse any `xml:"subsonic-response" json:"subsonic-response"`
|
||||
}{
|
||||
SubsonicResponse: data,
|
||||
}
|
||||
|
||||
switch format {
|
||||
case "xml":
|
||||
return sendXML(w, data, status)
|
||||
case "json":
|
||||
return sendJSON(w, resp, status)
|
||||
case "jsonp":
|
||||
return sendJSON(w, resp, status)
|
||||
}
|
||||
|
||||
return fmt.Errorf("invalid format")
|
||||
}
|
||||
Reference in New Issue
Block a user