Adds download support for files store in the QuanLib EFS.
[quanweb.git] / main / handler.go
index 52d08e5f8ff98f192f9dbc109418424522ac6719..255f19397a6fd6db357bae249a3d882f360e32f7 100644 (file)
@@ -3,7 +3,9 @@ package main
 import (
   "encoding/json"
   "fmt"
+  "io"
   "net/http"
+  "os"
   "strconv"
   "strings"
 )
@@ -12,6 +14,15 @@ const PARAM_IDS = "ids"
 const MAX_TERMS = 10
 
 // ============================================================================
+func efsPathForId(efsId int) string {
+  config := getConfig()
+
+  idStr := fmt.Sprintf("%010d", efsId)
+  path := fmt.Sprintf("%s/%s/%s/%s/%s/%s.dat", config.efsBasePath, idStr[0:2], idStr[2:4], idStr[4:6], idStr[6:8], idStr)
+
+  return path
+}
+
 func handler(w http.ResponseWriter, r *http.Request) {
   err := r.ParseForm()
   if nil != err {
@@ -19,9 +30,11 @@ func handler(w http.ResponseWriter, r *http.Request) {
     return
   }
 
-  action := r.URL.Path[1:]
+  action := strings.Split(r.URL.Path[1:], "/")[0]
 
   switch(action) {
+  case "download":
+    handleDownload(w, r)
   case "info":
     handleInfo(w, r)
   case "search":
@@ -35,6 +48,38 @@ func handler(w http.ResponseWriter, r *http.Request) {
   }
 }
 
+func handleDownload(w http.ResponseWriter, r *http.Request) {
+  path := r.URL.Path[1:]
+  tok := strings.Split(path, "/")
+  if 2 != len(tok)  {
+    fmt.Fprintln(w, "Unexpected path for download:", path)
+    return
+  }
+  efsId, err := strconv.Atoi(tok[1])
+  if (nil != err) || (0 == efsId) {
+    fmt.Fprintln(w, "Invalid id for download:", path, err)
+    return
+  }
+  
+  mimeType := queryMimeTypeByEfsId(efsId)
+  if 0 == len(mimeType) {
+    fmt.Fprintln(w, "No MIME type found for id:", efsId)
+    return
+  }
+
+  efsPath := efsPathForId(efsId)
+
+  var fd *os.File
+  fd, err = os.Open(efsPath)
+  if nil != err {
+    fmt.Fprintln(w, "Failed to read file for id:", efsId, err)
+    return
+  }
+  defer fd.Close()
+
+  io.Copy(w, fd)
+}
+
 func handleInfo(w http.ResponseWriter, r *http.Request) {
   idParams := r.Form[PARAM_IDS]
   if 1 != len(idParams) {