-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserve.go
52 lines (41 loc) · 842 Bytes
/
serve.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
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
)
func servePost(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
filename, ok := vars["id"]
if !ok {
writeError(writer, fmt.Errorf("not found"), http.StatusNotFound)
return
}
post, ok := requestedPosts[filename]
if !ok {
writeError(writer, fmt.Errorf("not found"), http.StatusNotFound)
return
}
file, err := os.Open(post.path)
if err != nil {
writeError(writer, err, http.StatusInternalServerError)
return
}
defer func() {
err = file.Close()
if err != nil {
log.Printf("unable to close file %v\n", err)
}
return
}()
_, err = io.Copy(writer, file)
if err != nil {
writeError(writer, err, http.StatusInternalServerError)
return
}
delete(requestedPosts, filename)
return
}