-
Notifications
You must be signed in to change notification settings - Fork 129
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Allow web serving of user files (#1457)
* Environment Variable to override WSAddr * Add command line and Env Variable config items * Create MyFiles Web Endpoint * Remove debug log left by mistake * Make Myfiles Directory Configurable --------- Co-authored-by: crwxaj <52156245+crwxaj@users.noreply.github.com>
- Loading branch information
Showing
3 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
package server | ||
|
||
import ( | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"os" | ||
"path/filepath" | ||
"strings" | ||
|
||
"github.com/xbapps/xbvr/pkg/common" | ||
) | ||
|
||
type MyFilesHandler struct { | ||
} | ||
|
||
func (h MyFilesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | ||
path := filepath.Join(common.MyFilesDir, r.URL.Path) | ||
fi, err := os.Stat(path) | ||
|
||
if os.IsNotExist(err) || strings.Contains(path, "..") { // check the path exists and not trying to go up directory levels | ||
// file does not exist | ||
http.Error(w, err.Error(), http.StatusNotFound) | ||
return | ||
} | ||
|
||
//copy the relevant headers. If you want to preserve the downloaded file name, extract it with go's url parser. | ||
if strings.HasSuffix(path, ".json") { | ||
w.Header().Set("Content-Type", r.Header.Get("application/json")) | ||
} | ||
w.Header().Set("Content-Length", fmt.Sprint(fi.Size())) // useful for download progress | ||
|
||
//stream the body to the client without fully loading it into memory | ||
reader, _ := os.Open(path) | ||
io.Copy(w, reader) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters