Commit 3ad966b3 authored by 张瑜's avatar 张瑜

init

parents
.idea
.DS_Store
/storage/*
application-local.yaml
application.yaml
###### 环境依赖
开启GO111MODULE
###### 运行前
配置文件
cp application-local.yaml.example application-local.yaml
package appServer
import (
"fmt"
"github.com/kataras/iris/v12"
"xiaoxiong/internal/global"
)
type HomeClipboardRequest struct {
Message string `json:"message"`
}
type HomeClipboardResponse struct {
global.Response
}
func HomeClipboard(ctx iris.Context) {
//req := &HomeClipboardRequest{}
//resp := &HomeClipboardResponse{}
//if err := ctx.ReadJSON(req); err != nil {
// return
//}
//service.HomeClipboard(*req, *resp)
fmt.Println("asd")
}
# mysql connect configuration
mysql:
path: 'rm-uf6lzzal5v3fdj342co.mysql.rds.aliyuncs.com:3306'
config: 'charset=utf8mb4&parseTime=True&loc=Local'
db-name: 'xmx'
username: 'xmx'
password: '5DvHZO4^GGxvv%uUJ9'
max-idle-conns: 10
max-open-conns: 100
log-mode: false
log-zap: false
system:
debug: false
env: 'public'
addr: 8080
db-type: 'mysql'
# zap logger configuration
zap:
level: 'debug'
format: 'console'
prefix: ''
director: 'storage/logs'
link-name: 'latest_log'
show-line: true
encode-level: 'LowercaseLevelEncoder'
stacktrace-key: 'stacktrace'
log-in-console: true
redis:
db: 0
addr: 'testxmx1.redis.rds.aliyuncs.com:6379'
password: '1OeBZh83RmUoq88r'
package cmd
import (
"github.com/urfave/cli/v2"
"os"
"xiaoxiong/internal/global"
"xiaoxiong/internal/utils"
)
var app = &cli.App{
Name: "小熊有好货",
Usage: "xiaoxiong",
}
var c = cli.Commands{}
func Run(){
initApp()
app.Commands = c
err := app.Run(os.Args)
if err != nil {
panic(err)
}
}
// 初始化核心组件
func initApp(){
// 配置文件
_ = utils.Viper()
// log
global.Log = utils.Zap()
// 数据库
global.GORM = utils.GormInit()
// redis
global.Redis = utils.InitRedis()
}
\ No newline at end of file
package cmd
import (
"fmt"
"xiaoxiong/internal/global"
"xiaoxiong/routes"
"github.com/kataras/iris/v12"
"github.com/urfave/cli/v2"
)
func init(){
c = append(c, &cli.Command{
Name: "server",
Action: func(c *cli.Context) error {
app := iris.New()
routes.Router(app)
addr := fmt.Sprintf("%s:%d", global.CONFIG.System.Host,global.CONFIG.System.Addr) // 监听端口
err := app.Run(iris.Addr(addr))
if err != nil {
panic(err)
}
return nil
},
})
}
\ No newline at end of file
package config
type Config struct {
System System `mapstructure:"system" json:"system" yaml:"system"`
MySql MySql `mapstructure:"mysql" json:"mysql" yaml:"mysql"`
Zap Zap `mapstructure:"zap" json:"zap" yaml:"zap"`
Redis Redis `mapstructure:"redis" json:"redis" yaml:"redis"`
}
package config
type MySql struct {
Path string `mapstructure:"path" json:"path" yaml:"path"`
Config string `mapstructure:"config" json:"config" yaml:"config"`
Dbname string `mapstructure:"db-name" json:"dbname" yaml:"db-name"`
Username string `mapstructure:"username" json:"username" yaml:"username"`
Password string `mapstructure:"password" json:"password" yaml:"password"`
MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"`
MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"`
LogMode bool `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"`
LogZap bool `mapstructure:"log-zap" json:"logZap" yaml:"log-zap"`
}
package config
type Redis struct {
DB int `mapstructure:"db" json:"db" yaml:"db"`
Addr string `mapstructure:"addr" json:"addr" yaml:"addr"`
Password string `mapstructure:"password" json:"password" yaml:"password"`
}
package config
type System struct {
Debug bool `mapstructure:"debug" json:"debug" yaml:"debug"`
Env string `mapstructure:"env" json:"env" yaml:"env"`
Host string `mapstructure:"host" json:"host" yaml:"host"`
Addr int `mapstructure:"addr" json:"addr" yaml:"addr"`
DbType string `mapstructure:"db-type" json:"dbType" yaml:"db-type"`
OssType string `mapstructure:"oss-type" json:"ossType" yaml:"oss-type"`
UseMultipoint bool `mapstructure:"use-multipoint" json:"useMultipoint" yaml:"use-multipoint"`
ActivityDomain string `mapstructure:"activity-domain" json:"activityDomain" yaml:"activity-domain"`
Schema string `mapstructure:"schema" json:"schema" yaml:"schema"`
Jwt_signing_key string `mapstructure:"jwt_signing_key" json:"jwt_signing_key" yaml:"jwt_signing_key"`
Upload_path string `mapstructure:"upload_path" json:"upload_path" yaml:"upload_path"`
}
package config
type Zap struct {
Level string `mapstructure:"level" json:"level" yaml:"level"`
Format string `mapstructure:"format" json:"format" yaml:"format"`
Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"`
Director string `mapstructure:"director" json:"director" yaml:"director"`
LinkName string `mapstructure:"link-name" json:"linkName" yaml:"link-name"`
ShowLine bool `mapstructure:"show-line" json:"showLine" yaml:"showLine"`
EncodeLevel string `mapstructure:"encode-level" json:"encodeLevel" yaml:"encode-level"`
StacktraceKey string `mapstructure:"stacktrace-key" json:"stacktraceKey" yaml:"stacktrace-key"`
LogInConsole bool `mapstructure:"log-in-console" json:"logInConsole" yaml:"log-in-console"`
}
module xiaoxiong
go 1.16
require (
github.com/ajg/form v1.5.1 // indirect
github.com/casbin/casbin v1.9.1
github.com/casbin/gorm-adapter v1.0.0
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/geiqin/thirdparty v1.0.8
github.com/go-redis/redis v6.15.9+incompatible
github.com/go-sql-driver/mysql v1.6.0
github.com/google/go-querystring v1.1.0 // indirect
github.com/imkira/go-interpol v1.1.0 // indirect
github.com/jinzhu/gorm v1.9.16 // indirect
github.com/jinzhu/now v1.1.2
github.com/jonboulle/clockwork v0.2.2 // indirect
github.com/kataras/iris/v12 v12.1.8
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/lestrrat-go/strftime v1.0.5 // indirect
github.com/moul/http2curl v1.0.0 // indirect
github.com/onsi/gomega v1.14.0 // indirect
github.com/oschwald/geoip2-golang v1.5.0
github.com/sergi/go-diff v1.2.0 // indirect
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
github.com/spf13/viper v1.8.1
github.com/urfave/cli/v2 v2.3.0 // indirect
github.com/valyala/fasthttp v1.28.0 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 // indirect
github.com/yudai/gojsondiff v1.0.0 // indirect
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
go.uber.org/zap v1.18.1
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97
gorm.io/datatypes v1.0.1
gorm.io/driver/mysql v1.1.1
gorm.io/gorm v1.21.12
)
This diff is collapsed.
package global
import "github.com/kataras/iris/v12"
const (
CODE_SUCCESS = 2000 // 成功
CODE_PARAM_ERROR = 2001 //参数错误
CODE_OPERATION_FAIL = 2010 //操作失败
)
type Response struct {
}
type ResponseOption func(*ResponseOptions)
type ResponseOptions struct {
Code int `json:"code"` // 状态码 200 成功 其它失败
Data interface{} `json:"data"`
Msg string `json:"msg"` // 消息
}
func WithCode (c int)ResponseOption{
return func(r *ResponseOptions){
r.Code = c
}
}
func WithData (d interface{})ResponseOption{
return func(r *ResponseOptions){
r.Data = d
}
}
func WithMsg (m string)ResponseOption{
return func(r *ResponseOptions){
r.Msg = m
}
}
func (r *Response) ParamError(c iris.Context, msg ...interface{}) {
}
package global
// 业务常量
const (
)
package global
import (
"github.com/go-redis/redis"
"go.uber.org/zap"
"gorm.io/gorm"
"xiaoxiong/config"
)
var (
GORM *gorm.DB
CONFIG config.Config
Log *zap.Logger
Redis *redis.Client
)
package global
// redis常量
const (
)
package service
func HomeClipboard(itemId string, relationId string, openId string, turnType int) {
}
package dtk
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"xiaoxiong/internal/global"
"xiaoxiong/internal/utils"
)
type CommonData struct {
appKey string
version string
timer string
nonce string
signRan string
}
type ItemDetailData struct {
RequestId string `json:"requestId"`
Time int64 `json:"time"`
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Id int `json:"id"`
GoodsId string `json:"goodsId"`
Title string `json:"title"`
Dtitle string `json:"dtitle"`
OriginalPrice float64 `json:"originalPrice"`
ActualPrice float64 `json:"actualPrice"`
ShopType int `json:"shopType"`
GoldSellers int `json:"goldSellers"`
MonthSaLes int `json:"monthSales"`
TwoHoursSales int `json:"twoHoursSales"`
DailySales int `json:"dailySales"`
CommissionType int `json:"commissionType"`
Desc string `json:"desc"`
CouponReceiveNum int `json:"couponReceiveNum"`
CouponLink string `json:"couponLink"`
CouponEndTime string `json:"couponEndTime"`
CouponStartTime string `json:"couponStartTime"`
CouponPrice int `json:"couponPrice"`
CouponConditions string `json:"couponConditions"`
CouponId string `json:"couponId"`
ActivityType int `json:"activityType"`
CreateTime string `json:"createTime"`
MainPic string `json:"mainPic"`
MarketingMainPic string `json:"marketingMainPic"`
SellerId string `json:"sellerId"`
BrandWenan string `json:"brandWenan"`
Cid int `json:"cid"`
Discounts float64 `json:"discounts"`
CommiSsionRate int `json:"commissionRate"`
CouponTotalNum int `json:"couponTotalNum"`
Haitao int `json:"haitao"`
ActivityStartTime string `json:"activityStartTime"`
ActivityEndTime string `json:"activityEndTime"`
ShopName string `json:"shopName"`
ShopLevel int `json:"shopLevel"`
DescScore float64 `json:"descScore"`
Brand int `json:"brand"`
BrandId int `json:"brandId"`
BrandName string `json:"brandName"`
HotPush int `json:"hotPush"`
TeamName string `json:"teamName"`
ItemLink string `json:"itemLink"`
Tchaoshi int `json:"tchaoshi"`
DsrScore float64 `json:"dsrScore"`
DsrPercent float64 `json:"dsrPercent"`
ShipScore float64 `json:"shipScore"`
ShipPercent float64 `json:"shipPercent"`
ServiceScore float64 `json:"serviceScore"`
ServicePercent float64 `json:"servicePercent"`
Subcid []interface{} `json:"subcid"`
Imgs string `json:"imgs"`
Reimgs string `json:"reimgs"`
QuanMLink int `json:"quanMLink"`
HzQuanOver int `json:"hzQuanOver"`
Yunfeixian int `json:"yunfeixian"`
EstimateAmount int `json:"estimateAmount"`
ShoPLogo string `json:"shopLogo"`
SpecialText []interface{} `json:"specialText"`
FreeshipRemoteDistrict int `json:"freeshipRemoteDistrict"`
Video string `json:"video"`
DetailPics string `json:"detailPics"`
IsSubdivision int `json:"isSubdivision"`
SubdivisionId int `json:"subdivisionId"`
SubdivisionName string `json:"subdivisionName"`
SubdivisionRank int `json:"subdivisionRank"`
DirecTCommissionType int `json:"directCommissionType"`
DirectCommission int `json:"directCommission"`
DirectCommissionLink string `json:"directCommissionLink"`
Sales24H int `json:"sales24h"`
Lowest int `json:"lowest"`
Tbcid int `json:"tbcid"`
} `json:"data"`
}
func ItemDetail(itemId string, turnType int8) (*ItemDetailData, error) {
var err error
t := time.Now().UnixMicro() / 1000
nonce := utils.RandNum(100000, 999999)
appKey := "5d00ab04a9f3a"
secret := "8de67b31a8b08167253b718fa565eb04"
d := &CommonData{
appKey,
"v1.3.0",
strconv.FormatInt(t, 10),
strconv.Itoa(nonce),
"",
}
str := fmt.Sprintf("appKey=%s&timer=%s&nonce=%s&key=%s", d.appKey, d.timer, d.nonce, secret)
m := md5.New()
m.Write([]byte(str))
d.signRan = strings.ToTitle(hex.EncodeToString(m.Sum(nil)))
u, err := url.Parse("https://openapi.dataoke.com/api/goods/get-goods-details")
if err != nil {
return nil, err
}
p := url.Values{}
//t := reflect.TypeOf(*d)
//v := reflect.ValueOf(*d)
//for k := 0; k < t.NumFiled(); k++ {
// fmt.Printf("%s -- %v \n", t.Filed(k).Name, v.Field(k).Interface())
//}
p.Set("appKey", d.appKey)
p.Set("version", d.version)
p.Set("timer", d.timer)
p.Set("nonce", d.nonce)
p.Set("signRan", d.signRan)
p.Set("goodsId", "630305425763")
u.RawQuery = p.Encode()
urlPath := u.String()
resp, err := http.Get(urlPath)
defer func() {
err = resp.Body.Close()
if err != nil {
global.Log.Info(fmt.Sprintf("resp close err %s", err.Error()))
}
}()
body, _ := ioutil.ReadAll(resp.Body)
res := &ItemDetailData{}
_ = json.Unmarshal(body, res)
return res, nil
}
package utils
import (
"github.com/casbin/casbin"
gormadapter "github.com/casbin/gorm-adapter"
_ "github.com/go-sql-driver/mysql"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"os"
"xiaoxiong/internal/global"
)
// 读取配置文件 初始化数据库
func GormInit() *gorm.DB {
dsn := global.CONFIG.MySql.Username + ":" + global.CONFIG.MySql.Password + "@tcp(" + global.CONFIG.MySql.Path + ")/" + global.CONFIG.MySql.Dbname + "?" + global.CONFIG.MySql.Config
return GormMysql(dsn)
}
// 初始化Mysql数据库
func GormMysql(dsn string) *gorm.DB {
mysqlConfig := mysql.Config{
DSN: dsn, // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
SkipInitializeWithVersion: false, // 根据版本自动配置
}
db, err := gorm.Open(mysql.New(mysqlConfig), gormConfig(global.CONFIG.MySql.LogMode))
if err != nil {
global.Log.Panic("mysql 初始化失败!")
os.Exit(0)
return nil
}
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(global.CONFIG.MySql.MaxIdleConns)
sqlDB.SetMaxOpenConns(global.CONFIG.MySql.MaxOpenConns)
global.Log.Debug("conn mysql succ!")
return db
}
// 根据配置决定是否开启日志
func gormConfig(mod bool) *gorm.Config {
if global.CONFIG.MySql.LogZap {
return &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
DisableForeignKeyConstraintWhenMigrating: true,
}
}
if mod {
return &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
DisableForeignKeyConstraintWhenMigrating: true,
}
} else {
return &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
DisableForeignKeyConstraintWhenMigrating: true,
}
}
}
func InitAcsbin() *casbin.Enforcer {
dsn := global.CONFIG.MySql.Username + ":" + global.CONFIG.MySql.Password + "@tcp(" + global.CONFIG.MySql.Path + ")/" + global.CONFIG.MySql.Dbname
a := gormadapter.NewAdapter("mysql", dsn, true)
enforcer := casbin.NewEnforcer("rbac_model.conf", a)
return enforcer
}
package utils
import (
"crypto/md5"
"fmt"
"golang.org/x/crypto/bcrypt"
)
// HashAndSalt 加密密码
func HashAndSalt(pwd []byte) string {
hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
if err != nil {
}
return string(hash)
}
// ComparePasswords 验证密码
func ComparePasswords(hashedPwd string, plainPwd []byte) bool {
byteHash := []byte(hashedPwd)
err := bcrypt.CompareHashAndPassword(byteHash, plainPwd)
if err != nil {
return false
}
return true
}
// FromStringGetMd5 以下是MD5 计算的方法
func FromStringGetMd5(hashedPwd string, plainPwd []byte) bool {
has := md5.Sum(plainPwd)
str := fmt.Sprintf("%x", has)
if hashedPwd != str {
return false
}
return true
}
package utils
import (
"math/rand"
"sync/atomic"
"time"
)
var genRandCodeCount int64
// GenRandCode 生成随机码
func GenRandCode(inviteCodeLen int, targetKind int) string {
atomic.AddInt64(&genRandCodeCount, 1)
ikind, kinds, result := targetKind, [][]int{[]int{10, 48}, []int{26, 97}, []int{26, 65}}, make([]byte, inviteCodeLen)
isAll := targetKind > 2 || targetKind < 0
rand.Seed(time.Now().UnixNano() + genRandCodeCount)
for i := 0; i < inviteCodeLen; i++ {
if isAll {
ikind = rand.Intn(3)
}
scope, base := kinds[ikind][0], kinds[ikind][1]
result[i] = uint8(base + rand.Intn(scope))
}
return string(result)
}
// RandNum 生成[start,end)随机数
func RandNum(start, end int) int {
if end < start {
return 0
}
return rand.New(rand.NewSource(time.Now().UnixNano())).Intn(end-start) + start
}
func RandInt() int {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
rand := int(rnd.Int31n(1000000))
return rand
}
package utils
import (
"github.com/go-redis/redis"
"go.uber.org/zap"
"xiaoxiong/internal/global"
)
func InitRedis() *redis.Client {
redisCfg := global.CONFIG.Redis
client := redis.NewClient(&redis.Options{
Addr: redisCfg.Addr,
Password: redisCfg.Password, // no password set
DB: redisCfg.DB, // use default DB
})
pong, err := client.Ping().Result()
if err != nil {
global.Log.Error("redis connect ping failed, err:", zap.Any("err", err))
panic(err)
return nil
} else {
global.Log.Debug("redis connect ping response:", zap.String("pong", pong))
return client
}
}
package utils
func TbkItemInfoGetRequest() {
}
\ No newline at end of file
package taobao
func newClient() {
}
\ No newline at end of file
package taobao
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"xiaoxiong/internal/global"
"xiaoxiong/internal/utils"
)
type TbkItemInfoGetRequest struct {
Platform string `json:"platform"`
NumIids string `json:"num_iids"`
}
type CommonRequest struct {
AppKey string `json:"app_key"`
V string `json:"v"`
Format string `json:"format"`
SignMethod string `json:"sign_method"`
Method string `json:"method"`
Timestamp string `json:"timestamp"`
PartnerId string `json:"partner_id"`
Sign string `json:"sign"`
}
func newCommonRequest(appKeyType int8)*CommonRequest{
r := &CommonRequest{}
if appKeyType {
}
r.Format = "json"
r.V = "2.0"
r.Method = "sign_method"
return r
}
func ItemDetail(itemId string, turnType int8) () {
var err error
req := &TbkItemInfoGetRequest{
"2",
itemId,
}
commonReq :=
commonReq.AppKey
}
package utils
import (
"fmt"
"github.com/spf13/viper"
"xiaoxiong/internal/global"
)
func Viper() *viper.Viper {
var err error
config := viper.New()
config.SetConfigType("yaml")
config.SetConfigName("application")
config.AddConfigPath("./")
err = config.ReadInConfig()
if err != nil {
fmt.Println("error on parsing configuration file", err)
return config
}
configs := config.AllSettings()
for k, v := range configs {
config.SetDefault(k, v)
}
config.SetConfigType("yaml")
config.SetConfigName("application")
config.AddConfigPath("./")
err = config.ReadInConfig()
if err != nil {
return config
}
if err := config.Unmarshal(&global.CONFIG); err != nil {
fmt.Println(err)
}
return config
}
package utils
import (
"fmt"
zaprotatelogs "github.com/lestrrat-go/file-rotatelogs"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
"path"
"time"
"xiaoxiong/internal/global"
)
var level zapcore.Level
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func Zap() (logger *zap.Logger) {
if ok, _ := PathExists(global.CONFIG.Zap.Director); !ok { // 判断是否有Director文件夹
fmt.Printf("create %v directory\n", global.CONFIG.Zap.Director)
_ = os.Mkdir(global.CONFIG.Zap.Director, os.ModePerm)
}
switch global.CONFIG.Zap.Level { // 初始化配置文件的Level
case "debug":
level = zap.DebugLevel
case "info":
level = zap.InfoLevel
case "warn":
level = zap.WarnLevel
case "error":
level = zap.ErrorLevel
case "dpanic":
level = zap.DPanicLevel
case "panic":
level = zap.PanicLevel
case "fatal":
level = zap.FatalLevel
default:
level = zap.InfoLevel
}
//if level == zap.DebugLevel || level == zap.ErrorLevel {
// logger = zap.New(getEncoderCore(), zap.AddStacktrace(level))
//} else {
logger = zap.New(getEncoderCore())
//}
if global.CONFIG.Zap.ShowLine {
logger = logger.WithOptions(zap.AddCaller())
}
logger.Debug("logger init succ")
return logger
}
// getEncoderConfig 获取zapcore.EncoderConfig
func getEncoderConfig() (config zapcore.EncoderConfig) {
config = zapcore.EncoderConfig{
MessageKey: "message",
LevelKey: "level",
TimeKey: "time",
NameKey: "logger",
CallerKey: "caller",
StacktraceKey: global.CONFIG.Zap.StacktraceKey,
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: CustomTimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.FullCallerEncoder,
}
switch {
case global.CONFIG.Zap.EncodeLevel == "LowercaseLevelEncoder": // 小写编码器(默认)
config.EncodeLevel = zapcore.LowercaseLevelEncoder
case global.CONFIG.Zap.EncodeLevel == "LowercaseColorLevelEncoder": // 小写编码器带颜色
config.EncodeLevel = zapcore.LowercaseColorLevelEncoder
case global.CONFIG.Zap.EncodeLevel == "CapitalLevelEncoder": // 大写编码器
config.EncodeLevel = zapcore.CapitalLevelEncoder
case global.CONFIG.Zap.EncodeLevel == "CapitalColorLevelEncoder": // 大写编码器带颜色
config.EncodeLevel = zapcore.CapitalColorLevelEncoder
default:
config.EncodeLevel = zapcore.LowercaseLevelEncoder
}
return config
}
// getEncoder 获取zapcore.Encoder
func getEncoder() zapcore.Encoder {
if global.CONFIG.Zap.Format == "json" {
return zapcore.NewJSONEncoder(getEncoderConfig())
}
return zapcore.NewConsoleEncoder(getEncoderConfig())
}
// getEncoderCore 获取Encoder的zapcore.Core
func getEncoderCore() (core zapcore.Core) {
writer, err := GetWriteSyncer() // 使用file-rotatelogs进行日志分割
if err != nil {
fmt.Printf("Get Write Syncer Failed err:%v", err.Error())
return
}
return zapcore.NewCore(getEncoder(), writer, level)
}
func GetWriteSyncer() (zapcore.WriteSyncer, error) {
fileWriter, err := zaprotatelogs.New(
path.Join(global.CONFIG.Zap.Director, "%Y-%m-%d.log"),
//zaprotatelogs.WithLinkName(CONFIG.Zap.LinkName),
zaprotatelogs.WithMaxAge(2*24*time.Hour),
zaprotatelogs.WithRotationTime(24*time.Hour),
)
if global.CONFIG.Zap.LogInConsole {
return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(fileWriter)), err
}
return zapcore.AddSync(fileWriter), err
}
// CustomTimeEncoder 自定义日志输出时间格式
func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format(global.CONFIG.Zap.Prefix + "2006/01/02 - 15:04:05.000"))
}
package main
import (
"xiaoxiong/cmd"
)
func main() {
cmd.Run()
}
package routes
import (
"github.com/kataras/iris/v12"
appServer "xiaoxiong/api/app"
)
func Router(app *iris.Application) {
app.Post("turnchain.homeClipboard", appServer.HomeClipboard)
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment