Skip to content

Commit 519e1d8

Browse files
committed
Move writing data to response as JSON to a method.
1 parent c22e6de commit 519e1d8

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

internal/server/server.go

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@
1818
package server
1919

2020
import (
21+
"bytes"
2122
"encoding/json"
2223
"github.com/rightmesh/awdb/pkg/adb"
24+
"io"
2325
"log"
2426
"net/http"
2527
)
@@ -46,10 +48,7 @@ func devicesHandler(response http.ResponseWriter, request *http.Request) {
4648
return
4749
}
4850

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)
5352
}
5453
}
5554

@@ -72,6 +71,25 @@ func proxyAdbRun(response http.ResponseWriter, adbRun *adb.Run) (err error) {
7271
return err
7372
}
7473

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+
7593
// Start sets up the HTTP routes and serves the service, crashing if any errors are encountered.
7694
func Start() {
7795
http.HandleFunc("/help/", helpHandler)

0 commit comments

Comments
 (0)