From e4f479942979f0ba2245ee6f368065369d68b230 Mon Sep 17 00:00:00 2001 From: Patrick Peng Sun Date: Sat, 20 May 2017 16:36:31 +1000 Subject: [PATCH] access crm attachment through our server as a proxy. --- crmAttachment_test.go | 5 +++-- fileinfo.go | 8 ++++++++ main.go | 1 + server.go | 26 ++++++++++++++++++++++++-- 4 files changed, 36 insertions(+), 4 deletions(-) diff --git a/crmAttachment_test.go b/crmAttachment_test.go index a1ec049..6340936 100644 --- a/crmAttachment_test.go +++ b/crmAttachment_test.go @@ -24,6 +24,7 @@ func TestDecodeJsonResponse(t *testing.T) { func TestCRMDownloadAttachment(t *testing.T) { SetupConfig() - crmDownloadAttachment("591ef9c61d6ca779c") - crmDownloadAttachmentAs("591ef9c61d6ca779c", "/tmp/wechat_hitxy_测试") + id := "59054884ef1b0c04f" + //crmDownloadAttachment(id) + crmDownloadAttachmentAs(id, "/tmp/wechat_hitxy_测试") } diff --git a/fileinfo.go b/fileinfo.go index 36a5d43..cd0e8d5 100644 --- a/fileinfo.go +++ b/fileinfo.go @@ -103,3 +103,11 @@ func getFileInfo4CRM(path string) (info crmFileInfo, err error) { info.Size, err = getFileSize(path) return } + +func isFileExist(path string) bool { + if _, err := os.Stat(path); os.IsNotExist(err) { + // path/to/whatever does not exist + return false + } + return true +} diff --git a/main.go b/main.go index 37dcccb..763e8b2 100644 --- a/main.go +++ b/main.go @@ -35,5 +35,6 @@ func main() { //http.HandleFunc("/", webrootHandler) http.HandleFunc("/api", apiV1Main) http.HandleFunc("/upload", uploadHandler) + http.HandleFunc("/crmfiles/", crmAttachmentHandler) http.ListenAndServe(":65500", nil) } diff --git a/server.go b/server.go index aa63d56..1bff7ec 100644 --- a/server.go +++ b/server.go @@ -188,6 +188,28 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) { io.Copy(f, file) } -func crmAttachmentHandler(w http.Response, r *http.Request) { - http.ServeFile(w, r) +func crmAttachmentHandler(w http.ResponseWriter, r *http.Request) { + fileID := getCrmFileID(r.URL.Path) + saveAs := GlobalPath.CRMAttachment + "crm_attach_" + fileID //add prefix for easy deleting + if fileID == "" { + log.Println("invalid fileID") + response404Handler(w) + return + } + log.Printf("download %s => %s", fileID, saveAs) + crmDownloadAttachmentAs(fileID, saveAs) + if !isFileExist(saveAs) { + response404Handler(w) + return + } + http.ServeFile(w, r, saveAs) +} + +func getCrmFileID(urlPath string) string { + return strings.TrimPrefix(urlPath, "/crmfiles/") +} + +func response404Handler(w http.ResponseWriter) { + w.WriteHeader(http.StatusNotFound) + fmt.Fprintf(w, "not found") }