github.com/mundipagg/boleto-api@v0.0.0-20230620145841-3f9ec742599f/models/result.go (about) 1 package models 2 3 import ( 4 "regexp" 5 6 "github.com/gin-gonic/gin" 7 ) 8 9 //GetBoletoResult Centraliza as informações da operação GetBoleto 10 type GetBoletoResult struct { 11 Id string 12 Format string 13 PublicKey string 14 URI string 15 BoletoSource string 16 TotalElapsedTimeInMilliseconds int64 17 CacheElapsedTimeInMilliseconds int64 18 DatabaseElapsedTimeInMilliseconds int64 19 ErrorResponse BoletoResponse 20 LogSeverity string 21 } 22 23 func NewGetBoletoResult(c *gin.Context) *GetBoletoResult { 24 g := new(GetBoletoResult) 25 g.Id = c.Query("id") 26 g.Format = c.Query("fmt") 27 g.PublicKey = c.Query("pk") 28 g.URI = c.Request.RequestURI 29 g.BoletoSource = "none" 30 return g 31 } 32 33 //HasValidPublicKey Verifica se a chave pública para buscar um boleto está presente e se é um hexadecimal 34 func HasValidPublicKey(g *GetBoletoResult) bool { 35 return g.PublicKey != "" && isValidHex(g.PublicKey) 36 } 37 38 func HasValidId(g *GetBoletoResult) bool { 39 return g.Id != "" && isValidHex(g.Id) 40 } 41 42 func (g *GetBoletoResult) HasValidParameters() bool { 43 return HasValidPublicKey(g) && HasValidId(g) 44 } 45 46 //SetErrorResponse Insere as informações de erro para resposta 47 func (g *GetBoletoResult) SetErrorResponse(c *gin.Context, err ErrorResponse, statusCode int) { 48 g.ErrorResponse = BoletoResponse{ 49 Errors: NewErrors(), 50 } 51 g.ErrorResponse.Errors.Append(err.Code, err.Message) 52 53 if statusCode > 499 { 54 c.JSON(statusCode, ErrorResponseToClient()) 55 } else { 56 c.JSON(statusCode, g.ErrorResponse) 57 } 58 } 59 60 func ErrorResponseToClient() BoletoResponse { 61 resp := BoletoResponse{ 62 Errors: NewErrors(), 63 } 64 resp.Errors.Append("MP500", "Internal Error") 65 return resp 66 } 67 68 func isValidHex(id string) bool { 69 match, _ := regexp.MatchString("^([0-9A-Fa-f])+$", id) 70 return match 71 }