7 "github.com/gin-gonic/gin"
11 var MAIL_CONFIG MailConfig
13 type MailConfig struct {
15 SmtpAddress string `toml:"smtp_address"`
16 AddressFrom string `toml:"address_from"`
17 Login string `toml:"login"`
18 Password string `toml:"password"`
22 Domain string `toml:"domain"`
23 JwtSecret string `toml:"jwt_secret"`
24 PasswordResetSecret string `toml:"password_reset_secret"`
25 FreeSMSUser string `toml:"free_sms_user"`
26 FreeSMSPass string `toml:"free_sms_pass"`
29 func SetConfig(config Config) {
32 JWT_SECRET = []byte(config.JwtSecret)
33 PASSWORD_RESET_SECRET = []byte(config.PasswordResetSecret)
36 func SetMailConfig(config MailConfig) {
39 if config.Login != "" && config.AddressFrom != "" && config.Password != "" && config.SmtpAddress != "" {
40 MAIL_CONFIG.IsEnabled = true
41 ConfigureMailTemplateEngine()
51 func (e Error) Err() error {
59 func (e Error) Error() string {
67 func ErrorIs(err error, code ErrorCode) bool {
72 if apiError, ok := err.(*Error); !ok {
75 return apiError.Code == code
79 func NewInternalError(err error) *Error {
80 if apiError, ok := err.(*Error); ok {
83 return &Error{InternalError, "internal error", err}
86 func ToSnake(in string) string {
91 for i := 0; i < length; i++ {
92 if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
93 out = append(out, '_')
95 out = append(out, unicode.ToLower(runes[i]))
101 type Response struct {
102 StatusCode Status `json:"-"`
103 ErrorCode ErrorCode `json:"-"`
105 Status string `json:"status"`
106 Code string `json:"code,omitempty"`
107 Response interface{} `json:"response,omitempty"`
108 Message string `json:"message,omitempty"`
111 func (r Response) populateStatus() Response {
112 r.Status = ToSnake(r.StatusCode.String())
114 if r.ErrorCode != 0 {
115 r.Code = ToSnake(r.ErrorCode.String())
121 func ErrorResponse(code ErrorCode, message string) Response {
129 func SuccessResponse(data interface{}) Response {
136 func WriteJsonResponse(response Response, c *gin.Context) {
137 response = response.populateStatus()
139 c.JSON(StatusToHttpCode(response.StatusCode, response.ErrorCode), response)
142 func WriteBinary(contentType string, b []byte, c *gin.Context) {
143 c.Data(http.StatusOK, contentType, b)
146 type Middleware func(*gin.Context) *Error
148 func M(handler Middleware) gin.HandlerFunc {
149 return func(c *gin.Context) {
153 WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
162 type Query interface {
163 ValidateParams() *Error
164 Run() (interface{}, *Error)
167 func RunQuery(query Query, c *gin.Context) {
168 if err := query.ValidateParams(); err != nil {
169 WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
174 if out, err := query.Run(); err != nil {
175 WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
178 WriteJsonResponse(SuccessResponse(out), c)