-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
161 lines (133 loc) · 4.3 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"mysftp"
"net/http"
"os"
"strconv"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
var router *chi.Mux
func init() {
router = chi.NewRouter()
router.Use(middleware.Recoverer)
}
func routers() *chi.Mux {
router.Get("/ping", ping)
router.Post("/connect", connectToSftp)
router.Get("/download", download)
router.Put("/upload", upload)
return router
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
func ping(w http.ResponseWriter, r *http.Request) {
respondWithJSON(w, http.StatusOK, map[string]string{"message": "Pong"})
}
func logger() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println(time.Now(), r.Method, r.URL)
router.ServeHTTP(w, r) // dispatch the request
})
}
type Post struct {
Host string `json:"host"`
User string `json:"user"`
Password string `json:"password"`
Port int `json:"port"`
}
type fileStruct struct {
FileName string
FileSize int64
}
var post Post
var mySftpDataConnection *mysftp.SftpClient
var errs error
func connectToSftp(w http.ResponseWriter, req *http.Request) {
newDecoderErr := json.NewDecoder(req.Body).Decode(&post)
if newDecoderErr != nil {
log.Printf("error decoding response: %v", newDecoderErr)
if e, ok := newDecoderErr.(*json.SyntaxError); ok {
log.Printf("syntax error at byte offset %d", e.Offset)
}
log.Printf("response: %q", post.Host)
}
log.Println(post.Host)
mySftpDataConnection, errs = mysftp.CreateNewConnection(post.Host, post.User, post.Password, post.Port)
var fileNames []fileStruct
files, err := ioutil.ReadDir("./sftpuser")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
log.Println(f.Name(), f.Size())
fileNames = append(fileNames, fileStruct{f.Name(), f.Size()})
}
w.Header().Set("Content-Type", "application/json")
// get a payload p := Payload{d}
json.NewEncoder(w).Encode(fileNames)
}
func upload(w http.ResponseWriter, req *http.Request) {
if _, err := os.Stat("./uploadFolder"); os.IsNotExist(err) {
log.Printf("/uploadFolder is not here")
_ = os.Mkdir("./uploadFolder", 0755)
}
if _, err := os.Stat("./uploadFolder"); !os.IsNotExist(err) {
log.Printf("/uploadFolder is here")
}
// Parse our multipart form, 10 << 20 specifies a maximum
// upload of 10 MB files.
req.ParseMultipartForm(10 << 20)
// FormFile returns the first file for the given key `myFile`
// it also returns the FileHeader so we can get the Filename,
// the Header and the size of the file
remoteFile, remoteFileHeader, remoteFileErr := req.FormFile("remoteFile")
if remoteFileErr != nil {
fmt.Println("Error Retrieving the File", remoteFileErr)
return
}
defer remoteFile.Close()
createTemporaryFile, createTemporaryFileErr := ioutil.TempFile("./uploadFolder", remoteFileHeader.Filename)
if createTemporaryFileErr != nil {
fmt.Println("createTemporaryFileErr", createTemporaryFileErr)
}
fmt.Printf("tempFile: %+v\n", createTemporaryFile.Name())
defer createTemporaryFile.Close()
readUploadedFileAndConvertIntoByteArray, readUploadedErr := ioutil.ReadAll(remoteFile)
if readUploadedErr != nil {
fmt.Println(readUploadedErr)
}
createTemporaryFile.Write(readUploadedFileAndConvertIntoByteArray)
mySftpDataConnection.Put(createTemporaryFile.Name(), remoteFileHeader.Filename)
}
func download(w http.ResponseWriter, req *http.Request) {
os.Chdir("./downloadFolder")
req.ParseForm()
remoteFileName := req.FormValue("remoteFileName")
mySftpDataConnection.Get(remoteFileName, remoteFileName)
attachment := fmt.Sprintf("attachment; filename=" + strconv.Quote(remoteFileName))
w.Header().Set("Content-Disposition", attachment)
w.Header().Set("Content-Type", req.Header.Get("Content-Type"))
openLocalFileUploaded, openLocalFileUploadedErr := os.Open(remoteFileName)
if openLocalFileUploadedErr != nil {
log.Println("openLocalFileUploadedErr open before send dl=> ", openLocalFileUploadedErr)
return
}
io.Copy(w, openLocalFileUploaded)
defer os.Remove(remoteFileName) // deleteFile uploaded on server before transfer to sftp
}
func main() {
routers()
fmt.Println("Listening")
http.ListenAndServe(":8100", logger())
}