/
server.go
236 lines (186 loc) · 5.67 KB
/
server.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package main
import (
"io"
"io/ioutil"
"net/http"
"bytes"
"os"
"fmt"
"log"
//"path/filepath"
"strings"
//"image/draw"
"image"
"image/jpeg"
_ "image/png"
"code.google.com/p/graphics-go/graphics"
"container/heap"
"encoding/json"
"regexp"
"path"
"runtime"
"strconv"
)
var config *ServerConfig
//var icache map[string]*bytes.Reader
var icache *ImageCache = NewImageCache()
func main() {
if runtime.NumCPU() > 2 {
runtime.GOMAXPROCS( runtime.NumCPU() -1 )
}
var err error
config, err = loadImageCacheConfig()
if err != nil {
fmt.Println("Error parsing config: " + err.Error())
return
}
fmt.Println(config)
port := strconv.Itoa(config.Port)
if len( os.Args ) > 1 {
port = os.Args[1]
}
http.HandleFunc( "/", func( resp http.ResponseWriter, req *http.Request ) {
//vals := req.URL.Path
io.WriteString( resp, "Hello world!\n" + req.URL.Path )
})
http.HandleFunc( "/index.json", func(r http.ResponseWriter, req *http.Request) {
indexJson(config, r, req)
})
relHandler( "/thumb/", serveThumb )
listenOn := "localhost:" + port
fmt.Println( "listening on " + listenOn )
http.ListenAndServe(listenOn, nil )
}
func indexJson( config *ServerConfig, resp http.ResponseWriter, req *http.Request ) {
var outerr error
fmt.Println(config)
defer func() {
if recover() != nil {
if outerr == nil {
http.Error( resp, "Internal Server Error", 500 )
} else {
http.Error( resp, outerr.Error(), 500 )
}
}
}()
root := req.URL.Query().Get( "root" )
if root != "" {
root = path.Clean( root )
}
//TODO: make dir scanning possible.
dir, err := os.Open( config.Root + "/" + root )
defer dir.Close()
if err != nil {
log.Panic( "ERROR: Could not read directory" )
}
//TODO: Filter out non-images
filestats, err := dir.Readdir( -1 )
if err != nil {
log.Panic( "ERROR: Could not read directory" )
}
files := make([]string, 0, len(filestats))
for _, file := range filestats {
if file.IsDir() && file.Name()[0] != '.' {
files = append( files, root + "/" + file.Name() + "/" )
} else if isImage( file ) {
files = append( files, root + "/" + file.Name() )
}
}
out := map[string]interface{}{
"status": "OK",
"files": files,
}
if bytes, err := json.Marshal( out ); err == nil {
resp.Write( bytes )
} else {
io.WriteString( resp, "[]" )
}
}
var imgRE *regexp.Regexp = nil
func isImage( f os.FileInfo ) (bool) {
if imgRE == nil {
imgRE = regexp.MustCompile( `(?i)\.(png|jpg|gif)$` )
}
return imgRE.MatchString( f.Name() )
}
func serveThumb( resp http.ResponseWriter, req *http.Request, path string ) {
var outerr error
log.Println( "Requested image", path )
//log.Println( "Oldest: ", icache.Top() )
//log.Println( "heap: ", icache.GetPaths() )
defer func() {
if recover() != nil {
if outerr == nil {
http.Error( resp, "Internal Server Error", 500 )
} else {
http.Error( resp, outerr.Error(), 500 )
}
}
}()
/*
if icache == nil {
//icache = make( map[string]*bytes.Reader, 100 )
icache = &ImageCache{}
}
*/
cached, ok := icache.Find( path )
if ok {
icache.Update( path )
} else {
log.Println( "Generating thumbnail" )
fd, err := os.Open( config.Root + "/" + path )
defer fd.Close()
if err != nil {
outerr = err;
log.Panic( "ERROR: file open error ", err.Error() )
}
img, _, err := image.Decode( fd )
if err != nil {
outerr = err;
log.Panic( "ERROR: Could not decode. ", err.Error() )
}
scaled := image.NewRGBA( image.Rect( 0, 0, 100, 100 ) )
graphics.Thumbnail( scaled, img )
var buf bytes.Buffer
err = jpeg.Encode( &buf, scaled, &jpeg.Options{jpeg.DefaultQuality} )
if err != nil {
outerr = err;
log.Panic( "ERROR: could not encode to jpeg. ", err.Error() )
}
data, err := ioutil.ReadAll( &buf )
if err != nil {
outerr = err;
log.Panic( "ERROR: ", err.Error() )
}
cached = bytes.NewReader( data )
heap.Push( icache, NewCacheItem( path, cached ) )
if icache.Len() > config.MaxImages {
log.Println( "Dropping oldest cache: ", heap.Pop( icache ).(*CacheItem).path )
}
//icache[ path ] = cached
}
cached.Seek( 0, 0 )
io.Copy( resp, cached )
}
func relHandler( prefix string, handler func( http.ResponseWriter, *http.Request, string ) ) {
// -1 for the trailing slash. /foo/ should be 2
prefLen := len( strings.Split( prefix, "/" ) ) - 1
http.HandleFunc( prefix, relServer( handler, prefLen ) )
}
func relServer( handler func( http.ResponseWriter, *http.Request, string ), prefixLength int ) ( func( http.ResponseWriter, *http.Request ) ) {
return func( resp http.ResponseWriter, req *http.Request ) {
suffix := pathStripPrefix( req.URL.Path, prefixLength )
handler( resp, req, suffix )
}
}
func pathStripPrefix( path string, num int ) (string) {
pathparts := strings.Split( path, "/" )
if num >= len( pathparts ) { return "" }
return strings.Join( pathparts[ num: ], "/" )
}
/*
func pathSuffix( path string, prefix string ) {
preparts := strings.Split( prefix, "/" )
pathparts := strings.Split( path, "/" )
}
*/