lib.go 6.1 KB

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