http.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. package protocol
  2. import (
  3. "net/http"
  4. "github.com/opencost/opencost/core/pkg/log"
  5. "github.com/opencost/opencost/core/pkg/util/json"
  6. "google.golang.org/protobuf/encoding/protojson"
  7. "google.golang.org/protobuf/proto"
  8. )
  9. // HTTPProtocol is a struct used as a selector for request/response protocol utility methods
  10. type HTTPProtocol struct{}
  11. const internalServerErrorJSON = `{"code":500,"message":"Internal Server Error"}`
  12. // HTTPError represents an http error response
  13. type HTTPError struct {
  14. StatusCode int
  15. Body string
  16. }
  17. // Error returns the error string
  18. func (he HTTPError) Error() string {
  19. return string(he.Body)
  20. }
  21. // BadRequest creates a BadRequest HTTPError
  22. func (hp HTTPProtocol) BadRequest(message string) HTTPError {
  23. return HTTPError{
  24. StatusCode: http.StatusBadRequest,
  25. Body: message,
  26. }
  27. }
  28. // UnprocessableEntity creates an UnprocessableEntity HTTPError
  29. func (hp HTTPProtocol) UnprocessableEntity(message string) HTTPError {
  30. if message == "" {
  31. message = "Unprocessable Entity"
  32. }
  33. return HTTPError{
  34. StatusCode: http.StatusUnprocessableEntity,
  35. Body: message,
  36. }
  37. }
  38. // InternalServerError creates an InternalServerError HTTPError
  39. func (hp HTTPProtocol) InternalServerError(message string) HTTPError {
  40. if message == "" {
  41. message = "Internal Server Error"
  42. }
  43. return HTTPError{
  44. StatusCode: http.StatusInternalServerError,
  45. Body: message,
  46. }
  47. }
  48. func (hp HTTPProtocol) NotImplemented(message string) HTTPError {
  49. if message == "" {
  50. message = "Not Implemented"
  51. }
  52. return HTTPError{
  53. StatusCode: http.StatusNotImplemented,
  54. Body: message,
  55. }
  56. }
  57. func (hp HTTPProtocol) Forbidden(message string) HTTPError {
  58. if message == "" {
  59. message = "Forbidden"
  60. }
  61. return HTTPError{
  62. StatusCode: http.StatusForbidden,
  63. Body: message,
  64. }
  65. }
  66. // NotFound creates a NotFound HTTPError
  67. func (hp HTTPProtocol) NotFound() HTTPError {
  68. return HTTPError{
  69. StatusCode: http.StatusNotFound,
  70. Body: "Not Found",
  71. }
  72. }
  73. // HTTPResponse represents a data envelope for our HTTP messaging
  74. type HTTPResponse struct {
  75. Code int `json:"code"`
  76. Data interface{} `json:"data"`
  77. Message string `json:"message,omitempty"`
  78. Warning string `json:"warning,omitempty"`
  79. }
  80. // ToResponse accepts a data payload and/or error to encode into a new HTTPResponse instance. Responses
  81. // which should not contain an error should pass nil for err.
  82. func (hp HTTPProtocol) ToResponse(data interface{}, err error) *HTTPResponse {
  83. if err != nil {
  84. return &HTTPResponse{
  85. Code: http.StatusInternalServerError,
  86. Data: data,
  87. Message: err.Error(),
  88. }
  89. }
  90. return &HTTPResponse{
  91. Code: http.StatusOK,
  92. Data: data,
  93. }
  94. }
  95. func (hp HTTPProtocol) WriteRawOK(w http.ResponseWriter) {
  96. w.Header().Set("Content-Type", "application/json")
  97. w.Header().Set("Content-Length", "0")
  98. w.WriteHeader(http.StatusOK)
  99. }
  100. func (hp HTTPProtocol) WriteRawNoContent(w http.ResponseWriter) {
  101. w.Header().Set("Content-Type", "application/json")
  102. w.WriteHeader(http.StatusNoContent)
  103. }
  104. // WriteJSONData uses json content-type and json encoder with no data envelope allowing to remove
  105. // xss CWE as well as backwards compatibility to exisitng FE expectations
  106. func (hp HTTPProtocol) WriteJSONData(w http.ResponseWriter, data interface{}) {
  107. w.Header().Set("Content-Type", "application/json")
  108. if err := json.NewEncoder(w).Encode(data); err != nil {
  109. log.Error("Failed to encode JSON response: " + err.Error())
  110. w.WriteHeader(http.StatusInternalServerError)
  111. w.Write([]byte(internalServerErrorJSON))
  112. }
  113. }
  114. // WriteRawError uses json content-type and outputs raw error message for backwards compatibility to existing
  115. // frontend expectations.
  116. func (hp HTTPProtocol) WriteRawError(w http.ResponseWriter, httpStatusCode int, err string) {
  117. http.Error(w, err, httpStatusCode)
  118. }
  119. // WriteEncodedError writes an error response in the format of HTTPResponse
  120. func (hp HTTPProtocol) WriteEncodedError(w http.ResponseWriter, httpStatusCode int, errorResponse interface{}) {
  121. w.Header().Set("Content-Type", "application/json")
  122. w.WriteHeader(httpStatusCode)
  123. if err := json.NewEncoder(w).Encode(errorResponse); err != nil {
  124. log.Error("Failed to encode error response: " + err.Error())
  125. w.WriteHeader(http.StatusInternalServerError)
  126. w.Write([]byte(internalServerErrorJSON))
  127. }
  128. }
  129. // WriteData wraps the data payload in an HTTPResponse and writes the resulting response using the
  130. // http.ResponseWriter
  131. func (hp HTTPProtocol) WriteData(w http.ResponseWriter, data interface{}) {
  132. w.Header().Set("Content-Type", "application/json")
  133. status := http.StatusOK
  134. w.WriteHeader(status)
  135. resp := &HTTPResponse{
  136. Code: status,
  137. Data: data,
  138. }
  139. if err := json.NewEncoder(w).Encode(resp); err != nil {
  140. log.Error("Failed to encode response: " + err.Error())
  141. w.WriteHeader(http.StatusInternalServerError)
  142. w.Write([]byte(internalServerErrorJSON))
  143. }
  144. }
  145. // WriteDataWithWarning writes the data payload similiar to WriteData except it provides an additional warning message.
  146. func (hp HTTPProtocol) WriteDataWithWarning(w http.ResponseWriter, data interface{}, warning string) {
  147. w.Header().Set("Content-Type", "application/json")
  148. status := http.StatusOK
  149. resp := &HTTPResponse{
  150. Code: status,
  151. Data: data,
  152. Warning: warning,
  153. }
  154. w.WriteHeader(status)
  155. if err := json.NewEncoder(w).Encode(resp); err != nil {
  156. log.Error("Failed to encode response with warning: " + err.Error())
  157. w.WriteHeader(http.StatusInternalServerError)
  158. w.Write([]byte(internalServerErrorJSON))
  159. }
  160. }
  161. // WriteDataWithMessage writes the data payload similiar to WriteData except it provides an additional string message.
  162. func (hp HTTPProtocol) WriteDataWithMessage(w http.ResponseWriter, data interface{}, message string) {
  163. w.Header().Set("Content-Type", "application/json")
  164. status := http.StatusOK
  165. resp := &HTTPResponse{
  166. Code: status,
  167. Data: data,
  168. Message: message,
  169. }
  170. w.WriteHeader(status)
  171. if err := json.NewEncoder(w).Encode(resp); err != nil {
  172. log.Error("Failed to encode response with message: " + err.Error())
  173. w.WriteHeader(http.StatusInternalServerError)
  174. w.Write([]byte(internalServerErrorJSON))
  175. }
  176. }
  177. // WriteProtoWithMessage uses the protojson package to convert proto3 response to json response and
  178. // return it to the requester. Proto3 drops messages with default values but overriding the param
  179. // EmitUnpopulated to true it returns default values in the Json response payload. If error is
  180. // encountered it sent InternalServerError and the error why the json conversion failed.
  181. func (hp HTTPProtocol) WriteProtoWithMessage(w http.ResponseWriter, data proto.Message) {
  182. w.Header().Set("Content-Type", "application/json")
  183. m := protojson.MarshalOptions{
  184. EmitUnpopulated: true,
  185. }
  186. status := http.StatusOK
  187. w.WriteHeader(status)
  188. b, err := m.Marshal(data)
  189. if err != nil {
  190. hp.WriteError(w, hp.InternalServerError(err.Error()))
  191. log.Error("Failed to marshal proto to json: " + err.Error())
  192. return
  193. }
  194. w.Write(b)
  195. }
  196. // WriteDataWithMessageAndWarning writes the data payload similiar to WriteData except it provides a warning and additional message string.
  197. func (hp HTTPProtocol) WriteDataWithMessageAndWarning(w http.ResponseWriter, data interface{}, message string, warning string) {
  198. w.Header().Set("Content-Type", "application/json")
  199. status := http.StatusOK
  200. resp := &HTTPResponse{
  201. Code: status,
  202. Data: data,
  203. Message: message,
  204. Warning: warning,
  205. }
  206. w.WriteHeader(status)
  207. if err := json.NewEncoder(w).Encode(resp); err != nil {
  208. log.Error("Failed to encode response with message and warning: " + err.Error())
  209. w.WriteHeader(http.StatusInternalServerError)
  210. w.Write([]byte(internalServerErrorJSON))
  211. }
  212. }
  213. // WriteError wraps the HTTPError in a HTTPResponse and writes it via http.ResponseWriter
  214. func (hp HTTPProtocol) WriteError(w http.ResponseWriter, err HTTPError) {
  215. w.Header().Set("Content-Type", "application/json")
  216. status := err.StatusCode
  217. if status == 0 {
  218. status = http.StatusInternalServerError
  219. }
  220. w.WriteHeader(status)
  221. resp := &HTTPResponse{
  222. Code: status,
  223. Message: err.Body,
  224. }
  225. if err := json.NewEncoder(w).Encode(resp); err != nil {
  226. log.Error("Failed to encode error response: " + err.Error())
  227. w.WriteHeader(http.StatusInternalServerError)
  228. w.Write([]byte(internalServerErrorJSON))
  229. }
  230. }
  231. // WriteResponse writes the provided HTTPResponse instance via http.ResponseWriter
  232. func (hp HTTPProtocol) WriteResponse(w http.ResponseWriter, r *HTTPResponse) {
  233. w.Header().Set("Content-Type", "application/json")
  234. status := r.Code
  235. w.WriteHeader(status)
  236. if err := json.NewEncoder(w).Encode(r); err != nil {
  237. log.Error("Failed to encode response: " + err.Error())
  238. w.WriteHeader(http.StatusInternalServerError)
  239. w.Write([]byte(internalServerErrorJSON))
  240. }
  241. }