@@ -2,9 +2,7 @@ package server
22
33import (
44 "context"
5- "encoding/json"
65 "errors"
7- "fmt"
86 "log"
97 "net/http"
108 "server/internal/middleware"
@@ -28,17 +26,6 @@ type HandlerMux struct {
2826 rateLimiter func (http.ResponseWriter , * http.Request , http.Handler )
2927}
3028
31- type HTTPResponse struct {
32- Data interface {} `json:"data"`
33- }
34-
35- type HTTPErrorResponse struct {
36- Error interface {} `json:"error"`
37- }
38-
39- func errorResponse (response string ) string {
40- return fmt .Sprintf ("{\" error\" : %q}" , response )
41- }
4229
4330func (cim * HandlerMux ) ServeHTTP (w http.ResponseWriter , r * http.Request ) {
4431 // Convert the path to lowercase before passing to the underlying mux.
@@ -91,43 +78,25 @@ func (s *HTTPServer) Shutdown() error {
9178}
9279
9380func (s * HTTPServer ) HealthCheck (w http.ResponseWriter , request * http.Request ) {
94- util .JSONResponse (w , http .StatusOK , map [string ]string {"message" : "Server is running" })
81+ util .HttpResponseJSON (w , http .StatusOK , map [string ]string {"message" : "Server is running" })
9582}
9683
9784func (s * HTTPServer ) CliHandler (w http.ResponseWriter , r * http.Request ) {
9885 diceCmd , err := util .ParseHTTPRequest (r )
9986 if err != nil {
100- http . Error (w , "Error parsing HTTP request" , http . StatusBadRequest )
87+ util . HttpResponseException (w ,http . StatusBadRequest , "Error parsing HTTP request" );
10188 return
10289 }
10390
10491 resp , err := s .DiceClient .ExecuteCommand (diceCmd )
10592 if err != nil {
106- http .Error (w , errorResponse (err .Error ()), http .StatusBadRequest )
107- return
108- }
109-
110- if _ , ok := resp .(string ); ! ok {
111- log .Println ("Error marshaling response" , "error" , err )
112- http .Error (w , errorResponse ("Internal Server Error" ), http .StatusInternalServerError )
93+ util .HttpResponseException (w ,http .StatusBadRequest ,err );
11394 return
11495 }
11596
116- httpResponse := HTTPResponse {Data : resp .(string )}
117- responseJSON , err := json .Marshal (httpResponse )
118- if err != nil {
119- log .Println ("Error marshaling response" , "error" , err )
120- http .Error (w , errorResponse ("Internal Server Error" ), http .StatusInternalServerError )
121- return
122- }
123-
124- _ , err = w .Write (responseJSON )
125- if err != nil {
126- http .Error (w , errorResponse ("Internal Server Error" ), http .StatusInternalServerError )
127- return
128- }
97+ util .HttpResponseJSON (w , http .StatusOK , resp )
12998}
13099
131100func (s * HTTPServer ) SearchHandler (w http.ResponseWriter , request * http.Request ) {
132- util .JSONResponse (w , http .StatusOK , map [string ]string {"message" : "Search results" })
101+ util .HttpResponseJSON (w ,http .StatusOK ,map [string ]string {"message" : "Search results" });
133102}
0 commit comments