MCPcopy
hub / github.com/safing/portmaster / ServeFileFromArchive

Function ServeFileFromArchive

service/ui/serve.go:112–150  ·  view source on GitHub ↗

ServeFileFromArchive serves a file from the given archive.

(w http.ResponseWriter, r *http.Request, archiveName string, archiveFS *zipfs.FileSystem, path string)

Source from the content-addressed store, hash-verified

110
111// ServeFileFromArchive serves a file from the given archive.
112func ServeFileFromArchive(w http.ResponseWriter, r *http.Request, archiveName string, archiveFS *zipfs.FileSystem, path string) {
113 readCloser, err := archiveFS.Open(path)
114 if err != nil {
115 if errors.Is(err, fs.ErrNotExist) {
116 // Check if there is a base index.html file we can serve instead.
117 var indexErr error
118 path = "index.html"
119 readCloser, indexErr = archiveFS.Open(path)
120 if indexErr != nil {
121 // If we cannot get an index, continue with handling the original error.
122 log.Tracef("ui: requested resource \"%s\" not found in archive %s: %s", path, archiveName, err)
123 http.Error(w, err.Error(), http.StatusNotFound)
124 return
125 }
126 } else {
127 log.Tracef("ui: error opening module %s: %s", archiveName, err)
128 http.Error(w, err.Error(), http.StatusInternalServerError)
129 return
130 }
131 }
132
133 // set content type
134 _, ok := w.Header()["Content-Type"]
135 if !ok {
136 contentType, _ := utils.MimeTypeByExtension(filepath.Ext(path))
137 w.Header().Set("Content-Type", contentType)
138 }
139
140 w.WriteHeader(http.StatusOK)
141 if r.Method != http.MethodHead {
142 _, err = io.Copy(w, readCloser)
143 if err != nil {
144 log.Errorf("ui: failed to serve file: %s", err)
145 return
146 }
147 }
148
149 _ = readCloser.Close()
150}
151
152// redirectToDefault redirects the request to the default UI module.
153func redirectToDefault(w http.ResponseWriter, r *http.Request) {

Callers 1

ServeHTTPMethod · 0.85

Calls 10

TracefFunction · 0.92
MimeTypeByExtensionFunction · 0.92
ErrorfFunction · 0.92
HeaderMethod · 0.80
WriteHeaderMethod · 0.80
ErrorMethod · 0.65
SetMethod · 0.65
CloseMethod · 0.65
IsMethod · 0.45
CopyMethod · 0.45

Tested by

no test coverage detected