forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restful-serve-static.go
47 lines (38 loc) · 1.18 KB
/
restful-serve-static.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
package main
import (
"fmt"
"net/http"
"path"
"github.com/emicklei/go-restful"
)
// This example shows how to define methods that serve static files
// It uses the standard http.ServeFile method
//
// GET http://localhost:8080/static/test.xml
// GET http://localhost:8080/static/
//
// GET http://localhost:8080/static?resource=subdir/test.xml
var rootdir = "/tmp"
func main() {
restful.DefaultContainer.Router(restful.CurlyRouter{})
ws := new(restful.WebService)
ws.Route(ws.GET("/static/{subpath:*}").To(staticFromPathParam))
ws.Route(ws.GET("/static").To(staticFromQueryParam))
restful.Add(ws)
println("[go-restful] serving files on http://localhost:8080/static from local /tmp")
http.ListenAndServe(":8080", nil)
}
func staticFromPathParam(req *restful.Request, resp *restful.Response) {
actual := path.Join(rootdir, req.PathParameter("subpath"))
fmt.Printf("serving %s ... (from %s)\n", actual, req.PathParameter("subpath"))
http.ServeFile(
resp.ResponseWriter,
req.Request,
actual)
}
func staticFromQueryParam(req *restful.Request, resp *restful.Response) {
http.ServeFile(
resp.ResponseWriter,
req.Request,
path.Join(rootdir, req.QueryParameter("resource")))
}