新增部分注释

This commit is contained in:
chenjiekun
2021-09-01 18:16:27 +08:00
parent 147b15bc15
commit 7cfb807bf6
15 changed files with 100 additions and 84 deletions

View File

@@ -15,6 +15,7 @@ import (
store_memory "github.com/eolinker/goku/store-memory"
)
//Register 注册各类驱动工厂
func Register() {
storeRegister()

View File

@@ -6,29 +6,32 @@ import (
"path/filepath"
"plugin"
)
//RegisterFunc 注册函数
type RegisterFunc func()
func loadPlugins(dir string)error {
func loadPlugins(dir string) error {
files, err := filepath.Glob(fmt.Sprintf("%s/*.so", dir))
if err!= nil{
if err != nil {
return err
}
for _,f:=range files{
for _, f := range files {
p, err := plugin.Open(f)
if err!= nil{
log.Errorf("error to open plugin %s:%s",f,err.Error())
if err != nil {
log.Errorf("error to open plugin %s:%s", f, err.Error())
continue
}
r, err := p.Lookup("Register")
if err!= nil{
log.Errorf("call register from plugin : %s : %s",f,err.Error())
if err != nil {
log.Errorf("call register from plugin : %s : %s", f, err.Error())
continue
}
r.(RegisterFunc)()
}
return nil
}
}

View File

@@ -1,5 +1,6 @@
package jwt
//Config JWT实例配置
type Config struct {
Name string `json:"name"`
Driver string `json:"driver"`
@@ -14,6 +15,7 @@ type jwtUsers struct {
credentials []JwtCredential
}
//JwtCredential JWT验证信息
type JwtCredential struct {
Iss string `json:"iss"`
Secret string `json:"secret"`

View File

@@ -20,13 +20,13 @@ import (
)
type jwtToken struct {
Token string
Header_64 string
Claims_64 string
Signature_64 string
Header map[string]interface{}
Claims map[string]interface{}
Signature string
Token string
Header64 string
Claims64 string
Signature64 string
Header map[string]interface{}
Claims map[string]interface{}
Signature string
}
type signingMethod struct {
@@ -37,15 +37,15 @@ type signingMethod struct {
}
var (
ErrInvalidKey = errors.New("key is invalid")
ErrInvalidKeyType = errors.New("key is of invalid type")
ErrHashUnavailable = errors.New("the requested hash function is unavailable")
ErrSignatureInvalid = errors.New("signature is invalid")
ErrInvalidSigningMethod = errors.New("signing method is invalid")
ErrECDSAVerification = errors.New("crypto/ecdsa: verification error")
ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key")
ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key")
errInvalidKey = errors.New("key is invalid")
errInvalidKeyType = errors.New("key is of invalid type")
errHashUnavailable = errors.New("the requested hash function is unavailable")
errSignatureInvalid = errors.New("signature is invalid")
errInvalidSigningMethod = errors.New("signing method is invalid")
errECDSAVerification = errors.New("crypto/ecdsa: verification error")
errKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
errNotRSAPublicKey = errors.New("Key is not a valid RSA public key")
errNotECPublicKey = errors.New("Key is not a valid ECDSA public key")
)
func newSigningMethod(name string) *signingMethod {
@@ -80,7 +80,7 @@ func (m *signingMethod) Verify(signingString, signature string, key interface{})
// Verify the key is the right type
keyBytes, ok := key.([]byte)
if !ok {
return ErrInvalidKeyType
return errInvalidKeyType
}
// Decode signature, for comparison
@@ -91,7 +91,7 @@ func (m *signingMethod) Verify(signingString, signature string, key interface{})
// Can we use the specified hashing method?
if !m.Hash.Available() {
return ErrHashUnavailable
return errHashUnavailable
}
// This signing method is symmetric, so we validate the signature
@@ -100,7 +100,7 @@ func (m *signingMethod) Verify(signingString, signature string, key interface{})
hasher := hmac.New(m.Hash.New, keyBytes)
hasher.Write([]byte(signingString))
if !hmac.Equal(sig, hasher.Sum(nil)) {
return ErrSignatureInvalid
return errSignatureInvalid
}
// No validation errors. Signature is good.
@@ -120,12 +120,12 @@ func (m *signingMethod) Verify(signingString, signature string, key interface{})
var ok bool
if rsaKey, ok = key.(*rsa.PublicKey); !ok {
return ErrInvalidKeyType
return errInvalidKeyType
}
// Create hasher
if !m.Hash.Available() {
return ErrHashUnavailable
return errHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
@@ -149,11 +149,11 @@ func (m *signingMethod) Verify(signingString, signature string, key interface{})
case *ecdsa.PublicKey:
ecdsaKey = k
default:
return ErrInvalidKeyType
return errInvalidKeyType
}
if len(sig) != 2*m.KeySize {
return ErrECDSAVerification
return errECDSAVerification
}
r := big.NewInt(0).SetBytes(sig[:m.KeySize])
@@ -161,7 +161,7 @@ func (m *signingMethod) Verify(signingString, signature string, key interface{})
// Create hasher
if !m.Hash.Available() {
return ErrHashUnavailable
return errHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
@@ -169,14 +169,12 @@ func (m *signingMethod) Verify(signingString, signature string, key interface{})
// Verify the signature
if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true {
return nil
} else {
return ErrECDSAVerification
}
return errECDSAVerification
}
default:
{
return ErrInvalidSigningMethod
}
return errInvalidSigningMethod
}
}
@@ -186,7 +184,7 @@ func (m *signingMethod) Sign(signingString string, key interface{}) (string, err
{
if keyBytes, ok := key.([]byte); ok {
if !m.Hash.Available() {
return "", ErrHashUnavailable
return "", errHashUnavailable
}
hasher := hmac.New(m.Hash.New, keyBytes)
@@ -195,7 +193,7 @@ func (m *signingMethod) Sign(signingString string, key interface{}) (string, err
return encodeSegment(hasher.Sum(nil)), nil
}
return "", ErrInvalidKeyType
return "", errInvalidKeyType
}
case "RS256", "RS384", "RS512":
{
@@ -204,12 +202,12 @@ func (m *signingMethod) Sign(signingString string, key interface{}) (string, err
// Validate type of key
if rsaKey, ok = key.(*rsa.PrivateKey); !ok {
return "", ErrInvalidKey
return "", errInvalidKey
}
// Create the hasher
if !m.Hash.Available() {
return "", ErrHashUnavailable
return "", errHashUnavailable
}
hasher := m.Hash.New()
@@ -230,12 +228,12 @@ func (m *signingMethod) Sign(signingString string, key interface{}) (string, err
case *ecdsa.PrivateKey:
ecdsaKey = k
default:
return "", ErrInvalidKeyType
return "", errInvalidKeyType
}
// Create the hasher
if !m.Hash.Available() {
return "", ErrHashUnavailable
return "", errHashUnavailable
}
hasher := m.Hash.New()
@@ -246,12 +244,12 @@ func (m *signingMethod) Sign(signingString string, key interface{}) (string, err
curveBits := ecdsaKey.Curve.Params().BitSize
if m.CurveBits != curveBits {
return "", ErrInvalidKey
return "", errInvalidKey
}
keyBytes := curveBits / 8
if curveBits%8 > 0 {
keyBytes += 1
keyBytes++
}
// We serialize the outpus (r and s) into big-endian byte arrays and pad
@@ -274,7 +272,7 @@ func (m *signingMethod) Sign(signingString string, key interface{}) (string, err
}
default:
{
return "", ErrInvalidSigningMethod
return "", errInvalidSigningMethod
}
}
}
@@ -300,14 +298,14 @@ func encodeSegment(seg []byte) string {
return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
}
// Parse PEM encoded PKCS1 or PKCS8 public key
//ParseRSAPublicKeyFromPEM Parse PEM encoded PKCS1 or PKCS8 public key
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, ErrKeyMustBePEMEncoded
return nil, errKeyMustBePEMEncoded
}
// Parse the key
@@ -323,20 +321,20 @@ func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
var pkey *rsa.PublicKey
var ok bool
if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
return nil, ErrNotRSAPublicKey
return nil, errNotRSAPublicKey
}
return pkey, nil
}
// Parse PEM encoded PKCS1 or PKCS8 public key
//ParseECPublicKeyFromPEM Parse PEM encoded PKCS1 or PKCS8 public key
func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, ErrKeyMustBePEMEncoded
return nil, errKeyMustBePEMEncoded
}
// Parse the key
@@ -352,7 +350,7 @@ func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
var pkey *ecdsa.PublicKey
var ok bool
if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok {
return nil, ErrNotECPublicKey
return nil, errNotECPublicKey
}
return pkey, nil
@@ -377,9 +375,9 @@ func tokenize(token string) []string {
parts := strings.Split(token, ".")
if len(parts) == 3 {
return parts
} else {
return nil
}
return nil
}
// 解析token将token信息解析为jwtToken对象
@@ -388,27 +386,27 @@ func decodeToken(token string) (*jwtToken, error) {
if tokenParts == nil {
return nil, errors.New("[jwt_auth] Invalid token")
}
header_64 := tokenParts[0]
claims_64 := tokenParts[1]
signature_64 := tokenParts[2]
header64 := tokenParts[0]
claims64 := tokenParts[1]
signature64 := tokenParts[2]
var header, claims map[string]interface{}
var signature string
header_d64, err := b64Decode(header_64)
headerD64, err := b64Decode(header64)
if err != nil {
return nil, errors.New("[jwt_auth] Invalid base64 encoded JSON")
}
if err = json.Unmarshal([]byte(header_d64), &header); err != nil {
if err = json.Unmarshal([]byte(headerD64), &header); err != nil {
return nil, errors.New("[jwt_auth] Invalid JSON")
}
claims_d64, err := b64Decode(claims_64)
claimsD64, err := b64Decode(claims64)
if err != nil {
return nil, errors.New("[jwt_auth] Invalid base64 encoded JSON")
}
if err = json.Unmarshal([]byte(claims_d64), &claims); err != nil {
if err = json.Unmarshal([]byte(claimsD64), &claims); err != nil {
return nil, errors.New("[jwt_auth] Invalid JSON")
}
signature, err = b64Decode(signature_64)
signature, err = b64Decode(signature64)
if err != nil {
return nil, errors.New("[jwt_auth] Invalid base64 encoded JSON")
}
@@ -424,7 +422,7 @@ func decodeToken(token string) (*jwtToken, error) {
if len(signature) == 0 {
return nil, errors.New("[jwt_auth] Invalid signature")
}
return &jwtToken{Token: token, Header_64: header_64, Claims_64: claims_64, Signature_64: signature_64, Header: header, Claims: claims, Signature: signature}, nil
return &jwtToken{Token: token, Header64: header64, Claims64: claims64, Signature64: signature64, Header: header, Claims: claims, Signature: signature}, nil
}
//verifySignature 验证签名
@@ -454,10 +452,10 @@ func verifySignature(token *jwtToken, key string) error {
}
default:
{
return ErrInvalidSigningMethod
return errInvalidSigningMethod
}
}
return newSigningMethod(token.Header["alg"].(string)).Verify(token.Header_64+"."+token.Claims_64, token.Signature_64, k)
return newSigningMethod(token.Header["alg"].(string)).Verify(token.Header64+"."+token.Claims64, token.Signature64, k)
}
//verifyRegisteredClaims 验证签发字段

View File

@@ -47,8 +47,8 @@ func (c *client) GetNodeList(serviceName string) (discovery.Nodes, error) {
"marked": strconv.FormatBool(host.Marked),
"weight": strconv.FormatFloat(host.Weight, 'f', -1, 64),
}
if _, exist := nodes[host.InstanceId]; !exist {
node := discovery.NewNode(label, host.InstanceId, host.Ip, host.Port, "")
if _, exist := nodes[host.InstanceID]; !exist {
node := discovery.NewNode(label, host.InstanceID, host.IP, host.Port, "")
nodes[node.ID()] = node
}
}
@@ -62,13 +62,13 @@ func (c *client) GetNodeList(serviceName string) (discovery.Nodes, error) {
//GetInstanceList 获取目标地址指定服务名的实例列表
func (c *client) GetInstanceList(addr string, serviceName string) (*Instance, error) {
addr = addr + instancePath
paramsUrl := c.params
paramsUrl.Set("serviceName", serviceName)
paramsURL := c.params
paramsURL.Set("serviceName", serviceName)
req, err := http.NewRequest("GET", addr, nil)
if err != nil {
return nil, err
}
req.URL.RawQuery = paramsUrl.Encode()
req.URL.RawQuery = paramsURL.Encode()
response, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err

View File

@@ -27,14 +27,14 @@ type nacos struct {
locker sync.RWMutex
}
// nacos 服务实例结构
//Instance nacos 服务实例结构
type Instance struct {
Hosts []struct {
Valid bool `json:"valid"`
Marked bool `json:"marked"`
InstanceId string `json:"instanceId"`
InstanceID string `json:"instanceId"`
Port int `json:"port"`
Ip string `json:"ip"`
IP string `json:"ip"`
Weight float64 `json:"weight"`
}
}

View File

@@ -19,7 +19,7 @@ import (
const name = "static"
var (
ErrorStructType = errors.New("error struct type")
errorStructType = errors.New("error struct type")
)
type static struct {
@@ -48,7 +48,7 @@ func (s *static) Start() error {
func (s *static) Reset(conf interface{}, workers map[eosc.RequireId]interface{}) error {
cfg, ok := conf.(*Config)
if !ok {
return fmt.Errorf("need %s,now %s:%w", eosc.TypeNameOf((*Config)(nil)), eosc.TypeNameOf(conf), ErrorStructType)
return fmt.Errorf("need %s,now %s:%w", eosc.TypeNameOf((*Config)(nil)), eosc.TypeNameOf(conf), errorStructType)
}
s.scheme = cfg.getScheme()
if cfg.Health == nil {

View File

@@ -7,7 +7,7 @@ import (
"encoding/base64"
)
//对明文进行填充
//Padding 对明文进行填充
func Padding(plainText []byte, blockSize int) []byte {
//计算要填充的长度
n := blockSize - len(plainText)%blockSize
@@ -17,7 +17,7 @@ func Padding(plainText []byte, blockSize int) []byte {
return plainText
}
//对密文删除填充
//UnPadding 对密文删除填充
func UnPadding(cipherText []byte) []byte {
//取出密文最后一个字节end
end := cipherText[len(cipherText)-1]
@@ -26,7 +26,7 @@ func UnPadding(cipherText []byte) []byte {
return cipherText
}
//AEC加密CBC模式
//AES_CBC_Encrypt AEC加密CBC模式
func AES_CBC_Encrypt(plainText []byte, key []byte) string {
//指定加密算法返回一个AES算法的Block接口对象
block, err := aes.NewCipher(key)
@@ -47,7 +47,7 @@ func AES_CBC_Encrypt(plainText []byte, key []byte) string {
return base64.StdEncoding.EncodeToString(cipherText)
}
//AEC解密CBC模式
//AES_CBC_Decrypt AEC解密CBC模式
func AES_CBC_Decrypt(data string, key []byte) []byte {
cipherText, err := base64.StdEncoding.DecodeString(data)
if err != nil {

View File

@@ -2,6 +2,7 @@ package utils
import "os"
//GenFile 根据路径和数据生成文件
func GenFile(dir, fileName, data string) error {
dir = "work/export/" + dir
err := os.MkdirAll(dir, os.ModePerm)

View File

@@ -85,7 +85,7 @@ func Md5(encodeString string) string {
return hex.EncodeToString(h.Sum(nil)) // 输出加密结果
}
//GetRandomString 生成随机字符串
//GetRandomStringBack 生成随机字符串
func GetRandomStringBack(num int) string {
str := "123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"
bytes := []byte(str)
@@ -150,6 +150,7 @@ func GetMac() (bool, string) {
return false, ""
}
//GzipCompress 转成Gzip
func GzipCompress(origin []byte) ([]byte, error) {
var b bytes.Buffer
gz := gzip.NewWriter(&b)

View File

@@ -10,7 +10,7 @@ import (
var (
locker = sync.Mutex{}
lastId int64
lastID int64
start int64
)
@@ -19,17 +19,21 @@ func init() {
s, _ := time.Parse("2020-01-02T15:04:05Z07:00", time.RFC3339)
start = s.UnixNano()
}
//GenerateID 生成id
func GenerateID() int64 {
id := time.Now().UnixNano() - start
locker.Lock()
defer locker.Unlock()
for id <= lastId {
for id <= lastID {
id++
}
lastId = id
lastID = id
return id
}
//GenerateIDString 生成id字符串
func GenerateIDString() string {
id := GenerateID()
data := make([]byte, 8)

View File

@@ -5,6 +5,7 @@ import (
"strings"
)
//HeaderToString 将header转成字符串
func HeaderToString(h http.Header) string {
if h == nil {
return ""

View File

@@ -6,6 +6,7 @@ import (
"encoding/hex"
)
//HMacBySha256 HMacBySha256
func HMacBySha256(key, toSign string) string {
hash := hmac.New(sha256.New, []byte(key)) // 创建对应的sha256哈希加密算法
hash.Write([]byte(toSign)) // 写入加密数据
@@ -13,6 +14,7 @@ func HMacBySha256(key, toSign string) string {
return hex.EncodeToString(hash.Sum(nil))
}
//HexEncode HexEncode
func HexEncode(body []byte) string {
h := sha256.New()
h.Write(body)

View File

@@ -19,7 +19,9 @@ func JSObjectToJSON(s string) ([]byte, error) {
}
return []byte(v.String()), nil
}
func JsonUnmarshal(s, v interface{}) error {
//JSONUnmarshal 将json格式的s解码成v所需的json格式
func JSONUnmarshal(s, v interface{}) error {
data, err := json.Marshal(s)
if err != nil {
return err

View File

@@ -2,6 +2,7 @@ package utils
import "encoding/json"
//MustSliceString 断言输入的参数为字符串切片
func MustSliceString(v interface{}) ([]string, error) {
data, err := json.Marshal(v)