lib.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package utils
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/sha512"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "encoding/json"
  9. "encoding/pem"
  10. "fmt"
  11. _ "github.com/go-sql-driver/mysql"
  12. "github.com/skip2/go-qrcode"
  13. "github.com/wechatpay-apiv3/wechatpay-go/core"
  14. "github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
  15. "os"
  16. "strings"
  17. )
  18. func RandomString(size int, patten string) string {
  19. buffer, limit := make([]byte, size), len(patten)
  20. for i := 0; i < size; i++ {
  21. buffer[i] = patten[RandInt(limit)]
  22. }
  23. return string(buffer)
  24. }
  25. func WsEvent(event string, data any) WsMsg {
  26. return WsMsg{Event: event, Data: data}
  27. }
  28. func WsError(msg string) WsMsg {
  29. return WsMsg{Event: "__Error_Event__", Data: msg}
  30. }
  31. func Success(data any) Response {
  32. return Response{true, "success", data}
  33. }
  34. func Fail(msg string) Response {
  35. return Response{false, msg, nil}
  36. }
  37. func ReadConfig(filepath string) Config {
  38. config := Config{
  39. Release: false, ServerAddr: "localhost:3080", ServerPrefix: "http://localhost:3080", TimeFormat: "15:04:05",
  40. MysqlHost: "127.0.0.1", MysqlPort: 3306, MysqlUser: "wine", MysqlPass: "Wine-Mysql.1000", MysqlDatabase: "wine",
  41. RedisHost: "127.0.0.1", RedisPort: 6379, RedisPass: "Wine-Redis.1000", RedisDatabase: 0, WxPayTitle: "贵州醴泉古酿酒业",
  42. VipScanApi: "https://api.vip-sys.com/scan/", VipPayApi: "https://api.vip-sys.com/pay/",
  43. VipCallback: "https://wine.ifarmcloud.com/api/seller/current_user/",
  44. ServerPrivate: "./server-private.pem", ServerPublic: "./server-public.pem",
  45. ClientPrivate: "./client-private.pem", ClientPublic: "./client-public.pem",
  46. }
  47. file, err := os.Open(filepath)
  48. if err != nil {
  49. return config
  50. }
  51. defer func() {
  52. err = file.Close()
  53. if err != nil {
  54. }
  55. }()
  56. decoder := json.NewDecoder(file)
  57. var conf Config
  58. err = decoder.Decode(&conf)
  59. if err != nil {
  60. return config
  61. }
  62. return conf
  63. }
  64. func loadPrivate(filename string) (*rsa.PrivateKey, error) {
  65. data, err := os.ReadFile(filename)
  66. if err != nil {
  67. return nil, err
  68. }
  69. block, _ := pem.Decode(data)
  70. if block == nil {
  71. return nil, fmt.Errorf("failed to decode[%s] PEM block", filename)
  72. }
  73. return ParsePrivateKey(block.Bytes)
  74. }
  75. func loadPublic(filename string) (*rsa.PublicKey, error) {
  76. keyData, err := os.ReadFile(filename)
  77. if err != nil {
  78. return nil, err
  79. }
  80. block, _ := pem.Decode(keyData)
  81. if block == nil {
  82. return nil, fmt.Errorf("failed to decode[%s] PEM block", filename)
  83. }
  84. return ParsePublicKey(block.Bytes)
  85. }
  86. func privateKeyToPEM(pri *rsa.PrivateKey) string {
  87. private := MarshalPrivateKey(pri)
  88. block := &pem.Block{
  89. Type: "RSA PRIVATE KEY",
  90. Bytes: private,
  91. }
  92. return string(pem.EncodeToMemory(block))
  93. }
  94. func publicKeyToPEM(pub *rsa.PublicKey) (string, error) {
  95. public, err := MarshalPublicKey(pub)
  96. if err != nil {
  97. return "", err
  98. }
  99. block := &pem.Block{
  100. Type: "PUBLIC KEY",
  101. Bytes: public,
  102. }
  103. return string(pem.EncodeToMemory(block)), nil
  104. }
  105. func LoadRsaKeyPairs(conf *Config) error {
  106. pri1, err := loadPrivate(conf.ServerPrivate)
  107. if err != nil {
  108. return err
  109. }
  110. pub1, err := loadPublic(conf.ServerPublic)
  111. if err != nil {
  112. return err
  113. }
  114. ClientPub, err = publicKeyToPEM(pub1)
  115. if err != nil {
  116. return err
  117. }
  118. ServerPri = pri1
  119. pri2, err := loadPrivate(conf.ServerPrivate)
  120. if err != nil {
  121. return err
  122. }
  123. pub2, err := loadPublic(conf.ServerPublic)
  124. if err != nil {
  125. return err
  126. }
  127. ClientPri = privateKeyToPEM(pri2)
  128. ServerPub = pub2
  129. return nil
  130. }
  131. func Encrypt(text string) (string, error) {
  132. plain := []byte(text)
  133. ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, ServerPub, plain)
  134. if err != nil {
  135. return "", err
  136. }
  137. return base64.StdEncoding.EncodeToString(ciphertext), nil
  138. }
  139. func Decrypt(cipher string) (string, error) {
  140. ciphertext, err := base64.StdEncoding.DecodeString(cipher)
  141. if err != nil {
  142. return "", err
  143. }
  144. plain, err := rsa.DecryptPKCS1v15(rand.Reader, ServerPri, ciphertext)
  145. if err != nil {
  146. return "", err
  147. }
  148. return string(plain), nil
  149. }
  150. func UnZip(list JsonType) ([]string, []any) {
  151. var keys []string
  152. var values []any
  153. for k, v := range list {
  154. keys = append(keys, k)
  155. values = append(values, v)
  156. }
  157. return keys, values
  158. }
  159. func SqlFields(names []string) string {
  160. var res string
  161. for _, name := range names {
  162. res += fmt.Sprintf("`%s`=?,", name)
  163. }
  164. ll := len(res)
  165. if ll > 0 {
  166. return res[:ll-1]
  167. }
  168. return res
  169. }
  170. func SqlStringListJoin(values []string) string {
  171. var res string
  172. for _, item := range values {
  173. res += fmt.Sprintf("'%s',", item)
  174. }
  175. ll := len(res)
  176. if ll > 0 {
  177. return res[:ll-1]
  178. }
  179. return res
  180. }
  181. func SqlUint16ListJoin(values []uint16) string {
  182. var res string
  183. for _, item := range values {
  184. res += fmt.Sprintf("%d,", item)
  185. }
  186. ll := len(res)
  187. if ll > 0 {
  188. return res[:ll-1]
  189. }
  190. return res
  191. }
  192. func Uint32ListJoin(values []uint32) string {
  193. var res string
  194. for _, item := range values {
  195. res += fmt.Sprintf("%d,", item)
  196. }
  197. ll := len(res)
  198. if ll > 0 {
  199. return res[:ll-1]
  200. }
  201. return res
  202. }
  203. func AnyTrans(data any, aim any) error {
  204. tmp, err := json.Marshal(data)
  205. if err != nil {
  206. return err
  207. }
  208. err = json.Unmarshal(tmp, aim)
  209. if err != nil {
  210. return err
  211. }
  212. return nil
  213. }
  214. func TryWxPay(tradeNo string, name string, cash int) ([]byte, error) {
  215. resp, _, err := WxPaySrv.Prepay(WxPayCli,
  216. native.PrepayRequest{
  217. Appid: core.String(WxAppId),
  218. Mchid: core.String(WxMchId),
  219. Description: core.String(WxTitle + "-" + name),
  220. OutTradeNo: core.String(tradeNo),
  221. NotifyUrl: core.String("https://wine.ifarmcloud.com/api/seller/wxpay"),
  222. Amount: &native.Amount{Total: core.Int64(int64(cash))}, // cash
  223. },
  224. )
  225. if err != nil {
  226. fmt.Printf("wxpay error: %s\n", err)
  227. return nil, err
  228. }
  229. return qrcode.Encode(*resp.CodeUrl, qrcode.Medium, 512)
  230. }
  231. func Format(str string, v ...any) string {
  232. return fmt.Sprintf(str, v...)
  233. }
  234. func HashPassword(password string) string {
  235. hash := sha512.New()
  236. hash.Write([]byte(password))
  237. hashedPassword := hex.EncodeToString(hash.Sum(nil))
  238. return hashedPassword
  239. }
  240. func IsPasswordMatch(pwdInDb, pwdFromUser string) bool {
  241. return pwdInDb == HashPassword(pwdFromUser)
  242. }
  243. func Query(SQL string) ([]JsonType, error) {
  244. rows, err := Mysql.Query(SQL)
  245. if err != nil {
  246. return nil, err
  247. }
  248. columns, _ := rows.Columns()
  249. count := len(columns)
  250. var values = make([]interface{}, count)
  251. for i := range values {
  252. var ii interface{}
  253. values[i] = &ii
  254. }
  255. ret := make([]JsonType, 0)
  256. for rows.Next() {
  257. err = rows.Scan(values...)
  258. m := make(JsonType)
  259. if err != nil {
  260. return nil, err
  261. }
  262. for i, colName := range columns {
  263. m[colName] = *(values[i].(*interface{}))
  264. }
  265. ret = append(ret, m)
  266. }
  267. defer func() {
  268. _ = rows.Close()
  269. }()
  270. return ret, nil
  271. }
  272. func SaveBase64(image, filepath string) (string, string, error) {
  273. split := strings.Split(image, ",")
  274. info, data := split[0], split[1]
  275. decoded, err := base64.StdEncoding.DecodeString(data)
  276. if err != nil {
  277. return "", "Base64 格式错误", err
  278. }
  279. ext := strings.Split(info, "/")[1]
  280. ext = strings.Split(ext, ";")[0]
  281. err = os.WriteFile(filepath+"."+ext, decoded, 0644)
  282. if err != nil {
  283. return "", "文件存储失败", err
  284. }
  285. return ext, "", nil
  286. }