-
Notifications
You must be signed in to change notification settings - Fork 4
/
cmdFile.go
79 lines (70 loc) · 1.73 KB
/
cmdFile.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
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"strconv"
"github.com/gorilla/mux"
"github.com/nimezhu/nbdata"
"github.com/rs/cors"
"github.com/urfave/cli/v2"
)
var fileApp = nbdata.App{
"CMU Fileome Server",
"0.0.2",
}
func ls(dir string) []os.FileInfo {
files, err := ioutil.ReadDir(dir)
if err != nil {
return []os.FileInfo{}
}
return files
}
/* CNB
File Server for Simple 3D Structure or Other files
file server with meta.tsv for directory (alias)
easily manage files with or without google sheets
file server support range.
/* interface: ls dir and get/file */
//CmdFile : subcommand to start a simple file server
func CmdFile(c *cli.Context) error {
root := c.String("root")
port := c.Int("port")
router := mux.NewRouter()
//cors := data.CorsFactory(CORS)
customCors := c.String("cors")
corsOptions := nbdata.GetCors(customCors)
//router.Use(cors)
router.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
a, _ := json.Marshal(fileApp)
w.Write(a)
})
router.HandleFunc("/ls/{dir:.*}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
dir := vars["dir"]
fs := ls(path.Join(root, dir))
fn := []string{}
for _, f := range fs {
fn = append(fn, f.Name())
}
j, err := json.Marshal(fn)
if err == nil {
w.Write(j)
} else {
w.Write([]byte("error"))
}
})
router.PathPrefix("/get").Handler(http.StripPrefix("/get", http.FileServer(http.Dir(root))))
hc := cors.New(corsOptions)
handler := hc.Handler(router)
server := &http.Server{Addr: ":" + strconv.Itoa(port), Handler: handler}
log.Println("Please open http://127.0.0.1:" + strconv.Itoa(port))
err := server.ListenAndServe()
if err != nil {
panic(err)
}
return err
}