errors_here.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package utils
  2. import (
  3. "crypto/rsa"
  4. "crypto/x509"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. "math/rand"
  9. "net/http"
  10. "strings"
  11. "time"
  12. )
  13. type TimeType = time.Time
  14. func TimeNow() TimeType {
  15. return time.Now()
  16. }
  17. func TimeString() string {
  18. return time.Now().Format("20060102150405")
  19. }
  20. func Sleep(sec int) {
  21. time.Sleep(time.Duration(sec) * time.Second)
  22. }
  23. func Duration(sec int) time.Duration {
  24. return time.Duration(sec) * time.Second
  25. }
  26. func RandInt(n int) int {
  27. return rand.Intn(n)
  28. }
  29. func MarshalPrivateKey(key *rsa.PrivateKey) []byte {
  30. return x509.MarshalPKCS1PrivateKey(key)
  31. }
  32. func ParsePrivateKey(key []byte) (*rsa.PrivateKey, error) {
  33. return x509.ParsePKCS1PrivateKey(key)
  34. }
  35. func MarshalPublicKey(key *rsa.PublicKey) ([]byte, error) {
  36. return x509.MarshalPKIXPublicKey(key)
  37. }
  38. func ParsePublicKey(key []byte) (*rsa.PublicKey, error) {
  39. pubAny, err := x509.ParsePKIXPublicKey(key)
  40. if err != nil {
  41. return nil, err
  42. }
  43. public, ok := pubAny.(*rsa.PublicKey)
  44. if !ok {
  45. return nil, fmt.Errorf("invalid public key type")
  46. }
  47. return public, nil
  48. }
  49. func ErrorHandler(ctx *gin.Context) {
  50. defer func() {
  51. if recover() != nil {
  52. ctx.JSON(HttpError, Fail("oops! Something bad happened."))
  53. }
  54. }()
  55. ctx.Next()
  56. }
  57. func CheckOrigin(r *http.Request) bool {
  58. return true
  59. }
  60. func HttpPost(url string, payload JsonType) (*http.Response, error) {
  61. dataBytes , err := json.Marshal(payload)
  62. if err != nil {
  63. return nil, err
  64. }
  65. dataReader := strings.NewReader(string(dataBytes))
  66. request, err := http.NewRequest("POST", url, dataReader)
  67. if err != nil {
  68. return nil, err
  69. }
  70. request.Header.Add("Content-Type", "application/json")
  71. return http.DefaultClient.Do(request)
  72. }