init
This commit is contained in:
60
internal/server/response/response.go
Normal file
60
internal/server/response/response.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/goccy/go-json"
|
||||
"madsky.ru/go-tracker/internal/model/user"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Response struct {
|
||||
Status string `json:"status"`
|
||||
Message *string `json:"message"`
|
||||
Data interface{} `json:"data"`
|
||||
}
|
||||
|
||||
const (
|
||||
StatusOK = "Success"
|
||||
StatusError = "Error"
|
||||
)
|
||||
|
||||
func WriteJSON(w http.ResponseWriter, message *string, code int, data interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
|
||||
statusText := StatusOK
|
||||
if code >= 400 {
|
||||
statusText = StatusError
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(&Response{
|
||||
Status: statusText,
|
||||
Message: message,
|
||||
Data: data,
|
||||
}); err != nil {
|
||||
http.Error(w, "unknown error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
type CustomError struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *CustomError) Error() string {
|
||||
return fmt.Sprintf("custom error: %s", e.Message)
|
||||
}
|
||||
|
||||
func Error(w http.ResponseWriter, err error, code int) {
|
||||
errorMessage := err.Error()
|
||||
WriteJSON(w, &errorMessage, code, nil)
|
||||
}
|
||||
|
||||
func ToUserResponseDto(u *user.User) *user.ResponseDTO {
|
||||
var ur user.ResponseDTO
|
||||
ur.ID = u.ID
|
||||
ur.Email = u.Email
|
||||
ur.Role = u.Role
|
||||
ur.Name = u.Name
|
||||
|
||||
return &ur
|
||||
}
|
||||
Reference in New Issue
Block a user