1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- package utils
- import (
- "crypto/rsa"
- "crypto/x509"
- "encoding/json"
- "fmt"
- "github.com/gin-gonic/gin"
- "math/rand"
- "net/http"
- "strings"
- "time"
- )
- type TimeType = time.Time
- func TimeNow() TimeType {
- return time.Now()
- }
- func TimeString() string {
- return time.Now().Format("20060102150405")
- }
- func Sleep(sec int) {
- time.Sleep(time.Duration(sec) * time.Second)
- }
- func Duration(sec int) time.Duration {
- return time.Duration(sec) * time.Second
- }
- func RandInt(n int) int {
- return rand.Intn(n)
- }
- func MarshalPrivateKey(key *rsa.PrivateKey) []byte {
- return x509.MarshalPKCS1PrivateKey(key)
- }
- func ParsePrivateKey(key []byte) (*rsa.PrivateKey, error) {
- return x509.ParsePKCS1PrivateKey(key)
- }
- func MarshalPublicKey(key *rsa.PublicKey) ([]byte, error) {
- return x509.MarshalPKIXPublicKey(key)
- }
- func ParsePublicKey(key []byte) (*rsa.PublicKey, error) {
- pubAny, err := x509.ParsePKIXPublicKey(key)
- if err != nil {
- return nil, err
- }
- public, ok := pubAny.(*rsa.PublicKey)
- if !ok {
- return nil, fmt.Errorf("invalid public key type")
- }
- return public, nil
- }
- func ErrorHandler(ctx *gin.Context) {
- defer func() {
- if recover() != nil {
- ctx.JSON(HttpError, Fail("oops! Something bad happened."))
- }
- }()
- ctx.Next()
- }
- func CheckOrigin(r *http.Request) bool {
- return true
- }
- func HttpPost(url string, payload JsonType) (*http.Response, error) {
- dataBytes , err := json.Marshal(payload)
- if err != nil {
- return nil, err
- }
- dataReader := strings.NewReader(string(dataBytes))
- request, err := http.NewRequest("POST", url, dataReader)
- if err != nil {
- return nil, err
- }
- request.Header.Add("Content-Type", "application/json")
- return http.DefaultClient.Do(request)
- }
|