miniutils

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2022 License: MIT Imports: 24 Imported by: 17

README

Go实用小工具

为提高开发效率封装了一些实用工具、函数集,不依赖第三方库。 简单易用,拿来做Golang入门练习也不错。

示例

JWT 工具

JWT: https://jwt.io/

package main

import (
	"fmt"
	"log"
	"time"
	"github.com/iotames/miniutils"
)
func main() {
	secret := miniutils.GetRandString(32) // 设置JWT签名密钥
	jwt := miniutils.NewJwt(secret) // 初始化JWT小工具
	jwtInfo := map[string]interface{}{"id": 1519512704946016256, "name": "Harvey", "age": 16, "mobile": "15988888888"}
	tokenStr, err := jwt.Create(jwtInfo, time.Second*3600) // 设置原始数据jwtInfo,有效期3600秒,创建JWT字符串tokenStr
	if err != nil {
		fmt.Printf("jwt.Create error: %v", err)
        return
	}
	log.Println("create JWT:", tokenStr)
	info, err := miniutils.NewJwt("").Decode(tokenStr) // 解码 JWT 字符串. 返回 map[string]interface{} 格式的数据。
	if err != nil {
		fmt.Printf("jwt.Decode error: %v", err)
        return
	}
	log.Println("jwt Decode:", info)

	claims, err := jwt.Parse(tokenStr) // 解码 JWT 字符串并验签,验证有效期。 返回 map[string]interface{} 格式的数据。
	if err != nil {
		fmt.Printf("jwt.Parse error: %v", err)
        return
	}
	log.Println("jwt Parse:", claims)
    
    _, err = jwt.Parse(tokenStr + "sign error")
	if err == miniutils.ErrTokenSign {
		fmt.Printf("JWT 签名错误")
	}
}

日志记录

	logger := miniutils.GetLogger("")
	logger.Debug("first log 11111")
	logger.Info("second log 22222")
	logger = miniutils.NewLogger("runtime/mylogs")
	logger.Debug("my logs 2333")
	logger.CloseLogFile()

字符串提取工具

    strfind := miniutils.NewStrfind("https://d.168.com/offer/356789.html")
	dofind := strfind.SetRegexp(`offer/(\d+)\.html`).DoFind()
	offerCode := dofind.GetOne(false)
	allstr := dofind.GetOne(true)
	fmt.Println(offerCode) // "356789"
	fmt.Println(allstr) // "offer/356789.html"

Documentation

Index

Constants

View Source
const (
	LOG_LEVEL_DEBUG = 0
	LOG_LEVEL_INFO  = 1
	LOG_LEVEL_WARN  = 2
	LOG_LEVEL_ERROR = 3
)

Variables

View Source
var (
	ErrTokenFormat  = errors.New("token is not a JWT")
	ErrTokenExpired = errors.New("token is expired")
	ErrTokenSign    = errors.New("token sign error")
)

Functions

func Base64UrlDecode

func Base64UrlDecode(seg string) ([]byte, error)

Base64UrlDecode Decode JWT specific base64url encoding with padding stripped

func Base64UrlEncode

func Base64UrlEncode(seg []byte) string

Base64UrlEncode Encode JWT specific base64url encoding with padding stripped

func CopyDir added in v1.0.2

func CopyDir(src string, dst string) error

CopyDir 复制整个目录到指定位置 copies a whole directory recursively

func CopyFile added in v1.0.2

func CopyFile(src, dst string) error

CopyFile 复制单个文件到指定位置(包含文件名)。copies a single file from src to dst

func GetBaseUrl added in v1.0.3

func GetBaseUrl(url string) string

GetBaseUrl. GetBaseUrl("https://www.baidu.com/hello?word=hiiii") -> "https://www.baidu.com" url must starwith http; return like: https://www.baidu.com

func GetDomainByUrl added in v1.0.3

func GetDomainByUrl(url string) string

GetDomainByUrl. 获取url网址的域名。 the arg url startwith http, //, / ; return like: "www.baidu.com", "baidu.com", ""

func GetFileSha256

func GetFileSha256(path string) (hash string, err error)

GetFileSha256 get SHA256 hash of file.

func GetJwtBySecret

func GetJwtBySecret(keyBytes []byte, bodyInfo map[string]interface{}) (string, error)

func GetKeywordByDomain added in v1.0.3

func GetKeywordByDomain(domain string) string

GetKeywordByDomain GetKeywordByDomain("www.baidu.com") -> baidu

func GetMapStringValue added in v1.0.3

func GetMapStringValue(key string, dictMap map[string]interface{}) string

func GetPidByPort added in v1.0.2

func GetPidByPort(portNumber int) int

GetPidByPort. 查找端口所属进程的PID。 返回端口号对应的进程PID,若没有找到相关进程,返回-1

func GetRandString

func GetRandString(l int) string

func GetSha256

func GetSha256(s string) string

GetSha256 get SHA256 hash. The len of SHA256 value is 64.

func GetSha256BySecret

func GetSha256BySecret(secret string, keyBytes []byte) []byte

GetSha256BySecret get SHA256 hash by Key

func GetUrl added in v1.0.3

func GetUrl(url, base string) string

GetUrl. 获取Url链接全路径。常用于爬虫链接格式化。例: Get("/product?id=90", "https://www.site.com") url: startwith http, /, // ; base must startwith http

func GetUrlQueryValue added in v1.0.3

func GetUrlQueryValue(key, url string) string

GetUrlQueryValue 提取网址的查询字符串。即问号之后的部分。

func IsPathExists added in v1.0.2

func IsPathExists(path string) bool

IsPathExists 判断文件或文件夹是否存在

func JsonDecodeUseNumber

func JsonDecodeUseNumber(infoBytes []byte, result interface{}) error

func KillPid added in v1.0.2

func KillPid(pid string) error

KillPid 杀死运行中的进程

func Md5

func Md5(s string) string

Md5 get the MD5 hash.

func Mkdir added in v1.0.2

func Mkdir(path string) error

Mkdir 创建目录

func ReadDir added in v1.0.2

func ReadDir(path string, callback func(fileinfo fs.FileInfo)) error

ReadDir 读取目录下的文件

func ReadFileToString added in v1.0.2

func ReadFileToString(path string) (string, error)

ReadFileString 读取文件内容

func ReplaceAllString added in v1.0.3

func ReplaceAllString(originalstr, oldstr, newstr string) string

func StartBrowserByUrl added in v1.0.2

func StartBrowserByUrl(url string) error

StartBrowserByUrl 打开系统默认浏览器

Types

type JsonWebToken

type JsonWebToken struct {
	TokenString string
	// contains filtered or unexported fields
}

func NewJwt

func NewJwt(secret string) *JsonWebToken

NewJwt init JsonWebToken by secret string

func (*JsonWebToken) Create

func (j *JsonWebToken) Create(claims map[string]interface{}, expiresin time.Duration) (token string, err error)

Create JsonWebToken string Create(map[string]interface{}{"id": 123456789, "username": "Harvey"}, time.Second*time.Duration(3600))

func (*JsonWebToken) Decode

func (j *JsonWebToken) Decode(jwtStr string) (segInfo map[string]interface{}, err error)

Decode reads the JsonWebToken string. Return the JWT decoded data.

func (*JsonWebToken) Parse

func (j *JsonWebToken) Parse(tokenStr string) (result map[string]interface{}, err error)

Decode reads the JsonWebToken string. Check the JWT decoded data and return.

type LogLevel added in v1.0.2

type LogLevel int

type Logger added in v1.0.2

type Logger struct {
	// contains filtered or unexported fields
}

func GetLogger added in v1.0.2

func GetLogger(dirpath string) *Logger

GetLogger 获取日志工具 logger:= GetLogger(""); logger.Debug("写一条日志111")

func NewLogger added in v1.0.2

func NewLogger(logsDir string) *Logger

TODO TO BE a global unique instance

func (*Logger) CloseLogFile added in v1.0.2

func (l *Logger) CloseLogFile()

func (*Logger) Debug added in v1.0.2

func (l *Logger) Debug(conent ...interface{})

func (*Logger) Error added in v1.0.2

func (l *Logger) Error(content ...interface{})

func (*Logger) Info added in v1.0.2

func (l *Logger) Info(content ...interface{})

func (*Logger) Warn added in v1.0.2

func (l *Logger) Warn(content ...interface{})

type Strfind added in v1.0.3

type Strfind struct {
	BodyStr string
	// contains filtered or unexported fields
}

func NewStrfind added in v1.0.3

func NewStrfind(bodyStr string) *Strfind

NewStrfind 字符串提取器。使用正则表达式从字符串中提取信息。

func (*Strfind) DoFind added in v1.0.3

func (s *Strfind) DoFind() *Strfind

func (*Strfind) GetAll added in v1.0.3

func (s *Strfind) GetAll(matchFull bool) []string

func (*Strfind) GetOne added in v1.0.3

func (s *Strfind) GetOne(matchFull bool) string

func (*Strfind) SetRegexp added in v1.0.3

func (s *Strfind) SetRegexp(rege string) *Strfind

SetRegexp 设置一个正则表达式。例:匹配数字 `(?s:(\d+))` OR `(\d+)`

func (*Strfind) SetRegexpBeginEnd added in v1.0.3

func (s *Strfind) SetRegexpBeginEnd(begin string, end string) *Strfind

re = regexp.MustCompile(`<script type=\"application/ld\+json\">(?s:(.+?))</script>`)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL