vitess.io/vitess@v0.16.2/go/vt/vtadmin/http/response.go (about)

     1  /*
     2  Copyright 2020 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package http
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"net/http"
    23  
    24  	"vitess.io/vitess/go/vt/vtadmin/errors"
    25  )
    26  
    27  // JSONResponse represents a generic response object.
    28  type JSONResponse struct {
    29  	Result     any        `json:"result,omitempty"`
    30  	Error      *errorBody `json:"error,omitempty"`
    31  	Ok         bool       `json:"ok"`
    32  	httpStatus int
    33  }
    34  
    35  type errorBody struct {
    36  	Message string `json:"message"`
    37  	Code    string `json:"code"`
    38  	Details any    `json:"details,omitempty"`
    39  }
    40  
    41  // NewJSONResponse returns a JSONResponse for the given result and error. If err
    42  // is non-nil, and implements errors.TypedError, the HTTP status code and
    43  // message are provided by the error. If not, the code and message fallback to
    44  // 500 unknown.
    45  func NewJSONResponse(value any, err error) *JSONResponse {
    46  	if err != nil {
    47  		switch e := err.(type) {
    48  		case errors.TypedError:
    49  			return typedErrorJSONResponse(e)
    50  		default:
    51  			return typedErrorJSONResponse(&errors.Unknown{Err: e})
    52  		}
    53  	}
    54  
    55  	return &JSONResponse{
    56  		Result:     value,
    57  		Error:      nil,
    58  		Ok:         true,
    59  		httpStatus: 200,
    60  	}
    61  }
    62  
    63  // WithHTTPStatus forces a response to be used for the JSONResponse.
    64  func (r *JSONResponse) WithHTTPStatus(code int) *JSONResponse {
    65  	r.httpStatus = code
    66  	return r
    67  }
    68  
    69  func typedErrorJSONResponse(v errors.TypedError) *JSONResponse {
    70  	return &JSONResponse{
    71  		Error: &errorBody{
    72  			Message: v.Error(),
    73  			Details: v.Details(),
    74  			Code:    v.Code(),
    75  		},
    76  		Ok:         false,
    77  		httpStatus: v.HTTPStatus(),
    78  	}
    79  }
    80  
    81  // Write marshals a JSONResponse into the http response.
    82  func (r *JSONResponse) Write(w http.ResponseWriter) {
    83  	b, err := json.Marshal(r)
    84  	if err != nil {
    85  		w.WriteHeader(500)
    86  		// A bit clunky but if we already failed to marshal JSON, let's do it by hand.
    87  		msgFmt := `{"error": {"code": "unknown_error", "message": %q}}`
    88  		fmt.Fprintf(w, msgFmt, err.Error())
    89  
    90  		return
    91  	}
    92  
    93  	if r.httpStatus != 200 {
    94  		w.WriteHeader(r.httpStatus)
    95  	}
    96  
    97  	fmt.Fprintf(w, "%s", b)
    98  }