errors_here.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package utils
  2. import (
  3. "crypto/rsa"
  4. "crypto/x509"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "math/rand"
  8. "net/http"
  9. "time"
  10. )
  11. type TimeType = time.Time
  12. func TimeNow() TimeType {
  13. return time.Now()
  14. }
  15. func TimeString() string {
  16. return time.Now().Format("20060102150405")
  17. }
  18. func Sleep(sec int) {
  19. time.Sleep(time.Duration(sec) * time.Second)
  20. }
  21. func Duration(sec int) time.Duration {
  22. return time.Duration(sec) * time.Second
  23. }
  24. func RandInt(n int) int {
  25. return rand.Intn(n)
  26. }
  27. func MarshalPrivateKey(key *rsa.PrivateKey) []byte {
  28. return x509.MarshalPKCS1PrivateKey(key)
  29. }
  30. func ParsePrivateKey(key []byte) (*rsa.PrivateKey, error) {
  31. return x509.ParsePKCS1PrivateKey(key)
  32. }
  33. func MarshalPublicKey(key *rsa.PublicKey) ([]byte, error) {
  34. return x509.MarshalPKIXPublicKey(key)
  35. }
  36. func ParsePublicKey(key []byte) (*rsa.PublicKey, error) {
  37. pubAny, err := x509.ParsePKIXPublicKey(key)
  38. if err != nil {
  39. return nil, err
  40. }
  41. public, ok := pubAny.(*rsa.PublicKey)
  42. if !ok {
  43. return nil, fmt.Errorf("invalid public key type")
  44. }
  45. return public, nil
  46. }
  47. func ErrorHandler(ctx *gin.Context) {
  48. defer func() {
  49. if recover() != nil {
  50. ctx.JSON(HttpError, Fail("oops! Something bad happened."))
  51. }
  52. }()
  53. ctx.Next()
  54. }
  55. func CheckOrigin(r *http.Request) bool {
  56. return true
  57. }