github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/tequilapi/utils/utils.go (about)

     1  /*
     2   * Copyright (C) 2017 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package utils
    19  
    20  import (
    21  	"encoding/json"
    22  	"errors"
    23  	"fmt"
    24  	"net/http"
    25  
    26  	"github.com/gin-gonic/gin"
    27  	"github.com/mysteriumnetwork/go-rest/apierror"
    28  	"github.com/rs/zerolog/log"
    29  )
    30  
    31  // WriteAsJSON writes a given value `v` to a given http.ResponseWritter
    32  // forcing `content-type application/json`. Optional httpCode parameter
    33  // can be given to also write a specific status code.
    34  func WriteAsJSON(v interface{}, writer http.ResponseWriter, httpCode ...int) {
    35  	writer.Header().Set("Content-type", "application/json; charset=utf-8")
    36  
    37  	blob, err := json.Marshal(v)
    38  	if err != nil {
    39  		http.Error(writer, "Http response write error", http.StatusInternalServerError)
    40  		return
    41  	}
    42  
    43  	if len(httpCode) > 0 {
    44  		writer.WriteHeader(httpCode[0])
    45  	}
    46  
    47  	if _, err := writer.Write(blob); err != nil {
    48  		log.Error().Err(err).Msg("Writing response body failed")
    49  	}
    50  }
    51  
    52  // swagger:model APIError
    53  type apiErrorSwagger struct {
    54  	apierror.APIError
    55  }
    56  
    57  // ForwardError writes err to the response if it's in `apierror.APIError` format.
    58  // Otherwise, appends it to the fallback APIError's message.
    59  func ForwardError(c *gin.Context, err error, fallback *apierror.APIError) {
    60  	var apiErr *apierror.APIError
    61  	if errors.As(err, &apiErr) {
    62  		c.Error(err)
    63  	} else {
    64  		fallback.Err.Message = fallback.Err.Message + ": " + fmt.Errorf("%w", err).Error()
    65  		c.Error(fallback)
    66  	}
    67  }