/
example.go
115 lines (111 loc) · 2.57 KB
/
example.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
/*
* Copyright (c) 2012 Jason McVetta. This is Free Software, released under the
* terms of the WTFPL v2. It comes without any warranty, express or implied.
* See http://sam.zoy.org/wtfpl/COPYING for more details.
*
*
* Static files used this example are derived from the example included with
* the jQuery File Upload plugin:
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Original software by Tschan licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
package main
import (
"github.com/bmizerany/mc"
"github.com/jmcvetta/jfu"
"github.com/jmcvetta/mgourl"
"labix.org/v2/mgo"
"log"
"net/http"
"os"
"path/filepath"
)
func main() {
log.SetFlags(log.Ltime | log.Lshortfile)
//
// Setup environment from Heroku
//
port := os.Getenv("PORT")
if port == "" {
port = "5000"
}
//
//
pathRoot := os.Getenv("PWD") // Root of the application install
//
mcServers := os.Getenv("MEMCACHIER_SERVERS")
mcUser := os.Getenv("MEMCACHIER_USERNAME")
mcPasswd := os.Getenv("MEMCACHIER_PASSWORD")
//
//
mongoUri := os.Getenv("MONGOLAB_URI")
dbName := "jfuexample" // If no DB name specified, use "jfuexample"
if mongoUri != "" {
switch _, auth, _, err := mgourl.ParseURL(mongoUri); true {
case err != nil:
log.Fatal("Could not parse MongoDB URL:", err)
case auth.Db != "":
dbName = auth.Db
}
} else {
mongoUri = "localhost"
}
//
// Initialize MongoDB connection
//
log.Println("Connecting to MongoDB on", mongoUri)
conn, err := mgo.Dial(mongoUri)
if err != nil {
log.Fatalln(err)
}
db := conn.DB(dbName)
gfs := db.GridFS("test_foobar")
store := jfu.NewMongoStore(gfs)
//
// Initialize Memcache connection
//
if mcServers == "" {
mcServers = "localhost:11211"
}
client, err := mc.Dial("tcp", mcServers)
if err != nil {
log.Panic(err)
}
if mcUser != "" && mcPasswd != "" {
client.Auth(mcUser, mcPasswd)
if err != nil {
log.Panic(err)
}
}
//
// Initialize UploadHandler
//
conf := jfu.DefaultConfig
conf.MaxFileSize = 100 << 10 // 100kb
uh := jfu.UploadHandler{
Prefix: "/jfu",
Store: &store,
Conf: &conf,
Cache: client,
}
//
// Register Handlers
//
http.Handle("/jfu", &uh)
http.Handle("/jfu/", &uh)
log.Println("Serve JFU")
path := http.Dir(filepath.Join(pathRoot, "static"))
http.Handle("/", http.FileServer(path))
log.Println("Serve files from ", path)
//
// Start the webserver
//
addr := "0.0.0.0:" + port
log.Println("Starting webserver on", addr, "...")
log.Fatal(http.ListenAndServe(addr, nil))
}