SM2 加解密示例类

This commit is contained in:
wuchao 2024-06-11 14:57:08 +08:00
parent 89ba5c1075
commit 47f7a8324f
12 changed files with 627 additions and 69 deletions

View File

@ -15,6 +15,8 @@ import (
"net/http"
"qteam/app/utils"
"qteam/config"
"regexp"
"strings"
"qteam/app/constants/errorcode"
@ -103,22 +105,35 @@ func GenRequest(c *gin.Context, request interface{}) (msgs []string, err error)
if c.Request.Method == "GET" || c.Request.Method == "DELETE" {
err = c.ShouldBindQuery(request)
} else {
err = c.ShouldBindJSON(request)
//err = c.ShouldBindJSON(request)
err = c.ShouldBind(request)
}
var req, _ = json.Marshal(request)
utils.Log(c, "request", string(req))
if err == nil {
validate := validator.New()
validate.RegisterValidation("AmountValidation", AmountValidationFunc)
zh_ch := zh.New()
uni := ut.New(zh_ch)
trans, _ := uni.GetTranslator("zh")
validate.RegisterTranslation("AmountValidation", trans, func(ut ut.Translator) error {
return ut.Add("AmountValidation", "{0} 为数字 小数点后最多两位", true) // 添加翻译
},
func(ut ut.Translator, fe validator.FieldError) string {
t, _ := ut.T("AmountValidation", fe.Field()) // 获取翻译
return t
},
)
//验证器注册翻译器
zh_translations.RegisterDefaultTranslations(validate, trans)
errValidate := validate.Struct(request)
if errValidate != nil {
for _, v := range errValidate.(validator.ValidationErrors) {
msgs = append(msgs, v.Translate(trans))
msgs = append(msgs, utils.ToSnakeCase(v.Translate(trans)))
}
err = errors.New(errorcode.GetMsg(errorcode.ParamError, ""))
return
@ -127,6 +142,28 @@ func GenRequest(c *gin.Context, request interface{}) (msgs []string, err error)
return
}
// AmountValidationFunc 自定义面值校验函数
func AmountValidationFunc(f1 validator.FieldLevel) bool {
str := f1.Field().String()
re := regexp.MustCompile("[^0-9.]")
s := re.FindString(str)
if len(s) > 0 {
return false
}
l := strings.Split(str, ".")
if len(l) > 2 {
return false
}
if len(l) == 2 {
if len(l[1]) > 2 {
return false
}
}
return true
}
// 重复读取body
func ReadBody(c *gin.Context) (body []byte, err error) {
body, err = ioutil.ReadAll(c.Request.Body)

View File

@ -0,0 +1,12 @@
package front
import (
"github.com/gin-gonic/gin"
"qteam/app/http/controllers"
"qteam/app/services"
)
func GetGenerateSm2Key(c *gin.Context) {
PublicKey, privateKey, _ := services.GenerateSM2Key()
controllers.Success(c, map[string]string{"PublicKey": PublicKey, "privateKey": privateKey}, "")
}

View File

@ -61,7 +61,9 @@ func ValidateRequest() gin.HandlerFunc {
if strings.Index(path, "admin") >= 0 {
handler = requestmapping.BackendRequestMap[path]
} else {
handler = requestmapping.FrontRequestMap[path]
var ok bool
handler, ok = requestmapping.FrontRequestMap[path]
utils.Log(c, "test", ok)
}
if handler == nil {
utils.Log(c, "path", path)
@ -80,3 +82,19 @@ func ValidateRequest() gin.HandlerFunc {
}
}
}
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, platform,Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control,token, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}

View File

@ -1,7 +1,5 @@
package requestmapping
var FrontRequestMap = map[string]func() interface{}{
//"/v1/login": func() interface{} {
// return new(front.LoginRequest)
//},
"/v1/GenerateSm2Key": func() interface{} { return new(struct{}) },
}

View File

@ -5,6 +5,7 @@ package routes
*/
import (
"qteam/app/http/controllers"
"qteam/app/http/controllers/front"
"qteam/app/http/middlewares"
"qteam/app/http/trace"
"qteam/app/utils/metric"
@ -39,14 +40,14 @@ func RegisterRoute(router *gin.Engine) {
router.Use(middlewares.Trace())
}
}
router.Use(middlewares.Cors())
router.NoRoute(controllers.Error404)
//api版本
//v1 := router.Group("/v1", middlewares.ValidateRequest())
//{
//
//}
v1 := router.Group("/v1", middlewares.ValidateRequest())
{
v1.GET("/GenerateSm2Key", front.GetGenerateSm2Key)
}
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

156
app/services/SmService.go Normal file
View File

@ -0,0 +1,156 @@
package services
import (
"crypto/rand"
"encoding/hex"
"fmt"
"github.com/tjfoc/gmsm/sm2"
"math/big"
"qteam/config"
"strings"
)
// 生成公钥、私钥
func GenerateSM2Key() (PublicKey string, PrivateKey string, err error) {
// 生成私钥、公钥
privKey, err := sm2.GenerateKey(rand.Reader)
if err != nil {
fmt.Println("生成密钥对失败:", err)
return "", "", err
}
return PublicKeyToString(&privKey.PublicKey), PrivateKeyToString(privKey), nil
}
// PublicKeyToString 公钥sm2.PublicKey转字符串(与java中org.bouncycastle.crypto生成的公私钥完全互通使用)
func PublicKeyToString(publicKey *sm2.PublicKey) string {
xBytes := publicKey.X.Bytes()
yBytes := publicKey.Y.Bytes()
// 确保坐标字节切片长度相同
byteLen := len(xBytes)
if len(yBytes) > byteLen {
byteLen = len(yBytes)
}
// 为坐标补齐前导零
xBytes = append(make([]byte, byteLen-len(xBytes)), xBytes...)
yBytes = append(make([]byte, byteLen-len(yBytes)), yBytes...)
// 添加 "04" 前缀
publicKeyBytes := append([]byte{0x04}, append(xBytes, yBytes...)...)
return strings.ToUpper(hex.EncodeToString(publicKeyBytes))
}
// PrivateKeyToString 私钥sm2.PrivateKey 转字符串(与java中org.bouncycastle.crypto生成的公私钥完全互通使用)
func PrivateKeyToString(privateKey *sm2.PrivateKey) string {
return strings.ToUpper(hex.EncodeToString(privateKey.D.Bytes()))
}
func SM2Decrypt(cipherText string) (string, error) {
if cipherText == "" {
return "", nil
}
decrypt, err := decryptLoc(config.GetConf().Sm2.PublicKey, config.GetConf().Sm2.PrivateKey, cipherText)
if err != nil {
return "", err
}
return decrypt, nil
}
func SM2Encrypt(cipherText string) (string, error) {
if cipherText == "" {
return "", nil
}
decrypt, err := encryptLoc(config.GetConf().Sm2.PublicKey, cipherText)
if err != nil {
return "", err
}
return decrypt, nil
}
func encryptLoc(publicKeyStr, data string) (string, error) {
publicKeyObj, err := StringToPublicKey(publicKeyStr)
if err != nil {
fmt.Println(err)
}
decodeString, err := hex.DecodeString(data)
decrypt, err := sm2.Encrypt(publicKeyObj, decodeString, rand.Reader, sm2.C1C2C3)
if err != nil {
fmt.Println(err)
}
resultStr := hex.EncodeToString(decrypt)
fmt.Println("解密后的字符串:", resultStr)
return resultStr, nil
}
func decryptLoc(publicKeyStr, privateKeyStr, cipherText string) (string, error) {
publicKeyObj, err := StringToPublicKey(publicKeyStr)
if err != nil {
fmt.Println(err)
}
privateKeyObj, err := StringToPrivateKey(privateKeyStr, publicKeyObj)
if err != nil {
fmt.Println(err)
}
decodeString, err := hex.DecodeString(cipherText)
decrypt, err := sm2.Decrypt(privateKeyObj, decodeString, sm2.C1C2C3)
if err != nil {
fmt.Println(err)
}
resultStr := hex.EncodeToString(decrypt)
fmt.Println("解密后的字符串:", resultStr)
return resultStr, nil
}
// StringToPrivateKey 私钥还原为 sm2.PrivateKey对象(与java中org.bouncycastle.crypto生成的公私钥完全互通使用)
func StringToPrivateKey(privateKeyStr string, publicKey *sm2.PublicKey) (*sm2.PrivateKey, error) {
privateKeyBytes, err := hex.DecodeString(privateKeyStr)
if err != nil {
return nil, err
}
// 将字节切片转换为大整数
d := new(big.Int).SetBytes(privateKeyBytes)
// 创建 sm2.PrivateKey 对象
privateKey := &sm2.PrivateKey{
PublicKey: *publicKey,
D: d,
}
return privateKey, nil
}
// StringToPublicKey 公钥字符串还原为 sm2.PublicKey 对象(与java中org.bouncycastle.crypto生成的公私钥完全互通使用)
func StringToPublicKey(publicKeyStr string) (*sm2.PublicKey, error) {
publicKeyBytes, err := hex.DecodeString(publicKeyStr)
if err != nil {
return nil, err
}
// 提取 x 和 y 坐标字节切片
curve := sm2.P256Sm2().Params()
byteLen := (curve.BitSize + 7) / 8
xBytes := publicKeyBytes[1 : byteLen+1]
yBytes := publicKeyBytes[byteLen+1 : 2*byteLen+1]
// 将字节切片转换为大整数
x := new(big.Int).SetBytes(xBytes)
y := new(big.Int).SetBytes(yBytes)
// 创建 sm2.PublicKey 对象
publicKey := &sm2.PublicKey{
Curve: curve,
X: x,
Y: y,
}
return publicKey, nil
}
// 验证签名
func VerSm2Sig(pub *sm2.PublicKey, msg []byte, sign []byte) bool {
isok := pub.Verify(msg, sign)
return isok
}

View File

@ -3,17 +3,29 @@ package utils
import (
"context"
"crypto/md5"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"github.com/qit-team/snow-core/redis"
"github.com/tjfoc/gmsm/sm2"
"github.com/tjfoc/gmsm/x509"
mrand "math/rand"
"net"
"os"
"path/filepath"
"qteam/app/constants/common"
"qteam/config"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"unicode"
)
const (
@ -67,19 +79,140 @@ func Encode(number int64) string {
}
// 生成用户touken
func GeneratorToken(playerName string, playerId string) string {
func GeneratorToken(playerName string, playerId int) string {
//去生成一个token返回给客户端
m5 := SToMd5(playerName + time.Now().String())
var pid, _ = strconv.ParseInt(playerId, 10, 64)
var pid = int64(playerId)
bsCode := Encode(pid)
tk := m5 + bsCode
//将token放入redis
_, err := redis.GetRedis(redis.SingletonMain).SetEX(context.Background(), GetRealKey(tk), playerId, 3600).Result()
_, err := redis.GetRedis(redis.SingletonMain).SetEX(context.Background(), GetRealKey(common.TOKEN_PRE+tk), playerId, time.Duration(3600)*time.Second).Result()
if err != nil {
Log(nil, "token", err)
}
return tk
}
// ExistFile 检查给定的文件是否存在
func ExistFile(dirPath string) (exist bool, err error) {
// 使用filepath.Abs获取绝对路径确保我们处理的是实际存在的路径
absPath, err := filepath.Abs(dirPath)
if err != nil {
return exist, fmt.Errorf("failed to get absolute path: %v", err)
}
// 使用os.Stat检查路径是否存在
_, err = os.Stat(absPath)
if errors.Is(err, os.ErrNotExist) {
return exist, nil
}
return true, err
}
// StrToTimeShanghai 字符串转时间
func StrToTimeShanghai(strTime string) (t time.Time, err error) {
location, _ := time.LoadLocation("Asia/Shanghai")
return time.ParseInLocation(time.DateTime, strTime, location)
}
func GenIncrementId(tableName string) (int, error) {
var id, err = redis.GetRedis().Incr(context.Background(), GetRealKey(tableName)).Result()
return int(id), err
}
// CheckOrCreateYmdDirectory 创建ymd目录
func CheckOrCreateYmdDirectory(dirPath string) (SavePath string, err error) {
// 使用filepath.Abs获取绝对路径确保我们处理的是实际存在的路径
now := time.Now()
year := now.Year()
month := now.Month()
day := now.Day()
savePath := filepath.Join("uploads", dirPath, fmt.Sprintf("%d", year), fmt.Sprintf("%d", month), fmt.Sprintf("%d", day))
absPath, err := filepath.Abs(savePath)
if err != nil {
return SavePath, fmt.Errorf("failed to get absolute path: %v", err)
}
// 使用os.Stat检查路径是否存在
info, err := os.Stat(absPath)
if err != nil {
if !os.IsNotExist(err) {
return SavePath, fmt.Errorf("error checking directory: %v", err)
}
// 目录不存在,尝试创建
err = os.MkdirAll(absPath, 0755) // 0755是默认权限可以按需调整
if err != nil {
return SavePath, fmt.Errorf("failed to create directory: %v", err)
}
} else if !info.IsDir() {
return SavePath, fmt.Errorf("%s exists but it's not a directory", absPath)
}
SavePath = absPath
return SavePath, nil
}
// CheckOrCreateDirectory 检查给定的目录是否存在,如果不存在则创建它
func CheckOrCreateDirectory(dirPath string) error {
// 使用filepath.Abs获取绝对路径确保我们处理的是实际存在的路径
absPath, err := filepath.Abs(dirPath)
if err != nil {
return fmt.Errorf("failed to get absolute path: %v", err)
}
// 使用os.Stat检查路径是否存在
info, err := os.Stat(absPath)
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("error checking directory: %v", err)
}
// 目录不存在,尝试创建
err = os.MkdirAll(absPath, 0755) // 0755是默认权限可以按需调整
if err != nil {
return fmt.Errorf("failed to create directory: %v", err)
}
} else if !info.IsDir() {
return fmt.Errorf("%s exists but it's not a directory", absPath)
}
return nil
}
func ToSnakeCase(s string) string {
ch, en := splitChineseEnglish(s)
fmt.Println(ch, en)
re := regexp.MustCompile("([a-z0-9])([A-Z])")
snake := re.ReplaceAllString(en, "${1}_${2}")
return strings.ToLower(snake) + ch
}
func splitChineseEnglish(input string) (chinese string, english string) {
var index = findChineseStartIndex(input)
return input[index:], input[0:index]
}
func findChineseStartIndex(input string) int {
runes := []rune(input)
for i, r := range runes {
if unicode.Is(unicode.Han, r) {
return i
}
}
return -1 // 如果没有找到中文字符,返回-1
}
func DownloadFileFromOss(url, savePath string) error {
_, bucket, err := AliOssClient()
if err != nil {
return err
}
err = bucket.GetObjectToFileWithURL(url, savePath)
return err
}
func EntityCopy(dst, src interface{}) {
dstValue := reflect.ValueOf(dst).Elem()
srcValue := reflect.ValueOf(src).Elem()
@ -128,3 +261,110 @@ func EntityCopy(dst, src interface{}) {
}
}
}
// AliOssClient 返回Oss客户链接
func AliOssClient() (client *oss.Client, Bucket *oss.Bucket, err error) {
/*
oss 的相关配置信息
*/
bucketName := config.GetConf().AliOss.BucKet
endpoint := config.GetConf().AliOss.EndPoint
accessKeyId := config.GetConf().AliOss.AccessKey
accessKeySecret := config.GetConf().AliOss.AccessKeySecret
//domain := config.GetConf().AliOss.Domain
//Dir := config.GetConf().AliOss.Dir
//创建OSSClient实例
client, err = oss.New(endpoint, accessKeyId, accessKeySecret)
if err != nil {
return nil, nil, err
}
// 获取存储空间
Bucket, err = client.Bucket(bucketName)
if err != nil {
return nil, nil, err
}
return client, Bucket, nil
}
func GetSHA256HashCode(message []byte) string {
//方法一:
//创建一个基于SHA256算法的hash.Hash接口的对象
hash := sha256.New()
//输入数据
hash.Write(message)
//计算哈希值
bytes := hash.Sum(nil)
//将字符串编码为16进制格式,返回字符串
hashCode := hex.EncodeToString(bytes)
//返回哈希值
return hashCode
//方法二:
//bytes2:=sha256.Sum256(message)//计算哈希值返回一个长度为32的数组
//hashcode2:=hex.EncodeToString(bytes2[:])//将数组转换成切片转换成16进制返回字符串
//return hashcode2
}
func GetSHA512HashCode(message []byte) string {
hash := sha512.New()
hash.Write(message)
bytes := hash.Sum(nil)
hashCode := hex.EncodeToString(bytes)
return hashCode
}
// SM2Encode sm2公钥加密
func SM2Encode(pubKey string, plaintext string, mode int) (string, error) {
pubMen, err := x509.ReadPublicKeyFromHex(pubKey)
if err != nil {
return "", err
}
msg := []byte(plaintext)
ciphertxt, err := sm2.Encrypt(pubMen, msg, rand.Reader, mode)
if err != nil {
return "", err
}
return hex.EncodeToString(ciphertxt), nil
}
// SM2Decode sm2私钥解密
func SM2Decode(privKey string, data string, mode int) (string, error) {
priv, err := x509.ReadPrivateKeyFromHex(privKey)
if err != nil {
return "", err
}
ciphertext, err := hex.DecodeString(data)
if err != nil {
return "", err
}
plaintext, err := sm2.Decrypt(priv, []byte(ciphertext), mode)
if err != nil {
return "", err
}
return string(plaintext), nil
}
func GenerateOrderNumber() string {
// 生成当前日期部分例如20231008
datePart := time.Now().Format("20060102150405")
// 生成随机数部分4位随机数
mrand.Seed(time.Now().UnixNano())
randomPart := fmt.Sprintf("%04d", mrand.Intn(10000))
// 添加固定前缀
prefix := "SN"
// 最终的订单号由前缀、日期和随机数部分组成
orderNumber := fmt.Sprintf("%s%s%s", prefix, datePart, randomPart)
return orderNumber
}
func IsNil(x interface{}) bool {
if x == nil {
return true
}
rv := reflect.ValueOf(x)
return rv.Kind() == reflect.Ptr && rv.IsNil()
}

View File

@ -1,10 +1,9 @@
package config
import (
"os"
"github.com/BurntSushi/toml"
"github.com/qit-team/snow-core/config"
"os"
)
const (
@ -32,14 +31,81 @@ type Config struct {
Nacos Nacos `toml:"Nacas"`
Rpc Rpc `toml:"Rpc"`
AppKey string `toml:"AppKey"`
KafkaUrl []string `toml:"KafkaUrl"`
AliSms AliSms `toml:"AliSms"`
AdminGate string `toml:"AdminGate"`
PluginDir string `toml:"PLUGIN_DIR"`
ImgDir string `toml:"IMG_DIR"`
OtherDir string `toml:"OTHER_DIR"`
AliOss AliOss `toml:"AliOss"`
TemplateUrl string `toml:"TemplateUrl"`
Message Message `toml:"Message"`
OpenApi OpenApi `toml:"OpenApi"`
OpenApiMarketConfig MarketConfig `toml:"MarketConfig"`
RocketMq []string `toml:"RocketMq"`
Sm2 Sm2 `toml:"Sm2"`
}
type Sm2 struct {
PublicKey string
PrivateKey string
}
type OpenApi struct {
MerchantId string
SecretKey string
IsProd bool
NotifyUrl string
TimeOut int
}
type Message struct {
ClientKey string
ClientSecret string
ServerIndex string
TempIndex string
Url string
}
type AliOss struct {
AccessKey string
AccessKeySecret string
EndPoint string
BucKet string
Domain string
Dir string
}
type AliSms struct {
Url string
AccessKeyId string
AccessKeySecret string
SignName string
TemplateSmsCode string
Nums int
}
type Rpc struct {
User string
Port string
Servers []string
}
type Nacos struct {
Url string
Port int64
Url string
Port int64
ServiceName string
GroupName string
ClusterName string
ServicePort int64
}
type MarketConfig struct {
AppId string `json:"app_id"` //APP ID
Sign string `json:"sign"` //签名
ReqCode string `json:"req_code"` //固定值voucher.create
MemId string `json:"mem_id"` //商户号
PosId string `json:"pos_id"` //商户方平台号
Host string `json:"-"`
SecretKey string
}
func newConfig() *Config {

19
go.mod
View File

@ -4,25 +4,29 @@ go 1.21
require (
github.com/BurntSushi/toml v0.4.1
github.com/ahmetb/go-linq/v3 v3.2.0
github.com/Shopify/sarama v1.19.0
github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible
github.com/forgoer/openssl v1.6.0
github.com/gin-gonic/gin v1.7.7
github.com/go-playground/locales v0.14.0
github.com/go-playground/universal-translator v0.18.0
github.com/go-sql-driver/mysql v1.6.0
github.com/nacos-group/nacos-sdk-go/v2 v2.2.5
github.com/nats-io/nats.go v1.9.1
github.com/openzipkin/zipkin-go v0.2.2
github.com/pkg/errors v0.9.1
github.com/prometheus/client_golang v1.12.2
github.com/qit-team/snow-core v0.1.28
github.com/qit-team/work v0.3.11
github.com/robfig/cron v1.2.0
github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271
github.com/swaggo/gin-swagger v1.3.3
github.com/swaggo/swag v1.7.9
github.com/tjfoc/gmsm v1.4.1
github.com/valyala/fasthttp v1.31.0
google.golang.org/grpc v1.56.3
google.golang.org/protobuf v1.30.0
gopkg.in/go-playground/validator.v9 v9.31.0
xorm.io/builder v0.3.9
)
require (
@ -40,7 +44,11 @@ require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/eapache/go-resiliency v1.1.0 // indirect
github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 // indirect
github.com/eapache/queue v1.1.0 // indirect
github.com/emirpasic/gods v1.12.0 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
@ -68,10 +76,14 @@ require (
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/nats-io/jwt v0.3.2 // indirect
github.com/nats-io/nkeys v0.1.3 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
github.com/pierrec/lz4 v2.0.5+incompatible // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.32.1 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a // indirect
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 // indirect
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/syndtr/goleveldb v1.0.0 // indirect
@ -96,6 +108,7 @@ require (
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
stathat.com/c/consistent v1.0.0 // indirect
xorm.io/builder v0.3.9 // indirect
xorm.io/core v0.7.3 // indirect
xorm.io/xorm v1.2.5 // indirect
)

21
go.sum
View File

@ -51,14 +51,14 @@ github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tN
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/Shopify/sarama v1.19.0 h1:9oksLxC6uxVPHPVYUmq6xhr1BOF/hHobWH2UzO67z1s=
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
github.com/Shopify/toxiproxy v2.1.4+incompatible h1:TKdv8HiTLgE5wdJuEML90aBgNWsokNbMijUGhmcoBJc=
github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g=
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c=
github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs=
github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY=
github.com/ahmetb/go-linq/v3 v3.2.0 h1:BEuMfp+b59io8g5wYzNoFe9pWPalRklhlhbiU3hYZDE=
github.com/ahmetb/go-linq/v3 v3.2.0/go.mod h1:haQ3JfOeWK8HpVxMtHHEMPVgBKiYyQ+f1/kLZh/cj9U=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
@ -78,6 +78,8 @@ github.com/aliyun/alibabacloud-dkms-gcs-go-sdk v0.2.2/go.mod h1:GDtq+Kw+v0fO+j5B
github.com/aliyun/alibabacloud-dkms-transfer-go-sdk v0.1.7 h1:olLiPI2iM8Hqq6vKnSxpM3awCrm9/BeOgHpzQkOYnI4=
github.com/aliyun/alibabacloud-dkms-transfer-go-sdk v0.1.7/go.mod h1:oDg1j4kFxnhgftaiLJABkGeSvuEvSF5Lo6UmRAMruX4=
github.com/aliyun/aliyun-mns-go-sdk v1.0.2/go.mod h1:eD/mEH7SwtLSwI9p8fP9VTH2cYM3wFSY1WNaxEdLIFU=
github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible h1:8psS8a+wKfiLt1iVDX79F7Y6wUM49Lcha2FMXt4UM8g=
github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8=
github.com/aliyunmq/mq-http-go-sdk v1.0.3/go.mod h1:JYfRMQoPexERvnNNBcal0ZQ2TVQ5ialDiW9ScjaadEM=
github.com/andybalholm/brotli v1.0.2/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=
github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=
@ -142,8 +144,11 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/eapache/go-resiliency v1.1.0 h1:1NtRmCAqadE2FN4ZcN6g90TP3uk8cg9rn9eNK2197aU=
github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs=
github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 h1:YEetp8/yCZMuEPMUDHG0CW/brkkEp8mzqk2+ODEitlw=
github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU=
github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc=
github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I=
github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M=
github.com/emirpasic/gods v1.12.0 h1:QAUIPSaCu4G+POclxeqb3F+WPpdKqFGlw36+yOzGlrg=
@ -515,11 +520,16 @@ github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRW
github.com/nacos-group/nacos-sdk-go/v2 v2.2.5 h1:r0wwT7PayEjvEHzWXwr1ROi/JSqzujM4w+1L5ikThzQ=
github.com/nacos-group/nacos-sdk-go/v2 v2.2.5/go.mod h1:OObBon0prVJVPoIbSZxpEkFiBfL0d1LcBtuAMiNn+8c=
github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg=
github.com/nats-io/jwt v0.3.2 h1:+RB5hMpXUUA2dfxuhBTEkMOrYmM+gKIZYS1KjSostMI=
github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU=
github.com/nats-io/nats-server/v2 v2.1.2 h1:i2Ly0B+1+rzNZHHWtD4ZwKi+OU5l+uQo1iDHZ2PmiIc=
github.com/nats-io/nats-server/v2 v2.1.2/go.mod h1:Afk+wRZqkMQs/p45uXdrVLuab3gwv3Z8C4HTBu8GD/k=
github.com/nats-io/nats.go v1.9.1 h1:ik3HbLhZ0YABLto7iX80pZLPw/6dx3T+++MZJwLnMrQ=
github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w=
github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
github.com/nats-io/nkeys v0.1.3 h1:6JrEfig+HzTH85yxzhSVbjHRJv9cn0p6n3IngIcM5/k=
github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo=
github.com/neelance/sourcemap v0.0.0-20200213170602-2833bce08e4c/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM=
@ -560,6 +570,7 @@ github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtP
github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac=
github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc=
github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I=
github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
@ -605,6 +616,7 @@ github.com/qit-team/snow-core v0.1.28 h1:RrX7i6GLbcMMSVzAT1lXgS/S3M2b1OrAnsoPaRG
github.com/qit-team/snow-core v0.1.28/go.mod h1:J9CNj6P2IRh72yVa7rut4T8ikq/4DjaisLqXZy40TNg=
github.com/qit-team/work v0.3.11 h1:AAtLTCOJ01WMFcvviK9rDGhHzaHE3bvunMOnSZ/80k8=
github.com/qit-team/work v0.3.11/go.mod h1:h5m1cZjn+BznChuAyMiR/+IUyWEmaMylPKRhq/AlxKw=
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a h1:9ZKAASQSHhDYGoxY8uLVpewe1GDZ2vu2Tr/vTdVAkFQ=
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
@ -658,6 +670,7 @@ github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns=
github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271 h1:WhxRHzgeVGETMlmVfqhRn8RIeeNoPr2Czh33I4Zdccw=
github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@ -690,6 +703,8 @@ github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JT
github.com/tidwall/pretty v0.0.0-20190325153808-1166b9ac2b65/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho=
github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE=
github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
@ -767,6 +782,7 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
@ -849,6 +865,7 @@ golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=

View File

@ -2,15 +2,14 @@ package rpc
import (
"github.com/qit-team/snow-core/kernel/server"
__ "qteam/rpc/user"
)
func StartRpc() error {
go (&__.UserServer{}).StartServer()
//go (&__.UserServer{}).StartServer()
//等待停止信号
server.WaitStop()
return nil
}

View File

@ -1,42 +1,43 @@
package __
import (
"context"
"google.golang.org/grpc"
"log"
"net"
"qteam/app/utils"
"qteam/config"
)
// 服务定义
type UserServer struct{}
func (s *UserServer) GetUserByStuNumber(ctx context.Context, request *UserRequest) (*UserResponse, error) {
return &UserResponse{}, nil
}
func (s *UserServer) mustEmbedUnimplementedUserServiceServer() {
//TODO implement me
//panic("implement me")
}
func (s *UserServer) StartServer() *grpc.Server {
server := grpc.NewServer()
//注册服务
RegisterUserServiceServer(server, &UserServer{})
//启动监听程序
listener, err := net.Listen("tcp", config.GetConf().Rpc.User)
if err != nil {
log.Fatal("启动监听失败", err)
}
err = server.Serve(listener)
if err != nil {
log.Fatal("启动服务失败", err)
}
utils.Log(nil, "服务启动成功", config.GetConf().Rpc.User)
return server
}
//
//import (
// "context"
// "google.golang.org/grpc"
// "log"
// "net"
// "qteam/app/utils"
// "qteam/config"
//)
//
//// 服务定义
//type UserServer struct{}
//
//func (s *UserServer) GetUserByStuNumber(ctx context.Context, request *UserRequest) (*UserResponse, error) {
// return &UserResponse{}, nil
//}
//
//func (s *UserServer) mustEmbedUnimplementedUserServiceServer() {
// //TODO implement me
// //panic("implement me")
//}
//func (s *UserServer) StartServer() *grpc.Server {
//
// server := grpc.NewServer()
//
// //注册服务
// RegisterUserServiceServer(server, &UserServer{})
// //启动监听程序
// listener, err := net.Listen("tcp", config.GetConf().Rpc.User)
// if err != nil {
// log.Fatal("启动监听失败", err)
// }
//
// err = server.Serve(listener)
//
// if err != nil {
// log.Fatal("启动服务失败", err)
// }
// utils.Log(nil, "服务启动成功", config.GetConf().Rpc.User)
// return server
//}