Skip to content

Releases: Fromsko/gouitls

v1.3.1

Choose a tag to compare

@Fromsko Fromsko released this 25 Nov 13:23

新增 redka 数据存储

一款使用 SQLite 制作的类 Redis 库,集成基础使用,但风格与 Redis 调用有些许区别

使用

  • 更新
go get -u github.com/Fromsko/gouitls
  • 使用
import (
	"testing"

	_ "github.com/mattn/go-sqlite3"
	"github.com/nalgeon/redka"
)

func TestRedDB(t *testing.T) {
	db := NewRedDB()

	db.Str().Set("name", "alice")
	db.Str().Set("age", 25)

	count, err := db.Key().Count("name", "age", "city")
	t.Log("count", "count", count, "err", err)
	name, err := db.Str().Get("name")
	t.Log("get", "name", name, "err", err)

	updCount := 0
	err = db.Update(func(tx *redka.Tx) error {
		err := tx.Str().Set("name", "bob")
		if err != nil {
			return err
		}
		updCount++
		err = tx.Str().Set("age", 50)
		if err != nil {
			return err
		}
		updCount++
		return nil
	})

	t.Log("updated", "count", updCount, "err", err)
	defer db.Close()
}

增添 V2 版本

Choose a tag to compare

@Fromsko Fromsko released this 15 Oct 13:14

新增 v2 版本

调用

func main(){
	// 适配器调用
	reqOne := v2.NewRequest(
		v2.WithURL("https://www.baidu.com"),
		v2.WithProxy("http://127.0.0.1:7890"),
		v2.WithMethod(http.MethodGet),
	)

	// 链式调用
	reqTwo := v2.NewRequest().
		WithURL("https://www.baidu.com").
		WithProxy("http://127.0.0.1:7890").
		WithMethod(http.MethodGet)

	reqOne.Send(func(resp v2.IResponse, err error) {
		// 接口实现
		resp.Bytes()        // []byte
		resp.Json()         // *gjson.Result
		resp.RaiseCode(200) // error
		resp.StatusCode()   // resp.code => 200
		resp.WriteFile("demo.txt", "0777", "")
		resp.WriteJson("demo.json", "0777", "")

		// 原始响应数据
		body := resp.(*v2.Response).Body
		contentTypeLen := resp.(*v2.Response).Resp.ContentLength
		fmt.Printf("body: %v\n", body)
		fmt.Printf("contentTypeLen: %v\n", contentTypeLen)
	})
}

新增两个接口

// IRequest 接口,定义请求的行为
type IRequest interface {
	WithURL(url string) IRequest
	WithMethod(method string) IRequest
	WithData(data io.Reader) IRequest
	WithForm(form url.Values) IRequest
	WithProxy(url string) IRequest
	WithCookies(cookies []*http.Cookie) IRequest
	WithHeaders(headers map[string]string) IRequest
	Send(callBack func(resp IResponse, err error))
}

// IResponse 接口,定义响应的行为
type IResponse interface {
	StatusCode() int
	Json() *gjson.Result
	Text() string
	Bytes() []byte
	RaiseCode(code int) error
	WriteFile(fileName, perm, dir string) error
	WriteJson(fileName, perm, dir string) error
}

v1.2.8

Choose a tag to compare

@Fromsko Fromsko released this 25 Jan 16:35
604c53f
package auth

import (
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/google/uuid"
)

type SubscriberAuth struct {
	Token      string        // Token
	Expiration time.Duration // 过期时间
	SecretKey  string        // 密钥
}

// GenToken 生成JWT token
func (sa *SubscriberAuth) GenToken(role, username string) (token string, err error) {
	// 创建一个新的令牌对象
	tk := jwt.New(jwt.SigningMethodHS256)

	// 设置令牌的claims
	claims := tk.Claims.(jwt.MapClaims)
	claims["username"] = username
	claims["role"] = role
	claims["exp"] = time.Now().Add(sa.Expiration).Unix()

	// 生成令牌
	token, err = tk.SignedString([]byte(sa.SecretKey))
	if err != nil {
		return "", err
	} else {
		sa.Token = token
	}
	return token, nil
}

// ValidateToken 验证和检查是否过期
func (sa *SubscriberAuth) ValidateToken(tokenString string) (bool, error) {
	// 解析令牌
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// 验证签名方法
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(sa.SecretKey), nil
	})

	if err != nil {
		return false, fmt.Errorf("token validation error: %v", err)
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		expirationTime := time.Unix(int64(claims["exp"].(float64)), 0)
		if time.Now().UTC().After(expirationTime) {
			return false, errors.New("token has expired")
		}
		fmt.Println("过期时间: ", expirationTime)
		return true, nil
	}

	return false, errors.New("invalid access token")
}

// GenUUID 生成UUID
func GenUUID(username string) string {
	ns := uuid.NameSpaceDNS
	userUUID := uuid.NewSHA1(ns, []byte(username))
	return userUUID.String()
}

// HashString 对内容进行 sha256
func HashString(input string) string {
	hasher := sha256.New()
	hasher.Write([]byte(input))
	hashedBytes := hasher.Sum(nil)
	hashedString := hex.EncodeToString(hashedBytes)
	return hashedString
}

v1.2.7

Choose a tag to compare

@Fromsko Fromsko released this 19 Jan 05:17
3494be2
// Succeed 正确数据
func Succeed(ctx *gin.Context, msg string, others ...gin.H) {
	rt := gin.H{
		"code": http.StatusOK,
		"msg":  msg,
	}

	if len(others) != 0 {
		for _, other := range others {
			for k, v := range other {
				rt[k] = v
			}
		}
	}

	ctx.JSON(http.StatusOK, rt)
}

// Failed 错误数据
func Failed(ctx *gin.Context, msg, err string, others ...gin.H) {
	rt := gin.H{
		"code": http.StatusOK,
		"msg":  msg,
		"err":  err,
	}

	if len(others) != 0 {
		for _, other := range others {
			for k, v := range other {
				rt[k] = v
			}
		}
	}

	ctx.JSON(rt["code"].(int), rt)
}

v1.2.6

Choose a tag to compare

@Fromsko Fromsko released this 19 Jan 05:02
44c6835
  • 采用指针类型来做函数可选式
  • 增加返回可选
  • 增加其他返回定义

v1.2.5

Choose a tag to compare

@Fromsko Fromsko released this 19 Jan 04:49
823ae62
// ReplyData 定义数据返回格式
func Client(ctx *gin.Context, jm *JsonMsg, opts ...Option) {
	if jm == nil {
		jm = &JsonMsg{}
		for _, opt := range opts {
			opt(*jm)
		}
	}

	if jm.flag {
		ctx.JSON(jm.Code, jm)
	} else {
		ctx.JSON(http.StatusOK, jm)
	}
}

v1.2.4

Choose a tag to compare

@Fromsko Fromsko released this 19 Jan 04:43
69c0aeb
// WithFlag 初始化标志位
func WithFlag(is bool) Option {
	return func(jm JsonMsg) {
		jm.flag = is
	}
}

v1.2.3

Choose a tag to compare

@Fromsko Fromsko released this 19 Jan 04:40
4768857
package reply

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// JsonMsg 通用返回格式
type JsonMsg struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Err  string `json:"err"`
	flag bool
}

// Option 函数选项式
type Option func(JsonMsg)

// WithMsg 返回数据
func WithMsg(msg string) Option {
	return func(jm JsonMsg) {
		jm.Msg = msg
	}
}

// WithErr 返回错误
func WithErr(err string) Option {
	return func(jm JsonMsg) {
		jm.Err = err
	}
}

// WithCode 返回状态码
func WithCode(code int) Option {
	return func(jm JsonMsg) {
		jm.Code = code
	}
}

// ReplyData 定义数据返回格式
func Client(ctx *gin.Context, opts ...Option) {
	c := &JsonMsg{}

	for _, opt := range opts {
		opt(*c)
	}

	if c.flag {
		ctx.JSON(c.Code, c)
	} else {
		ctx.JSON(http.StatusOK, c)
	}
}

v1.2.2

Choose a tag to compare

@Fromsko Fromsko released this 18 Jan 17:51
5de5798
import (
	"crypto/sha256"
	"encoding/hex"
)

// HashString 对内容进行 sha256
func HashString(input string) string {
	hasher := sha256.New()
	hasher.Write([]byte(input))
	hashedBytes := hasher.Sum(nil)
	hashedString := hex.EncodeToString(hashedBytes)
	return hashedString
}

v1.2.1

Choose a tag to compare

@Fromsko Fromsko released this 18 Jan 11:09
1e60705

修复 log/log.go 代码行数显示异常