go-component

module
v0.0.0-...-f6269ad Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2024 License: MIT

README

go-component

介绍

go语言的常用小工具。

软件架构

  1. http_respnse是常见的http返回值类型,用户web框架的数据,保护gin,hertz等。
  2. nacos_serve是获取nacos配置的工具包。
  3. qrcode生成二维码。
  4. xlog go原生日志封装版
  5. rwlokc redis读写锁

安装教程

  1. 本地环境安装
  1. 远程调用 远程调用使用go get方法,这里需要定位到确切的工具库如xlog,到达存放源文件目录即可。
  • go get gitee.com/gitee/gitee-component/xlog即可略。

使用说明

http_respnse

http_respnse工具库,封装了http返回值类型,方便web框架使用。

  1. 请求参数

在http请求时数据在请求行和请求头则不需要特殊的数据结构接受数据,当数据在请求体中时就需要相对应的结构体接收。根据实际定义即可。

  1. 返回参数

在http请求时,返回数据都是通过相应结构体返回数据的,浏览器通过响应体获取数据。同一个服务响应体数据结构应该一致。

一般情况下,返回数据需要如下参数:

  • 响应状态码
  • 响应数据
  • 响应消息
  • 是否成功标识

转化go结构体如下:

// Response 返回参数
type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
	Success bool        `json:"success"`
}
  1. 返回数据携带分页

对于返回为列表的数据,需要携带分页参数,除了数据之外,还需要数据总数,是否有上一下页,是否有下一页。

转化为go结构体为:

type Page struct {
	Data    interface{} `json:"data,omitempty"`
	Total   int64       `json:"total,omitempty"`
	HasNext bool        `json:"has_next,omitempty"`
	HasPrev bool        `json:"has_prev,omitempty"`
}

整体结合,分页响应数据Page作为响应体Response的Data字段的值。

  1. 案例
type User struct {
    Id      int64  `json:"id"`
    Name    string `json:"name"`
    Age     int64  `json:"age"`
    Sex     string `json:"sex"`
    Address string `json:"address"`
}
var users []User = []User{
    User{
        Id:      1,
        Name:    "张三",
        Age:     18,
        Sex:     "男",
        Address: "北京",
    },
    User{
        Id:      2,
        Name:    "李四",
        Age:     19,
        Sex:     "女",
        Address: "上海",
    },
    User{
        Id:      3,
        Name:    "王五",
        Age:     20,
        Sex:     "男",
        Address: "深圳",
    },
    User{
        Id:      4,
        Name:    "张三",
        Age:     28,
        Sex:     "男",
        Address: "北京",
    },
    User{
        Id:      5,
        Name:    "张三",
        Age:     19,
        Sex:     "女",
        Address: "南通",
    },
    User{
        Id:      6,
        Name:    "张三",
        Age:     31,
        Sex:     "男",
        Address: "成都",
    },
}

var userTmp = make([]User, 0)
for _, v := range users {
    if v.Name == "张三" {
        userTmp = append(userTmp, v)
    }
}

// 列表查询需要分页使用Page类型
var page = NewPageData(1, 10, int64(len(userTmp)), userTmp)
fmt.Printf("分页查询数据%v\n", page)


var userTmp1 = User{}
for _, v := range users {
    if v.Id == 2 {
        userTmp1 = v
    }
}
var userResp = NewSuccessResponse(200, "查询成功", userTmp1)
fmt.Printf("查询数据%v\n", userResp)

img.png

  1. 使用

go get gitee.com/gitee/gitee-component/http_respnse

nacos_serve

nacos_serve工具库,封装了nacos配置的工具包。

  1. 本地naocos配置

DeafultNacosConfig(username, password, namespaceId, ipAddr, scheme string, port uint64, dataId, group string) NacosConfig

此方法用于生成默认的配置,其中需要经常变更的由参数传递。

func DeafultNacosConfig(username, password, namespaceId, ipAddr, scheme string, port uint64, dataId, group string) NacosConfig {
	return NacosConfig{
		Client: ClientConfig{
			NamespaceId:         namespaceId,
			TimeoutMs:           5000,
			NotLoadCacheAtStart: true,
			LogDir:              "tmp/nacos/log",
			CacheDir:            "tmp/nacos/cache",
			LogLevel:            "debug",
			Username:            username,
			Password:            password,
		},
		Server: ServerConfig{
			IpAddr:      ipAddr,
			Port:        port,
			Scheme:      scheme,
			ContextPath: "/nacos",
		},
		Param: ClientParam{
			DataId: dataId,
			Group:  group,
		},
	}
}
  1. 获取远程配置

GetRemoteConfig[T any](config NacosConfig, param T) (T, error)

此方法用户获取远程配置T配置类,方法返回配置类型的实例,形参为nacos配置类变量,和需求配置类。例如:

type MySQLConfig struct {
    DSN string `yaml:"dsn"`
}

type RedisConfig struct {
    Address  string `yaml:"address"`
    Username string `yaml:"username"`
    Password string `yaml:"password"`
    DB       int    `yaml:"db"`
}

type HertzConfig struct {
    Address         string `yaml:"address"`
    EnablePprof     bool   `yaml:"enable_pprof"`
    EnableGzip      bool   `yaml:"enable_gzip"`
    EnableAccessLog bool   `yaml:"enable_access_log"`
    LogLevel        string `yaml:"log_level"`
    LogFileName     string `yaml:"log_file_name"`
    LogMaxSize      int    `yaml:"log_max_size"`
    LogMaxBackups   int    `yaml:"log_max_backups"`
    LogMaxAge       int    `yaml:"log_max_age"`
}

type ApiConfig struct {
    Env string

    Hertz HertzConfig `yaml:"hertz"`
    MySQL MySQLConfig `yaml:"mysql"`
    Redis RedisConfig `yaml:"redis"`
}
nc := nacosserve.DeafultNacosConfig("nacos", "nacos", "service_foodplatform", "192.168.5.128", "http", 8848, "commodity_api", "dev.food_platform")
var conf ApiConfig
ac, err := nacosserve.GetRemoteConfig[ApiConfig](nc, conf)
if err != nil {
    fmt.Println(err)
    t.Error(err)
    return
}
fmt.Println(ac)

返回的ac类型为ApiConfig,并获取了远程值。

QR-code

生成二维码工具安装:

go get gitee.com/gitee/gitee-component/qr_code

github源码

  1. 下载工具包

go get -u github.com/skip2/go-qrcode/...

  1. 引入工具包

import qrcode "github.com/skip2/go-qrcode"

  1. 使用
参数 说明
WriteFile 将二维码内容写入文件
WriteColorFile 将二维码内容写入文件并设置颜色
New 生成二维码
NewWithForceVersion 生成二维码并设置强制版本号
Encode 生成二维码内容返回字节数组
  • WriteFile
err := qrcode.WriteFile("https://www.baidu.com", qrcode.Medium, 256, "../img/qr.png")
if err != nil {
    panic(err)
}

func WriteFile(content string, level RecoveryLevel, size int, filename string) error

参数依次是:二维码内容,容错级别,二维码大小,文件名

二维码如果是网址用社交app扫码会自动打开网站。

xlog

xlog封装了go官方的log包,使用起来更加方便。

安装:go get gitee.com/gitee/gitee-component/xlog

无需实例化直接使用即可:

xlog.GoLogger.InfoF("信息")
xlog.GoLogger.WarnF("警告")
xlog.GoLogger.ErrorF("错误提示,程序不会停止")
xlog.GoLogger.FatalF("错误提示,程序会停止")

SetLogPath方法用户存储日志到文件中。其参数为绝对地址,最后一个/表示日志文件名称,如果是相对地址测绘在当前文件夹下生成日志文件。

xlog.SetLogPath("/Users/xxx/yyy") // xxx存在,yyy为文件名
xlog.SetLogPath("xxx/yyy")  // xxx为当前文件下的文件夹,yyy为文件名
rwlock

使用redis模拟互斥锁,原理是在redis数据库生成唯一键,当该建存在时表示上锁,过期或删除表示解锁。

Lock(name string) (error, *string)

对同一数据使用uuid唯一标识上锁,name一致标识同一数据,对数据操作时首先要上锁,程序会自动检测是否已锁,已锁会报错locking.

Unlock(name string, uid string) error

解锁会删除redis缓存,表示对该数据的解锁,传入的uid为上锁的标识,标识一致才可以解锁,自己上锁自己解锁,不能交叉,未解锁的有10秒的周期会自动解锁。

参与贡献

  1. Fork 本仓库
  2. 新建 Feat_xxx 分支
  3. 提交代码
  4. 新建 Pull Request

特技

  1. 使用 Readme_XXX.md 来支持不同的语言,例如 Readme_en.md, Readme_zh.md
  2. Gitee 官方博客 blog.gitee.com
  3. 你可以 https://gitee.com/explore 这个地址来了解 Gitee 上的优秀开源项目
  4. GVP 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
  5. Gitee 官方提供的使用手册 https://gitee.com/help
  6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 https://gitee.com/gitee-stars/

Directories

Path Synopsis
nacos_serve

Jump to

Keyboard shortcuts

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