github.com/erda-project/erda-infra@v1.0.9/providers/legacy/httpendpoints/response.go (about)

     1  // Copyright (c) 2021 Terminus, 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 httpendpoints
    16  
    17  import (
    18  	"encoding/json"
    19  	"net/http"
    20  
    21  	"github.com/erda-project/erda-infra/providers/legacy/httpendpoints/i18n"
    22  	"github.com/erda-project/erda-infra/providers/legacy/httpendpoints/ierror"
    23  	"github.com/sirupsen/logrus"
    24  )
    25  
    26  // HTTPResponse is a struct contains status code and content body
    27  type HTTPResponse struct {
    28  	Error   ierror.IAPIError
    29  	Status  int
    30  	Content interface{}
    31  }
    32  
    33  // GetStatus returns http status code.
    34  func (r HTTPResponse) GetStatus() int {
    35  	return r.Status
    36  }
    37  
    38  // GetContent returns http content body
    39  func (r HTTPResponse) GetContent() interface{} {
    40  	return r.Content
    41  }
    42  
    43  // GetLocaledResp .
    44  func (r HTTPResponse) GetLocaledResp(locale i18n.LocaleResource) HTTPResponse {
    45  	if r.Error != nil {
    46  		return HTTPResponse{
    47  			Status: r.Status,
    48  			Content: Resp{
    49  				Success: false,
    50  				Err: ErrorResponse{
    51  					Code: r.Error.Code(),
    52  					Msg:  r.Error.Render(locale),
    53  				},
    54  			},
    55  		}
    56  	}
    57  	return r
    58  }
    59  
    60  // Resp .
    61  type Resp struct {
    62  	Success bool          `json:"success"`
    63  	Data    interface{}   `json:"data,omitempty"`
    64  	Err     ErrorResponse `json:"err,omitempty"`
    65  	UserIDs []string      `json:"userIDs,omitempty"`
    66  }
    67  
    68  // ErrResp .
    69  func ErrResp(statusCode int, code, errMsg string) (Responser, error) {
    70  	return HTTPResponse{
    71  		Status: statusCode,
    72  		Content: Resp{
    73  			Success: false,
    74  			Err: ErrorResponse{
    75  				Code: code,
    76  				Msg:  errMsg,
    77  			},
    78  		},
    79  	}, nil
    80  }
    81  
    82  // OkResp 采用httpserver框架时正常返回结果封装
    83  // 在 `userIDs` 中设置需要由 openapi 注入的用户信息的 ID 列表
    84  func OkResp(data interface{}, userIDs ...[]string) (Responser, error) {
    85  	content := Resp{
    86  		Success: true,
    87  		Data:    data,
    88  	}
    89  	if len(userIDs) > 0 {
    90  		content.UserIDs = dedupSlice(userIDs[0], true)
    91  	}
    92  	return HTTPResponse{
    93  		Status:  http.StatusOK,
    94  		Content: content,
    95  	}, nil
    96  }
    97  
    98  func dedupSlice(ss []string, omitEmptyOpt ...bool) []string {
    99  	var omitEmpty bool
   100  	if len(omitEmptyOpt) > 0 && omitEmptyOpt[0] {
   101  		omitEmpty = true
   102  	}
   103  	result := make([]string, 0, len(ss))
   104  	m := make(map[string]struct{}, len(ss))
   105  	for _, s := range ss {
   106  		if s == "" && omitEmpty {
   107  			continue
   108  		}
   109  		if _, ok := m[s]; ok {
   110  			continue
   111  		}
   112  		result = append(result, s)
   113  		m[s] = struct{}{}
   114  	}
   115  	return result
   116  }
   117  
   118  // WriteYAML .
   119  func WriteYAML(w http.ResponseWriter, v string) {
   120  	w.Header().Set("Content-Type", "application/x-yaml; charset=utf-8")
   121  	w.WriteHeader(http.StatusOK)
   122  	_, err := w.Write([]byte(v))
   123  	if err != nil {
   124  		logrus.Debugln(err)
   125  	}
   126  }
   127  
   128  // WriteJSON .
   129  func WriteJSON(w http.ResponseWriter, v interface{}) {
   130  	w.Header().Set("Content-Type", ContentTypeJSON)
   131  	w.WriteHeader(http.StatusOK)
   132  	b, err := json.Marshal(v)
   133  	if err != nil {
   134  		logrus.Debugln(err)
   135  	}
   136  	_, err = w.Write(b)
   137  	if err != nil {
   138  		logrus.Debugln(err)
   139  	}
   140  }
   141  
   142  // WriteData .
   143  func WriteData(w http.ResponseWriter, v interface{}) {
   144  	WriteJSON(w, Resp{
   145  		Success: true,
   146  		Data:    v,
   147  	})
   148  }
   149  
   150  // WriteErr .
   151  func WriteErr(w http.ResponseWriter, code, errMsg string) {
   152  	WriteJSON(w, Resp{
   153  		Success: false,
   154  		Err: ErrorResponse{
   155  			Code: code,
   156  			Msg:  errMsg,
   157  		},
   158  	})
   159  }
   160  
   161  // ErrorResponse .
   162  type ErrorResponse struct {
   163  	Code string      `json:"code"`
   164  	Msg  string      `json:"msg"`
   165  	Ctx  interface{} `json:"ctx"`
   166  }