7 "github.com/gin-gonic/gin"
13 JwtSecret string `toml:"jwt_secret"`
14 PasswordResetSecret string `toml:"password_reset_secret"`
15 FreeSMSUser string `toml:"free_sms_user"`
16 FreeSMSPass string `toml:"free_sms_pass"`
19 func SetConfig(config Config) {
22 JWT_SECRET = []byte(config.JwtSecret)
23 PASSWORD_RESET_SECRET = []byte(config.PasswordResetSecret)
32 func (e Error) Err() error {
40 func (e Error) Error() string {
48 func ErrorIs(err error, code ErrorCode) bool {
53 if apiError, ok := err.(*Error); !ok {
56 return apiError.Code == code
60 func NewInternalError(err error) *Error {
61 return &Error{InternalError, "internal error", err}
64 func ToSnake(in string) string {
69 for i := 0; i < length; i++ {
70 if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
71 out = append(out, '_')
73 out = append(out, unicode.ToLower(runes[i]))
79 type Response struct {
80 StatusCode Status `json:"-"`
81 ErrorCode ErrorCode `json:"-"`
83 Status string `json:"status"`
84 Code string `json:"code,omitempty"`
85 Response interface{} `json:"response,omitempty"`
86 Message string `json:"message,omitempty"`
89 func (r Response) populateStatus() Response {
90 r.Status = ToSnake(r.StatusCode.String())
93 r.Code = ToSnake(r.ErrorCode.String())
99 func ErrorResponse(code ErrorCode, message string) Response {
107 func SuccessResponse(data interface{}) Response {
114 func WriteJsonResponse(response Response, c *gin.Context) {
115 response = response.populateStatus()
117 c.JSON(StatusToHttpCode(response.StatusCode, response.ErrorCode), response)
120 func WriteBinary(contentType string, b []byte, c *gin.Context) {
121 c.Data(http.StatusOK, contentType, b)
124 type Middleware func(*gin.Context) *Error
126 func M(handler Middleware) gin.HandlerFunc {
127 return func(c *gin.Context) {
131 WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
140 type Query interface {
141 ValidateParams() *Error
142 Run() (interface{}, *Error)
145 func RunQuery(query Query, c *gin.Context) {
146 if err := query.ValidateParams(); err != nil {
147 WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
152 if out, err := query.Run(); err != nil {
153 WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
156 WriteJsonResponse(SuccessResponse(out), c)