ServeFileFromArchive serves a file from the given archive.
(w http.ResponseWriter, r *http.Request, archiveName string, archiveFS *zipfs.FileSystem, path string)
| 110 | |
| 111 | // ServeFileFromArchive serves a file from the given archive. |
| 112 | func 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. |
| 153 | func redirectToDefault(w http.ResponseWriter, r *http.Request) { |