18
18
package server
19
19
20
20
import (
21
+ "bytes"
21
22
"encoding/json"
22
23
"github.com/rightmesh/awdb/pkg/adb"
24
+ "io"
23
25
"log"
24
26
"net/http"
25
27
)
@@ -46,10 +48,7 @@ func devicesHandler(response http.ResponseWriter, request *http.Request) {
46
48
return
47
49
}
48
50
49
- encoder := json .NewEncoder (response )
50
- if err := encoder .Encode (deviceList ); err != nil {
51
- // TODO: Wrap marshall calls in another method that can account for these errors.
52
- }
51
+ writeResponseAsJSON (response , deviceList )
53
52
}
54
53
}
55
54
@@ -72,6 +71,25 @@ func proxyAdbRun(response http.ResponseWriter, adbRun *adb.Run) (err error) {
72
71
return err
73
72
}
74
73
74
+ // writeResponseAsJSON attempts to marshal the provided data to JSON, writing it to the provided
75
+ // response with an HTTP 200 code if successful, or writing a 502 to the provided response if not.
76
+ func writeResponseAsJSON (response http.ResponseWriter , data interface {}) error {
77
+ temp := new (bytes.Buffer )
78
+
79
+ encoder := json .NewEncoder (temp )
80
+ err := encoder .Encode (data )
81
+ if err != nil {
82
+ response .Header ().Set ("Content-Type" , "text/plain; charset=utf-8" )
83
+ response .WriteHeader (http .StatusBadGateway )
84
+ return err
85
+ }
86
+
87
+ response .Header ().Set ("Content-Type" , "application/json; charset=utf-8" )
88
+ response .WriteHeader (http .StatusOK )
89
+ io .Copy (response , temp )
90
+ return nil
91
+ }
92
+
75
93
// Start sets up the HTTP routes and serves the service, crashing if any errors are encountered.
76
94
func Start () {
77
95
http .HandleFunc ("/help/" , helpHandler )
0 commit comments