github.com/rohankumardubey/aresdb@v0.0.2-0.20190517170215-e54e3ca06b9c/api/response.go (about)

     1  //  Copyright (c) 2017-2018 Uber Technologies, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package api
    16  
    17  import (
    18  	"encoding/json"
    19  	"net/http"
    20  
    21  	"github.com/uber/aresdb/utils"
    22  )
    23  
    24  // ErrorResponse represents error response.
    25  // swagger:response errorResponse
    26  type ErrorResponse struct {
    27  	//in: body
    28  	Body utils.APIError
    29  }
    30  
    31  // NoContentResponse represents Response with no content.
    32  // swagger:response noContentResponse
    33  type NoContentResponse struct{}
    34  
    35  // StringArrayResponse represents string array response.
    36  // swagger:response stringArrayResponse
    37  type StringArrayResponse struct {
    38  	//in: body
    39  	Body []string
    40  }
    41  
    42  // NewStringArrayResponse creates a StringArrayResponse.
    43  func NewStringArrayResponse() StringArrayResponse {
    44  	return StringArrayResponse{
    45  		Body: []string{},
    46  	}
    47  }
    48  
    49  // Respond responds with object with success status
    50  func Respond(w http.ResponseWriter, obj interface{}) {
    51  	RespondJSONObjectWithCode(w, http.StatusOK, obj)
    52  }
    53  
    54  // RespondJSONObjectWithCode with specified code and object.
    55  func RespondJSONObjectWithCode(w http.ResponseWriter, code int, obj interface{}) {
    56  	setCommonHeaders(w)
    57  	var err error
    58  	var jsonBytes []byte
    59  	if obj != nil {
    60  		jsonBytes, err = json.Marshal(obj)
    61  	}
    62  	writeJSONBytes(w, jsonBytes, err, code)
    63  }
    64  
    65  // RespondBytesWithCode with specified code and bytes.
    66  func RespondBytesWithCode(w http.ResponseWriter, code int, bs []byte) {
    67  	setCommonHeaders(w)
    68  	w.WriteHeader(code)
    69  	if bs != nil {
    70  		w.Write(bs)
    71  	}
    72  }
    73  
    74  // writeJSONBytes write jsonBytes to response if err is nil otherwise respond
    75  // with a ErrFailedToJSONMarshalResponseBody.
    76  func writeJSONBytes(w http.ResponseWriter, jsonBytes []byte, err error, code int) {
    77  	if err != nil {
    78  		RespondWithError(w, ErrFailedToJSONMarshalResponseBody)
    79  	}
    80  	w.Header().Set("Content-Type", "application/json")
    81  	w.WriteHeader(code)
    82  	if jsonBytes != nil {
    83  		w.Write(jsonBytes)
    84  	}
    85  }
    86  
    87  // RespondWithJSONBytes writes json bytes to response.
    88  func RespondWithJSONBytes(w http.ResponseWriter, jsonBytes []byte, err error) {
    89  	setCommonHeaders(w)
    90  	writeJSONBytes(w, jsonBytes, err, http.StatusOK)
    91  }
    92  
    93  // RespondWithJSONObject marshals the object into json bytes and write the bytes
    94  // into response.
    95  func RespondWithJSONObject(w http.ResponseWriter, jsonObj interface{}) {
    96  	RespondJSONObjectWithCode(w, http.StatusOK, jsonObj)
    97  }
    98  
    99  // setCommonHeaders writes no cache headers.
   100  func setCommonHeaders(w http.ResponseWriter) {
   101  	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
   102  	w.Header().Set("Pragma", "no-cache")
   103  	w.Header().Set("Expires", "0")
   104  }
   105  
   106  // RespondWithError responds with error.
   107  func RespondWithError(w http.ResponseWriter, err error) {
   108  	var errorResponse ErrorResponse
   109  	if e, ok := err.(utils.APIError); ok {
   110  		errorResponse = ErrorResponse{
   111  			Body: e,
   112  		}
   113  	} else {
   114  		errorResponse = ErrorResponse{
   115  			Body: utils.APIError{
   116  				Code:    http.StatusInternalServerError,
   117  				Message: err.Error(),
   118  			},
   119  		}
   120  	}
   121  	RespondJSONObjectWithCode(w, errorResponse.Body.Code, errorResponse.Body)
   122  }
   123  
   124  // RespondWithBadRequest responds with StatusBadRequest as code.
   125  func RespondWithBadRequest(w http.ResponseWriter, err error) {
   126  
   127  	if e, ok := err.(utils.APIError); ok {
   128  		e.Code = http.StatusBadRequest
   129  		RespondWithError(w, e)
   130  		return
   131  	}
   132  
   133  	RespondWithError(w, utils.APIError{
   134  		Code:  http.StatusBadRequest,
   135  		Cause: err,
   136  	})
   137  }