Skip to content

Instantly share code, notes, and snippets.

@hoshi-takanori
Last active August 29, 2015 14:21
Show Gist options
  • Save hoshi-takanori/caba1b570ec5b072e16c to your computer and use it in GitHub Desktop.
Save hoshi-takanori/caba1b570ec5b072e16c to your computer and use it in GitHub Desktop.
Custom http.FileServer to overwrite Content-Type header.
package main
import (
"net/http"
"strings"
)
var CustomTypeMap = map[string]string{
"text/x-java-source": "text/plain",
}
type CustomResponseWriter struct {
w http.ResponseWriter
}
func (cw CustomResponseWriter) Header() http.Header {
return cw.w.Header()
}
func (cw CustomResponseWriter) Write(b []byte) (int, error) {
return cw.w.Write(b)
}
func (cw CustomResponseWriter) WriteHeader(code int) {
contentType := cw.Header().Get("Content-Type")
for k, v := range CustomTypeMap {
if contentType == k || strings.HasPrefix(contentType, k + ";") {
cw.Header().Set("Content-Type", strings.Replace(contentType, k, v, 1))
break
}
}
cw.w.WriteHeader(code)
}
func CustomFileServer(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(CustomResponseWriter{w}, r)
}
}
func main() {
http.Handle("/", CustomFileServer(http.FileServer(http.Dir("public"))))
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment