lib.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. ServerPrivate: "./server-private.pem", ServerPublic: "./server-public.pem",
  43. ClientPrivate: "./client-private.pem", ClientPublic: "./client-public.pem",
  44. }
  45. file, err := os.Open(filepath)
  46. if err != nil {
  47. return config
  48. }
  49. defer func() {
  50. err = file.Close()
  51. if err != nil {
  52. }
  53. }()
  54. decoder := json.NewDecoder(file)
  55. var conf Config
  56. err = decoder.Decode(&conf)
  57. if err != nil {
  58. return config
  59. }
  60. return conf
  61. }
  62. func loadPrivate(filename string) (*rsa.PrivateKey, error) {
  63. data, err := os.ReadFile(filename)
  64. if err != nil {
  65. return nil, err
  66. }
  67. block, _ := pem.Decode(data)
  68. if block == nil {
  69. return nil, fmt.Errorf("failed to decode[%s] PEM block", filename)
  70. }
  71. return ParsePrivateKey(block.Bytes)
  72. }
  73. func loadPublic(filename string) (*rsa.PublicKey, error) {
  74. keyData, err := os.ReadFile(filename)
  75. if err != nil {
  76. return nil, err
  77. }
  78. block, _ := pem.Decode(keyData)
  79. if block == nil {
  80. return nil, fmt.Errorf("failed to decode[%s] PEM block", filename)
  81. }
  82. return ParsePublicKey(block.Bytes)
  83. }
  84. func privateKeyToPEM(pri *rsa.PrivateKey) string {
  85. private := MarshalPrivateKey(pri)
  86. block := &pem.Block{
  87. Type: "RSA PRIVATE KEY",
  88. Bytes: private,
  89. }
  90. return string(pem.EncodeToMemory(block))
  91. }
  92. func publicKeyToPEM(pub *rsa.PublicKey) (string, error) {
  93. public, err := MarshalPublicKey(pub)
  94. if err != nil {
  95. return "", err
  96. }
  97. block := &pem.Block{
  98. Type: "PUBLIC KEY",
  99. Bytes: public,
  100. }
  101. return string(pem.EncodeToMemory(block)), nil
  102. }
  103. func LoadRsaKeyPairs(conf *Config) error {
  104. pri1, err := loadPrivate(conf.ServerPrivate)
  105. if err != nil {
  106. return err
  107. }
  108. pub1, err := loadPublic(conf.ServerPublic)
  109. if err != nil {
  110. return err
  111. }
  112. ClientPub, err = publicKeyToPEM(pub1)
  113. if err != nil {
  114. return err
  115. }
  116. ServerPri = pri1
  117. pri2, err := loadPrivate(conf.ServerPrivate)
  118. if err != nil {
  119. return err
  120. }
  121. pub2, err := loadPublic(conf.ServerPublic)
  122. if err != nil {
  123. return err
  124. }
  125. ClientPri = privateKeyToPEM(pri2)
  126. ServerPub = pub2
  127. return nil
  128. }
  129. func Encrypt(text string) (string, error) {
  130. plain := []byte(text)
  131. ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, ServerPub, plain)
  132. if err != nil {
  133. return "", err
  134. }
  135. return base64.StdEncoding.EncodeToString(ciphertext), nil
  136. }
  137. func Decrypt(cipher string) (string, error) {
  138. ciphertext, err := base64.StdEncoding.DecodeString(cipher)
  139. if err != nil {
  140. return "", err
  141. }
  142. plain, err := rsa.DecryptPKCS1v15(rand.Reader, ServerPri, ciphertext)
  143. if err != nil {
  144. return "", err
  145. }
  146. return string(plain), nil
  147. }
  148. func UnZip(list JsonType) ([]string, []any) {
  149. var keys []string
  150. var values []any
  151. for k, v := range list {
  152. keys = append(keys, k)
  153. values = append(values, v)
  154. }
  155. return keys, values
  156. }
  157. func SqlFields(names []string) string {
  158. var res string
  159. for _, name := range names {
  160. res += fmt.Sprintf("`%s`=?,", name)
  161. }
  162. ll := len(res)
  163. if ll > 0 {
  164. return res[:ll-1]
  165. }
  166. return res
  167. }
  168. func SqlStringListJoin(values []string) string {
  169. var res string
  170. for _, item := range values {
  171. res += fmt.Sprintf("'%s',", item)
  172. }
  173. ll := len(res)
  174. if ll > 0 {
  175. return res[:ll-1]
  176. }
  177. return res
  178. }
  179. func SqlUint16ListJoin(values []uint16) string {
  180. var res string
  181. for _, item := range values {
  182. res += fmt.Sprintf("%d,", item)
  183. }
  184. ll := len(res)
  185. if ll > 0 {
  186. return res[:ll-1]
  187. }
  188. return res
  189. }
  190. func AnyTrans(data any, aim any) error {
  191. tmp, err := json.Marshal(data)
  192. if err != nil {
  193. return err
  194. }
  195. err = json.Unmarshal(tmp, aim)
  196. if err != nil {
  197. return err
  198. }
  199. return nil
  200. }
  201. func TryWxPay(tradeNo string, name string, cash int) ([]byte, error) {
  202. resp, _, err := WxPaySrv.Prepay(WxPayCli,
  203. native.PrepayRequest{
  204. Appid: core.String(WxAppId),
  205. Mchid: core.String(WxMchId),
  206. Description: core.String(WxTitle + "-" + name),
  207. OutTradeNo: core.String(tradeNo),
  208. NotifyUrl: core.String("https://wine.ifarmcloud.com/api/seller/wxpay"),
  209. Amount: &native.Amount{Total: core.Int64(int64(1))}, // cash
  210. },
  211. )
  212. if err != nil {
  213. fmt.Printf("wxpay error: %s\n", err)
  214. return nil, err
  215. }
  216. return qrcode.Encode(*resp.CodeUrl, qrcode.Medium, 512)
  217. }
  218. func Format(str string, v ...any) string {
  219. return fmt.Sprintf(str, v...)
  220. }
  221. func HashPassword(password string) string {
  222. hash := sha512.New()
  223. hash.Write([]byte(password))
  224. hashedPassword := hex.EncodeToString(hash.Sum(nil))
  225. return hashedPassword
  226. }
  227. func IsPasswordMatch(pwdInDb, pwdFromUser string) bool {
  228. return pwdInDb == HashPassword(pwdFromUser)
  229. }
  230. func Query(SQL string) ([]JsonType, error) {
  231. rows, err := Mysql.Query(SQL)
  232. if err != nil {
  233. return nil, err
  234. }
  235. columns, _ := rows.Columns()
  236. count := len(columns)
  237. var values = make([]interface{}, count)
  238. for i := range values {
  239. var ii interface{}
  240. values[i] = &ii
  241. }
  242. ret := make([]JsonType, 0)
  243. for rows.Next() {
  244. err = rows.Scan(values...)
  245. m := make(JsonType)
  246. if err != nil {
  247. return nil, err
  248. }
  249. for i, colName := range columns {
  250. m[colName] = *(values[i].(*interface{}))
  251. }
  252. ret = append(ret, m)
  253. }
  254. defer func() {
  255. _ = rows.Close()
  256. }()
  257. return ret, nil
  258. }
  259. func SaveBase64(image, filepath string) (string, string, error) {
  260. split := strings.Split(image, ",")
  261. info, data := split[0], split[1]
  262. decoded, err := base64.StdEncoding.DecodeString(data)
  263. if err != nil {
  264. return "", "Base64 格式错误", err
  265. }
  266. ext := strings.Split(info, "/")[1]
  267. ext = strings.Split(ext, ";")[0]
  268. err = os.WriteFile(filepath+"."+ext, decoded, 0644)
  269. if err != nil {
  270. return "", "文件存储失败", err
  271. }
  272. return ext, "", nil
  273. }