- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章golang实现ftp实时传输文件的案例由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
1、项目简介 。
本项目主要实现的功能是ftp客户端不断地将xml文件和jpg文件实时地上传到服务器,当然也可以是其他格式的文件。每当ftp客户端取到一个文件之后,将文件上传到服务器后,然后将其删除.
项目实现可配置,如果开发者有类似的需求,只需要修改配置文件就可以使用本项目去完成上传文件的功能.
本项目打日志是按照当天时间来生成日志文件,每天每一种类型的日志只打一个文件.
2、项目结构图片 。
3、项目代码 。
config配置中的代码 。
config.ini 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
[path]
xml_path = D:\\dian\\out\\ # xml文件所在的路径
img_path = D:\\dian\\out\\wave\\ # 图片文件所在路径
[ftp]
ftpfile_path = D:\\Itudou # 在服务器上的文件存储路径
ftp_server_ip = 192.168.56.1 # ftp服务器的IP
ftp_server_port = 21 # ftp服务器的端口
ftp_server_name = 20123762 # ftp服务器的用户名
ftp_server_pwd = 123456 # ftp服务器的密码
local_ip = 192.168.56.1 # 本地主机的IP
local_port = 80 #本地主机端口
comm_way = udp #ftp的通信方式
[file]
file_img =.jpg #文件后缀为img
file_xml =.xml #文件后缀为xml
log_print = ture #是否打日志,生产环境上不打日志,在调式程序的时候使用
|
读配置文件的代码 。
daos_config.go 。
。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
package daosconfig
import (
"bufio"
"io"
"os"
"strings"
)
type Config struct {
Mymap map[string]string
strcet string
}
func (c *Config) InitConfig(path string) {
c.Mymap = make(map[string]string)
f, err := os.Open(path)
if err != nil {
panic(err)
}
defer f.Close()
r := bufio.NewReader(f)
for {
b, _, err := r.ReadLine()
if err != nil {
if err == io.EOF {
break
}
panic(err)
}
s := strings.TrimSpace(string(b))
if strings.Index(s, "#") == 0 {
continue
}
n1 := strings.Index(s, "[")
n2 := strings.LastIndex(s, "]")
if n1 > -1 && n2 > -1 && n2 > n1+1 {
c.strcet = strings.TrimSpace(s[n1+1 : n2])
continue
}
if len(c.strcet) == 0 {
continue
}
index := strings.Index(s, "=")
if index < 0 {
continue
}
frist := strings.TrimSpace(s[:index])
if len(frist) == 0 {
continue
}
second := strings.TrimSpace(s[index+1:])
pos := strings.Index(second, "\t#")
if pos > -1 {
second = second[0:pos]
}
pos = strings.Index(second, " #")
if pos > -1 {
second = second[0:pos]
}
pos = strings.Index(second, "\t//")
if pos > -1 {
second = second[0:pos]
}
pos = strings.Index(second, " //")
if pos > -1 {
second = second[0:pos]
}
if len(second) == 0 {
continue
}
key := c.strcet + "=" + frist
c.Mymap[key] = strings.TrimSpace(second)
}
}
func (c Config) Read(node, key string) string {
key = node + "=" + key
v, found := c.Mymap[key]
if !found {
return ""
}
return v
}
|
ftp上传文件核心代码 。
daos_ftp.go 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
|
package daosftp
import (
"fmt"
"net"
"os"
"strings"
ftp "github.com/ftp"
"io/ioutil"
"regexp"
"path/filepath"
cfg "bjdaos_tool/pkg/daosconfig"
"bjdaos_tool/pkg/env"
"bjdaos_tool/pkg/daoslog"
)
func getListDir(dirPth string) (files []string,files1 []string, err error) {
dir, err := ioutil.ReadDir(dirPth)
if err != nil {
return nil,nil, err
}
PthSep := string(os.PathSeparator)
for _, fi := range dir {
if fi.IsDir() {
files1 = append(files1, dirPth+PthSep+fi.Name())
getListDir(dirPth + PthSep + fi.Name())
}else{
files = append(files, dirPth+PthSep+fi.Name())
}
}
return files,files1, nil
}
func GetAllFileName(path string, str string) (int, []string ) {
configPath := env.GetConfigPath()
ftpConfig := new(cfg.Config)
ftpConfig.InitConfig(configPath + "\\config.ini")
logPrint := ftpConfig.Read("file", "log_print")
files, _, err := getListDir(path)
if err != nil {
daoslog.WriteLog(logPrint, "System","get file path err")
}
fileLen := len(files)
fileSlice := make([]string,0, fileLen)
suffix1 := ftpConfig.Read("file", "file_img")
suffix2 := ftpConfig.Read("file", "file_xml")
reg_front := regexp.MustCompile("\\d{8}")
reg_end := regexp.MustCompile("\\d{14}")
if str == suffix1{
for i := 0; i < fileLen; i++{
data_front := reg_front.FindString(files[i])
date_end := reg_end.FindString(files[i])
imgName := data_front + "_" + date_end + str
fileSlice = append(fileSlice, imgName)
}
}else if str == suffix2 {
for i := 0; i < fileLen; i++{
data_front := reg_front.FindString(files[i])
date_end := reg_end.FindString(files[i])
imgName := data_front + "_" + date_end + str
fileSlice = append(fileSlice, imgName)
}
}
return fileLen, fileSlice
}
func getLocalIpAddr() string {
configPath := env.GetConfigPath()
ftpConfig := new(cfg.Config)
ftpConfig.InitConfig(configPath + "\\config.ini")
logPrint := ftpConfig.Read("file", "log_print")
network := ftpConfig.Read("ftp", "comm_way")
ip := ftpConfig.Read("ftp", "local_ip")
port := ftpConfig.Read("ftp", "local_port")
address := ip + ":" + port
conn, err := net.Dial(network, address)
if err != nil {
daoslog.WriteLog(logPrint, "System", "get local ip address err")
return "127.0.0.1"
}
defer conn.Close()
return strings.Split(conn.LocalAddr().String(), ":")[0]
}
func ftpUploadFile(ftpserver, ftpuser, pw, localFile, remoteSavePath, saveName string) {
configPath := env.GetConfigPath()
ftpConfig := new(cfg.Config)
ftpConfig.InitConfig(configPath + "\\config.ini")
logPrint := ftpConfig.Read("file", "log_print")
ftpfile_path := ftpConfig.Read("ftp", "ftpfile_path")
ftp, err := ftp.Connect(ftpserver)
if err != nil {
daoslog.WriteLog(logPrint, "System", "connect err")
}
err = ftp.Login(ftpuser, pw)
if err != nil {
daoslog.WriteLog(logPrint, "System", "Login err")
}
ftp.ChangeDir(ftpfile_path)
dir, err := ftp.CurrentDir()
ftp.MakeDir(remoteSavePath)
ftp.ChangeDir(remoteSavePath)
dir, _ = ftp.CurrentDir()
daoslog.WriteLog(logPrint, "System", dir)
file, err := os.Open(localFile)
if err != nil {
daoslog.WriteLog(logPrint, "System", "Open err")
}
defer file.Close()
err = ftp.Stor(saveName, file)
if err != nil {
daoslog.WriteLog(logPrint, "System", "Stor err")
}
ftp.Logout()
ftp.Quit()
logcotent := fmt.Sprintf("%s:%s","success upload file",localFile)
daoslog.WriteLog(logPrint, "System", logcotent)
}
func RemoveFile(filePath string, fileName string){
configPath := env.GetConfigPath()
ftpConfig := new(cfg.Config)
ftpConfig.InitConfig(configPath + "\\config.ini")
logPrint := ftpConfig.Read("file", "log_print")
err := os.Remove(filePath + fileName)
if err != nil {
daoslog.WriteLog("false", "System", "file remove err!")
} else {
logcotent := fmt.Sprintf("%s:%s","file remove OK!",fileName)
daoslog.WriteLog(logPrint, "System", logcotent)
}
}
func SendXmlFileToFtpServer(filePath string, fileType string) {
configPath := env.GetConfigPath()
ftpConfig := new(cfg.Config)
ftpConfig.InitConfig(configPath + "\\config.ini")
logPrint := ftpConfig.Read("file", "log_print")
flen, fileName := GetAllFileName(filePath, fileType)
serverIp := getLocalIpAddr()
ftpserverip := ftpConfig.Read("ftp", "ftp_server_ip")
ftpPort := ftpConfig.Read("ftp", "ftp_server_port")
ftpuser := ftpConfig.Read("ftp", "ftp_server_name")
pw := ftpConfig.Read("ftp", "ftp_server_pwd")
ftpserver := ftpserverip + ":" + ftpPort
filepath.Walk(filePath, func(path string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if f.IsDir() {
return nil
}
for i := 0; i < flen; i++{
if f.Name() == fileName[i] {
logcotent := fmt.Sprintf("path=",path)
daoslog.WriteLog(logPrint, "System", logcotent)
pathFields := strings.Split(path, "\\")
var domainName string
if len(pathFields) > 3 {
domainName = pathFields[len(pathFields)-3]
}
ftpUploadFile(ftpserver, ftpuser, pw, path, domainName, serverIp+"_"+fileName[i])
RemoveFile(filePath, fileName[i])
}
}
return nil
})
}
func SendJpgFileToFtpServer(filePath string, fileType string) {
configPath := env.GetConfigPath()
ftpConfig := new(cfg.Config)
ftpConfig.InitConfig(configPath + "\\config.ini")
logPrint := ftpConfig.Read("file", "log_print")
flen, fileName := GetAllFileName(filePath, fileType)
serverIp := getLocalIpAddr()
ftpserverip := ftpConfig.Read("ftp", "ftp_server_ip")
ftpPort := ftpConfig.Read("ftp", "ftp_server_port")
ftpuser := ftpConfig.Read("ftp", "ftp_server_name")
pw := ftpConfig.Read("ftp", "ftp_server_pwd")
ftpserver := ftpserverip + ":" + ftpPort
filepath.Walk(filePath, func(path string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if f.IsDir() {
return nil
}
for i := 0; i < flen; i++{
if f.Name() == fileName[i] {
logcotent := fmt.Sprintf("path=",path)
daoslog.WriteLog(logPrint, "System", logcotent)
pathFields := strings.Split(path, "\\")
var domainName string
if len(pathFields) > 3 {
domainName = pathFields[len(pathFields)-3]
}
ftpUploadFile(ftpserver, ftpuser, pw, path, domainName, serverIp+"_"+fileName[i])
RemoveFile(filePath, fileName[i])
}
}
return nil
})
}
|
打日志的代码 。
daos_log.go 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package daoslog
import (
"fmt"
"log"
"os"
"github.com/golang/glog"
"time"
"bjdaos_tool/pkg/env"
)
func WriteLog(islog, logtype , errcontent string) {
if islog == "false" {
return
}
if logtype != "Info" && logtype!= "Debug" && logtype!= "Error" && logtype != "System" {
glog.Error("this is not a logtype ")
return
}
data := time.Now().Format("20060102")
logPath := env.GetConLogPath()
logFilea := logPath + "\\" + data+"_"+ logtype+".log"
errcontent = "[" +errcontent + "]"
logFile, err := os.OpenFile(logFilea, os.O_RDWR | os.O_CREATE, 0777)
if err != nil {
fmt.Printf("open file error=%s\r\n", err.Error())
os.Exit(-1)
}
logger := log.New(logFile, "{"+logtype+"} ", log.Ldate | log.Ltime | log.Lshortfile)
logger.Println(errcontent)
}
|
路径处理代码 。
daos-evn.go 。
。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package env
import (
"os"
"runtime"
)
var ostype = runtime.GOOS
func GetProjectPath() string{
var projectPath string
projectPath, _ = os.Getwd()
return projectPath
}
func GetConfigPath() string{
path := GetProjectPath()
if ostype == "windows"{
path = path + "\\" + "config\\"
}else if ostype == "linux"{
path = path +"/" + "config/"
}
return path
}
func GetConLogPath() string{
path := GetProjectPath()
if ostype == "windows"{
path = path + "\\log\\"
}else if ostype == "linux"{
path = path + "/log/"
}
return path
}
|
4、总结 。
主函数:
main.go 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package main
import (
"bjdaos_tool/pkg/daosftp"
"bjdaos_tool/pkg/env"
cfg "bjdaos_tool/pkg/daosconfig"
)
func main(){
configPath := env.GetConfigPath()
ftpConfig := new(cfg.Config)
ftpConfig.InitConfig(configPath + "\\config.ini")
xml_path := ftpConfig.Read("path", "xml_path")
img_path := ftpConfig.Read("path", "img_path")
file_img := ftpConfig.Read("file", "file_img")
file_xml := ftpConfig.Read("file", "file_xml")
for{
daosftp.SendXmlFileToFtpServer(xml_path, file_xml)
daosftp.SendJpgFileToFtpServer(img_path, file_img)
}
}
|
本项目依赖包:
完整代码:https://github.com/guoshijiang/go_ftp 。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我。如有错误或未考虑完全的地方,望不吝赐教.
原文链接:https://blog.csdn.net/jiang_xinxing/article/details/72083981 。
最后此篇关于golang实现ftp实时传输文件的案例的文章就讲到这里了,如果你想了解更多关于golang实现ftp实时传输文件的案例的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
Closed. This question is opinion-based。它当前不接受答案。 想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。 2年前关闭。
我想显示我的网站上所有用户都在线(实时;就像任何聊天模块一样)。我正在使用下面提到的脚本来执行此操作。 HTML: Javascript: var doClose = false; documen
有什么方法可以知道 Algolia 何时成功处理了排队作业,或者与上次重新索引相比,Algolia 是否索引了新文档? 我们希望建立一个系统,每当新文档被索引时,浏览网站的用户都会收到实时更新警告,并
构建将在“桌面”而不是浏览器中运行的 Java 应用程序的推荐策略是什么。该应用程序的特点是: 1. Multiple application instances would be running o
这是场景: 我正在编写一个医疗相关程序,可以在没有连接的情况下使用。当采取某些措施时,程序会将时间写入CoreData记录。 这就是问题所在,如果他们的设备将时间设置为比实际时间早的时间。那将是一个大
我有: $(document).ready(function () { $(".div1, .div2, .div3, .div4, .div5").draggable();
我有以下 jquery 代码: $("a[id*='Add_']").live('click', function() { //Get parentID to add to. var
我有一个 jsp 文件,其中包含一个表单。提交表单会调用处理发送的数据的 servlet。我希望当我点击提交按钮时,一个文本区域被跨越并且应该实时显示我的应用程序的日志。我正在使用 Tomcat 7。
我编辑了我的问题,我在 Default.aspx 页面中有一个提交按钮和文本框。我打开两个窗口Default.aspx。我想在这个窗口中向文本框输入文本并按提交,其他窗口将实时更新文本框。 请帮助我!
我用 php 创建了一个小型 CMS,如果其他用户在线或离线,我想显示已登录的用户。 目前,我只创建一个查询请求,但这不会一直更新。我希望用户在发生某些事情时立即看到更改。我正在寻找一个类似于 fac
我有以下问题需要解决。我必须构建一个图形查看器来查看海量数据集。 我们有一些特定格式的文件,其中包含数百万条代表实验结果的记录。每条记录代表大图上的一个样本点。我见过的最大的文件有 4370 万条记录
我最近完成了申请,但遇到了一个大问题。我一次只需要允许 1 个用户访问它。每个用户每次都可以访问一个索引页面和“开始”按钮。当用户点击开始时,应用程序锁定,其他人需要等到用户完成。当用户关闭选项卡/浏
我是 Android 开发新手。我正在寻找任何将音高变换应用到输出声音(实时)的方法。但我找不到任何起点。 我找到了这个 topic但我仍然不知道如何应用它。 有什么建议吗? 最佳答案 一般来说,该算
背景 用户计算机上的桌面应用程序从调制解调器获取电话号码,并在接到电话后将其发送到 PHP 脚本。目前,我可以通过 PHP 在指定端口上接收数据/数据包。然后我有一个连接到 411 数据库并返回指定电
很抱歉提出抽象问题,但我正在寻找一些关于在循环中执行一些等效操作的应用程序类型的示例/建议/文章,并且循环的每次迭代都应该在特定时间部分公开其结果(例如, 10 秒)。 我的应用程序在外部 WCF 服
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: What specifically are wall-clock-time, user-cpu-time,
我最近遇到了一个叫做 LiveChart 的工具,决定试用一下。 不幸的是,我在弄清楚如何实时更新图表值时遇到了一些问题。我很确定有一种干净正确的方法可以做到这一点,但我找不到它。 我希望能够通过 p
我正在实现实时 flutter 库 https://pub.dartlang.org/packages/true_time 遇到错误 W/DiskCacheClient(26153): Cannot
我一直在使用 instagram 的实时推送 api ( http://instagram.com/developer/realtime/ ) 来获取特定位置的更新。我使用“半径”的最大可能值,即 5
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 7年前关闭。 Improve thi
我是一名优秀的程序员,十分优秀!