2013-03-18 09:48:50 -07:00
|
|
|
package blob
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"compress/gzip"
|
2013-04-09 03:12:24 -07:00
|
|
|
"fmt"
|
2013-03-18 09:48:50 -07:00
|
|
|
"io"
|
|
|
|
"net/http"
|
2013-03-22 04:03:31 -07:00
|
|
|
"strings"
|
2013-08-12 08:18:02 -07:00
|
|
|
|
|
|
|
"github.com/golang/glog"
|
2013-03-18 09:48:50 -07:00
|
|
|
)
|
|
|
|
|
2014-12-10 07:16:49 -08:00
|
|
|
// Sub-directories for templates and static content.
|
2013-03-19 08:11:55 -07:00
|
|
|
const (
|
|
|
|
TemplateFiles = "templates"
|
2013-03-19 08:28:55 -07:00
|
|
|
StaticFiles = "static"
|
2013-03-19 08:11:55 -07:00
|
|
|
)
|
|
|
|
|
2013-03-22 04:03:31 -07:00
|
|
|
var mimeMap = map[string]string{
|
2013-04-24 09:51:07 -07:00
|
|
|
"css": "text/css",
|
|
|
|
"js": "text/javascript",
|
|
|
|
"descriptor": "application/vnd.google.protobuf;proto=google.protobuf.FileDescriptorSet",
|
2013-03-22 04:03:31 -07:00
|
|
|
}
|
|
|
|
|
2014-12-10 07:16:49 -08:00
|
|
|
// GetFile retrieves the content of an embedded file.
|
2013-03-18 09:48:50 -07:00
|
|
|
func GetFile(bucket string, name string) ([]byte, error) {
|
2013-04-09 03:12:24 -07:00
|
|
|
blob, ok := files[bucket][name]
|
|
|
|
if !ok {
|
2014-12-10 07:16:49 -08:00
|
|
|
return nil, fmt.Errorf("could not find %s/%s (missing or updated files.go?)", bucket, name)
|
2013-04-09 03:12:24 -07:00
|
|
|
}
|
|
|
|
reader := bytes.NewReader(blob)
|
2013-03-18 09:48:50 -07:00
|
|
|
gz, err := gzip.NewReader(reader)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var b bytes.Buffer
|
|
|
|
io.Copy(&b, gz)
|
|
|
|
gz.Close()
|
|
|
|
|
|
|
|
return b.Bytes(), nil
|
|
|
|
}
|
|
|
|
|
2014-12-10 07:16:49 -08:00
|
|
|
// Handler implements http.Handler.
|
2013-03-18 09:48:50 -07:00
|
|
|
type Handler struct{}
|
|
|
|
|
|
|
|
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2013-04-09 03:12:24 -07:00
|
|
|
name := r.URL.Path
|
2013-03-18 09:48:50 -07:00
|
|
|
if name == "" {
|
|
|
|
name = "index.html"
|
|
|
|
}
|
|
|
|
|
2013-03-19 08:11:55 -07:00
|
|
|
file, err := GetFile(StaticFiles, name)
|
2013-03-18 09:48:50 -07:00
|
|
|
if err != nil {
|
|
|
|
if err != io.EOF {
|
2013-08-12 09:22:48 -07:00
|
|
|
glog.Warning("Could not get file: ", err)
|
2013-03-18 09:48:50 -07:00
|
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
|
|
return
|
|
|
|
}
|
2013-03-22 04:03:31 -07:00
|
|
|
contentType := http.DetectContentType(file)
|
|
|
|
if strings.Contains(contentType, "text/plain") || strings.Contains(contentType, "application/octet-stream") {
|
|
|
|
parts := strings.Split(name, ".")
|
|
|
|
contentType = mimeMap[parts[len(parts)-1]]
|
|
|
|
}
|
|
|
|
w.Header().Set("Content-Type", contentType)
|
2013-07-24 09:52:57 -07:00
|
|
|
w.Header().Set("Cache-Control", "public, max-age=259200")
|
2013-03-18 09:48:50 -07:00
|
|
|
w.Write(file)
|
|
|
|
}
|