src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

static.go (868B)


      1 package site
      2 
      3 import (
      4 	"fmt"
      5 	"net/http"
      6 	"path/filepath"
      7 )
      8 
      9 func (s *Site) static(w http.ResponseWriter, r *http.Request) {
     10 	if r.Method != http.MethodGet {
     11 		w.WriteHeader(http.StatusMethodNotAllowed)
     12 		return
     13 	}
     14 
     15 	f, err := s.files.ReadFile(r.URL.Path[1:])
     16 	if err != nil {
     17 		s.error(w, r, &Error{
     18 			Code:  http.StatusNotFound,
     19 			Error: fmt.Errorf("failed to open: %v", err),
     20 			Message: fmt.Sprintf(
     21 				"Failed to retrieve file: %s",
     22 				r.URL.Path,
     23 			),
     24 		})
     25 		return
     26 	}
     27 
     28 	switch filepath.Ext(r.URL.Path) {
     29 	case ".css":
     30 		w.Header().Add("Content-Type", "text/css; charset=utf-8")
     31 	case ".js":
     32 		w.Header().Add("Content-Type", "text/javascript; charset=utf-8")
     33 	case ".svg":
     34 		w.Header().Add("Content-Type", "image/svg+xml; charset=utf-8")
     35 	default:
     36 		w.Header().Add("Content-Type", http.DetectContentType(f))
     37 	}
     38 
     39 	w.WriteHeader(http.StatusOK)
     40 	w.Write(f)
     41 }