github.com/pavlo67/common@v0.5.3/common/server_http/response_rest.go (about)

     1  package server_http
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  
     8  	"github.com/pavlo67/common/common"
     9  	"github.com/pavlo67/common/common/errors"
    10  )
    11  
    12  const (
    13  	CORSAllowHeaders     = "authorization,content-type"
    14  	CORSAllowMethods     = "HEAD,GET,POST,PUT,DELETE,OPTIONS"
    15  	CORSAllowOrigin      = "*"
    16  	CORSAllowCredentials = "true"
    17  )
    18  
    19  // REST -------------------------------------------------------------------------------------
    20  
    21  type RESTDataMessage struct {
    22  	Info     string `json:"info,omitempty"`
    23  	Redirect string `json:"redirect,omitempty"`
    24  }
    25  
    26  // Redirect ----------------------------------------------------------------------------------
    27  
    28  func Redirect(w http.ResponseWriter, req *http.Request) {
    29  	// remove/add not default ports from req.Host
    30  	target := "https://" + req.Host + req.URL.Path
    31  	if len(req.URL.RawQuery) > 0 {
    32  		target += "?" + req.URL.RawQuery
    33  	}
    34  	http.Redirect(w, req, target, http.StatusTemporaryRedirect)
    35  }
    36  
    37  func ResponseRESTError(status int, err error, req *http.Request) (Response, error) {
    38  	commonErr := errors.CommonError(err)
    39  
    40  	key := commonErr.Key()
    41  	data := common.Map{ErrorKey: key}
    42  
    43  	if status == 0 || status == http.StatusOK {
    44  		if key == common.NoCredsKey || key == common.InvalidCredsKey {
    45  			status = http.StatusUnauthorized
    46  		} else if key == common.NoUserKey || key == common.NoRightsKey {
    47  			status = http.StatusForbidden
    48  		} else if status == 0 || status == http.StatusOK {
    49  			status = http.StatusInternalServerError
    50  
    51  		} else {
    52  			status = http.StatusInternalServerError
    53  		}
    54  	}
    55  
    56  	//if !strlib.In(s.secretENVsToLower, strings.ToLower(os.Getenv("ENV"))) {
    57  	//	data["details"] = commonErr.Error()
    58  	//}
    59  
    60  	jsonBytes, errJSON := json.Marshal(data)
    61  	if errJSON != nil {
    62  		commonErr = commonErr.Append(fmt.Errorf("marshalling error data (%#v): %s", data, errJSON))
    63  	}
    64  
    65  	if req != nil {
    66  		commonErr = commonErr.Append(fmt.Errorf("on %s %s", req.Method, req.URL))
    67  	}
    68  
    69  	return Response{Status: status, Data: jsonBytes}, commonErr
    70  }
    71  
    72  func ResponseRESTOk(status int, data interface{}, req *http.Request) (Response, error) {
    73  	if status == 0 {
    74  		status = http.StatusOK
    75  	}
    76  
    77  	if data == nil {
    78  		return Response{Status: status}, nil
    79  	}
    80  
    81  	var dataBytes []byte
    82  
    83  	switch v := data.(type) {
    84  	case []byte:
    85  		dataBytes = v
    86  	case *[]byte:
    87  		if v != nil {
    88  			dataBytes = *v
    89  		}
    90  	case string:
    91  		dataBytes = []byte(v)
    92  	case *string:
    93  		if v != nil {
    94  			dataBytes = []byte(*v)
    95  		}
    96  	default:
    97  		var err error
    98  		if dataBytes, err = json.Marshal(data); err != nil {
    99  			if req != nil {
   100  				err = fmt.Errorf("on %s %s: can't marshal json (%#v), got %s", req.Method, req.URL, data, err)
   101  			} else {
   102  				err = fmt.Errorf("can't marshal json (%#v): %s", data, err)
   103  			}
   104  
   105  			return Response{Status: http.StatusInternalServerError}, err
   106  		}
   107  	}
   108  
   109  	return Response{Status: status, Data: dataBytes}, nil
   110  }