File: httputil.go

package info (click to toggle)
golang-github-shurcool-httpfs 0.0~git20230704.f1e31cf-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 120 kB
  • sloc: makefile: 2
file content (32 lines) | stat: -rw-r--r-- 822 bytes parent folder | download | duplicates (3)
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
// Package httputil implements HTTP utility functions for http.FileSystem.
package httputil

import (
	"log"
	"net/http"

	"github.com/shurcooL/httpgzip"
)

// FileHandler is an http.Handler that serves the root of File,
// which is expected to be a normal file (not a directory).
type FileHandler struct {
	File http.FileSystem
}

func (h FileHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	f, err := h.File.Open("/")
	if err != nil {
		log.Printf("FileHandler.File.Open('/'): %v\n", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer f.Close()
	fi, err := f.Stat()
	if err != nil {
		log.Printf("FileHandler.File.Stat('/'): %v\n", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	httpgzip.ServeContent(w, req, fi.Name(), fi.ModTime(), f)
}