DESKTOP-6R169VE\hrj 1 год назад
Родитель
Сommit
479a3e674d
10 измененных файлов с 213 добавлено и 33 удалено
  1. 4 0
      README.md
  2. 0 2
      config/config.yaml
  3. 15 0
      config/settings.yaml
  4. 6 0
      go.mod
  5. 12 0
      go.sum
  6. 119 0
      logger/logger.go
  7. 43 31
      main.go
  8. BIN
      main.syso
  9. BIN
      resource/icon.ico
  10. 14 0
      resource/info.manifest

+ 4 - 0
README.md

@@ -0,0 +1,4 @@
+参考https://cloud.tencent.com/developer/article/2258875
+按以下命令打包:
+go generate
+go build -o zsyy-upload.exe -ldflags="-linkmode internal"  -ldflags="-H windowsgui"

+ 0 - 2
config/config.yaml

@@ -1,2 +0,0 @@
-postURL: http://localhost:8080/api/tpsUpload
-pdfPath: E:/test/

+ 15 - 0
config/settings.yaml

@@ -0,0 +1,15 @@
+postURL: http://localhost:8080/api/tpsUpload
+pdfPath: E:/test/
+
+settings:
+  sleeptime: 5
+  log:
+    compress: 1
+    consolestdout: 1
+    filestdout: 1
+    level: debug
+    localtime: 1
+    maxage: 30
+    maxbackups: 300
+    maxsize: 10240
+    path: ./config/upload.log

+ 6 - 0
go.mod

@@ -3,10 +3,12 @@ module zsyy-upload
 go 1.20
 
 require (
+	github.com/akavel/rsrc v0.10.2 // indirect
 	github.com/fsnotify/fsnotify v1.6.0 // indirect
 	github.com/hashicorp/hcl v1.0.0 // indirect
 	github.com/magiconair/properties v1.8.7 // indirect
 	github.com/mitchellh/mapstructure v1.5.0 // indirect
+	github.com/natefinch/lumberjack v2.0.0+incompatible // indirect
 	github.com/pelletier/go-toml/v2 v2.0.6 // indirect
 	github.com/spf13/afero v1.9.3 // indirect
 	github.com/spf13/cast v1.5.0 // indirect
@@ -14,8 +16,12 @@ require (
 	github.com/spf13/pflag v1.0.5 // indirect
 	github.com/spf13/viper v1.15.0 // indirect
 	github.com/subosito/gotenv v1.4.2 // indirect
+	go.uber.org/atomic v1.10.0 // indirect
+	go.uber.org/multierr v1.11.0 // indirect
+	go.uber.org/zap v1.24.0 // indirect
 	golang.org/x/sys v0.3.0 // indirect
 	golang.org/x/text v0.5.0 // indirect
 	gopkg.in/ini.v1 v1.67.0 // indirect
+	gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
 	gopkg.in/yaml.v3 v3.0.1 // indirect
 )

+ 12 - 0
go.sum

@@ -389,6 +389,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
 github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
 github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
 github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
+github.com/akavel/rsrc v0.10.2 h1:Zxm8V5eI1hW4gGaYsJQUhxpjkENuG91ki8B4zCrvEsw=
+github.com/akavel/rsrc v0.10.2/go.mod h1:uLoCtb9J+EyAqh+26kdrTgmzRBFPGOolLWKpdxkKq+c=
 github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
 github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
 github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
@@ -665,6 +667,8 @@ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3Rllmb
 github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
 github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
 github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
+github.com/natefinch/lumberjack v2.0.0+incompatible h1:4QJd3OLAMgj7ph+yZTuX13Ld4UpgHp07nNdFX7mqFfM=
+github.com/natefinch/lumberjack v2.0.0+incompatible/go.mod h1:Wi9p2TTF5DG5oU+6YfsmYQpsTIOm0B1VNzQg9Mw6nPk=
 github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
 github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
 github.com/pelletier/go-toml v1.9.4/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
@@ -791,11 +795,17 @@ go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
 go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
 go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
 go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
+go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ=
+go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
 go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
 go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
 go.uber.org/multierr v1.8.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak=
+go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
+go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
 go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo=
 go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw=
+go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
+go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
 golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
 golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
 golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
@@ -1360,6 +1370,8 @@ gopkg.in/ini.v1 v1.63.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
 gopkg.in/ini.v1 v1.66.4/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
 gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
 gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
+gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
+gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
 gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
 gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
 gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

+ 119 - 0
logger/logger.go

@@ -0,0 +1,119 @@
+package logger
+
+import (
+	"os"
+	"time"
+	"gopkg.in/natefinch/lumberjack.v2"
+	"github.com/spf13/viper"
+	"go.uber.org/zap"
+	"go.uber.org/zap/zapcore"
+)
+
+// error logger
+var log *zap.SugaredLogger
+
+var levelMap = map[string]zapcore.Level{
+	"debug":  zapcore.DebugLevel,
+	"info":   zapcore.InfoLevel,
+	"warn":   zapcore.WarnLevel,
+	"error":  zapcore.ErrorLevel,
+	"dpanic": zapcore.DPanicLevel,
+	"panic":  zapcore.PanicLevel,
+	"fatal":  zapcore.FatalLevel,
+}
+
+func Init() {
+	config := viper.New()
+	config.SetConfigFile("./config/settings.yaml")
+	config.ReadInConfig()
+
+	var syncWriters []zapcore.WriteSyncer
+	level := getLoggerLevel(config.GetString(`settings.log.level`))
+	fileConfig := &lumberjack.Logger{
+		Filename:   config.GetString(`settings.log.path`),    // 日志文件名
+		MaxSize:    config.GetInt(`settings.log.maxsize`),    // 日志文件大小
+		MaxAge:     config.GetInt(`settings.log.maxAge`),     // 最长保存天数
+		MaxBackups: config.GetInt(`settings.log.maxBackups`), // 最多备份几个
+		LocalTime:  config.GetBool(`settings.log.localtime`), // 日志时间戳
+		Compress:   config.GetBool(`settings.log.compress`),  // 是否压缩文件,使用gzip
+	}
+	encoder := zap.NewProductionEncoderConfig()
+	encoder.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
+		enc.AppendString(t.Format("2006-01-02 15:04:05.000000"))
+	}
+	if config.GetBool("settings.log.consoleStdout") {
+		syncWriters = append(syncWriters, zapcore.AddSync(os.Stdout))
+	}
+	if config.GetBool("settings.log.fileStdout") {
+		syncWriters = append(syncWriters, zapcore.AddSync(fileConfig))
+	}
+	core := zapcore.NewCore(
+		zapcore.NewJSONEncoder(encoder),
+		zapcore.NewMultiWriteSyncer(syncWriters...),
+		zap.NewAtomicLevelAt(level))
+	logger := zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
+	log = logger.Sugar()
+}
+
+func getLoggerLevel(lvl string) zapcore.Level {
+	if level, ok := levelMap[lvl]; ok {
+		return level
+	}
+	return zapcore.InfoLevel
+}
+
+func Debug(args ...interface{}) {
+	log.Debug(args...)
+}
+
+func Debugf(format string, args ...interface{}) {
+	log.Debugf(format, args...)
+}
+
+func Info(args ...interface{}) {
+	log.Info(args...)
+}
+
+func Infof(format string, args ...interface{}) {
+	log.Infof(format, args...)
+}
+
+func Warn(args ...interface{}) {
+	log.Warn(args...)
+}
+
+func Warnf(format string, args ...interface{}) {
+	log.Warnf(format, args...)
+}
+
+func Error(args ...interface{}) {
+	log.Error(args...)
+}
+
+func Errorf(format string, args ...interface{}) {
+	log.Errorf(format, args...)
+}
+
+func DPanic(args ...interface{}) {
+	log.DPanic(args...)
+}
+
+func DPanicf(format string, args ...interface{}) {
+	log.DPanicf(format, args...)
+}
+
+func Panic(args ...interface{}) {
+	log.Panic(args...)
+}
+
+func Panicf(format string, args ...interface{}) {
+	log.Panicf(format, args...)
+}
+
+func Fatal(args ...interface{}) {
+	log.Fatal(args...)
+}
+
+func Fatalf(format string, args ...interface{}) {
+	log.Fatalf(format, args...)
+}

+ 43 - 31
main.go

@@ -1,28 +1,44 @@
+//go:generate rsrc -ico resource/icon.ico -manifest resource/info.manifest -o main.syso
 package main
 
 import (
 	"bytes"
-	"fmt"
 	"io"
 	"io/ioutil"
 	"mime/multipart"
 	"net/http"
 	"os"
+	"time"
 	"path"
 	"strings"
-
+	"zsyy-upload/logger"
 	"github.com/spf13/viper"
 )
 
+var config *viper.Viper;
+
 func main() {
-	postFormDataWithMultipartFile()
+	config = viper.New()
+	config.SetConfigFile("./config/settings.yaml")
+	config.ReadInConfig()
+
+	sleeptime := config.GetInt("settings.sleeptime")
+	
+	logger.Init()
+
+	i := 1
+	for i<10 {
+		postFormDataWithMultipartFile()
+		time.Sleep(time.Second * time.Duration(sleeptime))
+	}
+	
 }
 
 func readDir(dirname string) ([]string, error) {
 	infos, err := ioutil.ReadDir(dirname)
 	if err != nil {
-		fmt.Println("file read Error!")
-		fmt.Printf("%s", err)
+		logger.Info("file read Error!")
+		logger.Errorf("%s", err)
 		return nil, err
 	}
 
@@ -47,32 +63,28 @@ func remove(file string) {
 	err := os.Remove(file) //删除文件test.txt
 	if err != nil {
 		//如果删除失败则输出 file remove Error!
-		fmt.Println("file remove Error!", err)
+		logger.Errorf("file remove Error!", err)
 	} else {
 		//如果删除成功则输出 file remove OK!
-		fmt.Println("file remove OK!", file)
+		logger.Infof("file remove OK!", file)
 	}
 }
 
 func postFormDataWithMultipartFile() {
-	fmt.Println("=======start=======")
-
-	config := viper.New()
-	// config.AddConfigPath("./config/")
-	// config.SetConfigName("config")
-	// config.SetConfigType("yaml")
-
-	config.SetConfigFile("./config/config.yaml")
-	config.ReadInConfig()
+	logger.Info("=======start========")
 
 	postURL := config.GetString("postURL")
 	pdfPath := config.GetString("pdfPath")
 	// postURL := "http://localhost:8080/api/tpsUpload"
-	fmt.Println("load yml postURL: ", postURL)
-	fmt.Println("load yml pdfPath: ", pdfPath)
+	logger.Info("load yml postURL: ", postURL)
+	logger.Info("load yml pdfPath: ", pdfPath)
 
 	fileNames, _ := readDir(pdfPath)
-	fmt.Println(fileNames)
+	if(fileNames == nil || len(fileNames) == 0){
+		logger.Info("读取文件为空")
+		return
+	}
+	logger.Infof("fileNames==",fileNames)
 
 	defer func() {
 		for _, val := range fileNames {
@@ -86,15 +98,15 @@ func postFormDataWithMultipartFile() {
 	for _, val := range fileNames {
 		file, err := os.Open(pdfPath + val)
 		if err != nil {
-			fmt.Println("err1")
-			fmt.Printf("%s", err)
+			logger.Info("err1")
+			logger.Errorf("%s", err)
 		}
 		defer file.Close()
 		fileWrite, _ := bodyWrite.CreateFormFile("files", val)
 		_, err = io.Copy(fileWrite, file)
 		if err != nil {
-			fmt.Println("err2")
-			fmt.Printf("%s", err)
+			logger.Info("err2")
+			logger.Errorf("%s", err)
 		}
 	}
 	bodyWrite.Close() //要关闭,会将w.w.boundary刷写到w.writer中
@@ -102,16 +114,16 @@ func postFormDataWithMultipartFile() {
 	// 创建请求
 	req, err := http.NewRequest(http.MethodPost, postURL, bodyBuf)
 	if err != nil {
-		fmt.Println("err3")
-		fmt.Printf("%s", err)
+		logger.Info("err3")
+		logger.Errorf("%s", err)
 	}
 	// 设置头
 	contentType := bodyWrite.FormDataContentType()
 	req.Header.Set("Content-Type", contentType)
 	resp, err := client.Do(req)
 	if err != nil {
-		fmt.Println("err4")
-		fmt.Printf("%s", err)
+		logger.Info("err4")
+		logger.Errorf("%s", err)
 	}
 
 	defer resp.Body.Close()
@@ -119,12 +131,12 @@ func postFormDataWithMultipartFile() {
 
 	b, err := ioutil.ReadAll(resp.Body)
 	if err != nil {
-		fmt.Println("err5")
-		fmt.Printf("%s", err)
+		logger.Info("err5")
+		logger.Errorf("%s", err)
 	}
-	fmt.Println(string(b))
+	logger.Info(string(b))
 
 	// client.CloseIdleConnections()
 
-	fmt.Println("=======end=======")
+	logger.Info("=======end=======")
 }


BIN
resource/icon.ico


+ 14 - 0
resource/info.manifest

@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
+    <assemblyIdentity version="1.0.0.0" processorArchitecture="*" name="SomeFunkyNameHere" type="win32"/>
+    <dependency>
+        <dependentAssembly>
+            <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
+        </dependentAssembly>
+    </dependency>
+    <asmv3:application>
+        <asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
+            <dpiAware>true</dpiAware>
+        </asmv3:windowsSettings>
+    </asmv3:application>
+</assembly>