Skip to content

Commit

Permalink
Serve a directory
Browse files Browse the repository at this point in the history
  • Loading branch information
tschaub committed Sep 6, 2023
0 parents commit 2df5c7c
Show file tree
Hide file tree
Showing 6 changed files with 362 additions and 0 deletions.
8 changes: 8 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module github.com/tschaub/host

go 1.21.0

require (
github.com/alecthomas/kong v0.8.0
github.com/rs/cors v1.9.0
)
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
github.com/alecthomas/assert/v2 v2.1.0 h1:tbredtNcQnoSd3QBhQWI7QZ3XHOVkw1Moklp2ojoH/0=
github.com/alecthomas/assert/v2 v2.1.0/go.mod h1:b/+1DI2Q6NckYi+3mXyH3wFb8qG37K/DuK80n7WefXA=
github.com/alecthomas/kong v0.8.0 h1:ryDCzutfIqJPnNn0omnrgHLbAggDQM2VWHikE1xqK7s=
github.com/alecthomas/kong v0.8.0/go.mod h1:n1iCIO2xS46oE8ZfYCNDqdR0b0wZNrXAIAqro/2132U=
github.com/alecthomas/repr v0.1.0 h1:ENn2e1+J3k09gyj2shc0dHr/yjaWSHRlrJ4DPMevDqE=
github.com/alecthomas/repr v0.1.0/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8=
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
github.com/rs/cors v1.9.0 h1:l9HGsTsHJcvW14Nk7J9KFz8bzeAWXn3CG6bgt7LsrAE=
github.com/rs/cors v1.9.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
117 changes: 117 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<!DOCTYPE html>
<html>

<head>
<meta charSet="utf-8">
<title>Index of {{.Dir}}</title>
<style>
:root {
--body-bg: #FFFFFF;
--body-color: #4B4B4B;
}

ul a.file::before {
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="20" height="20" viewBox="0 0 50 50"><path fill="%234B4B4B" d="M 7 2 L 7 48 L 43 48 L 43 14.59375 L 42.71875 14.28125 L 30.71875 2.28125 L 30.40625 2 Z M 9 4 L 29 4 L 29 16 L 41 16 L 41 46 L 9 46 Z M 31 5.4375 L 39.5625 14 L 31 14 Z"></path></svg>');
}

ul a.folder::before {
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="20" height="20" viewBox="0 0 50 50"><path fill="%234B4B4B" d="M 5 4 C 3.3550302 4 2 5.3550302 2 7 L 2 16 L 2 18 L 2 43 C 2 44.64497 3.3550302 46 5 46 L 45 46 C 46.64497 46 48 44.64497 48 43 L 48 19 L 48 16 L 48 11 C 48 9.3550302 46.64497 8 45 8 L 18 8 C 18.08657 8 17.96899 8.000364 17.724609 7.71875 C 17.480227 7.437136 17.179419 6.9699412 16.865234 6.46875 C 16.55105 5.9675588 16.221777 5.4327899 15.806641 4.9628906 C 15.391504 4.4929914 14.818754 4 14 4 L 5 4 z M 5 6 L 14 6 C 13.93925 6 14.06114 6.00701 14.308594 6.2871094 C 14.556051 6.5672101 14.857231 7.0324412 15.169922 7.53125 C 15.482613 8.0300588 15.806429 8.562864 16.212891 9.03125 C 16.619352 9.499636 17.178927 10 18 10 L 45 10 C 45.56503 10 46 10.43497 46 11 L 46 13.1875 C 45.685108 13.07394 45.351843 13 45 13 L 5 13 C 4.6481575 13 4.3148915 13.07394 4 13.1875 L 4 7 C 4 6.4349698 4.4349698 6 5 6 z M 5 15 L 45 15 C 45.56503 15 46 15.43497 46 16 L 46 19 L 46 43 C 46 43.56503 45.56503 44 45 44 L 5 44 C 4.4349698 44 4 43.56503 4 43 L 4 18 L 4 16 C 4 15.43497 4.4349698 15 5 15 z"></path></svg>');
}

@media (prefers-color-scheme: dark) {
:root {
--body-bg: #0d0d0d;
--body-color: #FFFFFF;
}

ul a.file::before {
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="20" height="20" viewBox="0 0 50 50"><path fill="%23FFFFFF" d="M 7 2 L 7 48 L 43 48 L 43 14.59375 L 42.71875 14.28125 L 30.71875 2.28125 L 30.40625 2 Z M 9 4 L 29 4 L 29 16 L 41 16 L 41 46 L 9 46 Z M 31 5.4375 L 39.5625 14 L 31 14 Z"></path></svg>');
}

ul a.folder::before {
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="20" height="20" viewBox="0 0 50 50"><path fill="%23FFFFFF" d="M 5 4 C 3.3550302 4 2 5.3550302 2 7 L 2 16 L 2 18 L 2 43 C 2 44.64497 3.3550302 46 5 46 L 45 46 C 46.64497 46 48 44.64497 48 43 L 48 19 L 48 16 L 48 11 C 48 9.3550302 46.64497 8 45 8 L 18 8 C 18.08657 8 17.96899 8.000364 17.724609 7.71875 C 17.480227 7.437136 17.179419 6.9699412 16.865234 6.46875 C 16.55105 5.9675588 16.221777 5.4327899 15.806641 4.9628906 C 15.391504 4.4929914 14.818754 4 14 4 L 5 4 z M 5 6 L 14 6 C 13.93925 6 14.06114 6.00701 14.308594 6.2871094 C 14.556051 6.5672101 14.857231 7.0324412 15.169922 7.53125 C 15.482613 8.0300588 15.806429 8.562864 16.212891 9.03125 C 16.619352 9.499636 17.178927 10 18 10 L 45 10 C 45.56503 10 46 10.43497 46 11 L 46 13.1875 C 45.685108 13.07394 45.351843 13 45 13 L 5 13 C 4.6481575 13 4.3148915 13.07394 4 13.1875 L 4 7 C 4 6.4349698 4.4349698 6 5 6 z M 5 15 L 45 15 C 45.56503 15 46 15.43497 46 16 L 46 19 L 46 43 C 46 43.56503 45.56503 44 45 44 L 5 44 C 4.4349698 44 4 43.56503 4 43 L 4 18 L 4 16 C 4 15.43497 4.4349698 15 5 15 z"></path></svg>');
}
}

body {
margin: 0;
padding: 30px;
background: var(--body-bg);
color: var(--body-color);
font-family: sans-serif;
}

header {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}

h1 {
font-size: 16px;
}

a {
color: var(--body-color);
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

ul {
display: flex;
flex-wrap: wrap;
}

ul li {
width: 230px;
padding-right: 20px;
}

ul a {
padding: 10px 5px;
white-space: nowrap;
overflow: hidden;
display: block;
width: 100%;
text-overflow: ellipsis;
}

ul {
margin: 0;
padding: 20px 0;
}

ul li {
list-style: none;
font-size: 14px;
display: flex;
justify-content: space-between;
}

ul a::before {
vertical-align: middle;
margin-right: 10px;
}
</style>
</head>

<body>
<header>
<h1>
Index of
{{range $i, $e := .Parents}}{{if $i}}/{{end}}<a href="{{$e.Path}}">{{$e.Name}}</a>{{end}}
</h1>
</header>
<ul>
{{range .Entries}}
<li>
<a href="{{.Path}}" class="{{.Type}}">{{.Name}}</a>
</li>
{{end}}
</ul>
</body>

</html>
23 changes: 23 additions & 0 deletions license.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# License for host

The host module is distributed under the MIT license. Find the full source
here: http://tschaub.mit-license.org/

Copyright Tim Schaub.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
188 changes: 188 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
package main

import (
_ "embed"
"errors"
"fmt"
"html/template"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strings"

"github.com/alecthomas/kong"
"github.com/rs/cors"
)

func main() {
ctx := kong.Parse(&ServeCmd{}, kong.UsageOnError())
err := ctx.Run()
ctx.FatalIfErrorf(err)
}

type ServeCmd struct {
Port int `help:"Listen on this port." default:"4000"`
Dir string `help:"Serve files from this directory." arg:"" type:"existingdir"`
Cors bool `help:"Include CORS support (on by default)." default:"true" negatable:""`
Dot bool `help:"Serve dot files (files prefixed with a '.')" default:"false"`
}

func (c *ServeCmd) Run() error {
server := &Server{
dir: c.Dir,
port: c.Port,
cors: c.Cors,
dot: c.Dot,
}

return server.Start()
}

type Server struct {
dir string
port int
cors bool
dot bool
}

func excludeDot(handler http.Handler) http.Handler {
return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
parts := strings.Split(request.URL.Path, "/")
for _, part := range parts {
if strings.HasPrefix(part, ".") {
http.NotFound(response, request)
return
}
}

handler.ServeHTTP(response, request)
})
}

type IndexData struct {
Dir string
Parents []*Entry
Entries []*Entry
}

type Entry struct {
Name string
Path string
Type string
}

const (
fileType = "file"
folderType = "folder"
)

//go:embed index.html
var indexHtml string

func withIndex(dir string, dot bool, handler http.Handler) http.Handler {
indexTemplate := template.Must(template.New("index").Parse(indexHtml))
base := filepath.Base(dir)
return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
urlPath := request.URL.Path
if !strings.HasSuffix(urlPath, "/") {
handler.ServeHTTP(response, request)
return
}

dirPath := filepath.Join(dir, urlPath)
list, dirErr := os.ReadDir(dirPath)
if dirErr != nil {
if errors.Is(dirErr, os.ErrNotExist) {
http.NotFound(response, request)
return
}
http.Error(response, dirErr.Error(), http.StatusInternalServerError)
return
}

entries := []*Entry{}
for _, item := range list {
name := item.Name()
if !dot && strings.HasPrefix(name, ".") {
continue
}
entry := &Entry{
Name: name,
Path: path.Join(urlPath, name),
}
if item.IsDir() {
entry.Type = folderType
entry.Path = entry.Path + "/"
} else {
entry.Type = fileType
}
entries = append(entries, entry)
}
sort.Slice(entries, func(i int, j int) bool {
iEntry := entries[i]
jEntry := entries[j]
if iEntry.Type == folderType && jEntry.Type != folderType {
return true
}
if jEntry.Type == folderType && iEntry.Type != folderType {
return false
}
return iEntry.Name < jEntry.Name
})

if urlPath != "/" {
parentEntry := &Entry{
Name: "..",
Path: path.Join(urlPath, ".."),
Type: folderType,
}
entries = append([]*Entry{parentEntry}, entries...)
}

parentParts := strings.Split(urlPath, "/")
parentParts = parentParts[:len(parentParts)-1]
parentEntries := make([]*Entry, len(parentParts))
for i, part := range parentParts {
entry := &Entry{
Name: part,
Path: strings.Join(parentParts[:i+1], "/") + "/",
Type: folderType,
}
if part == "" {
entry.Name = base
}
parentEntries[i] = entry
}

data := &IndexData{
Dir: filepath.Join(base, urlPath),
Entries: entries,
Parents: parentEntries,
}

response.WriteHeader(http.StatusOK)
if err := indexTemplate.Execute(response, data); err != nil {
fmt.Printf("trouble executing template: %s\n", err)
}
})
}

func (s *Server) Start() error {
mux := http.NewServeMux()

dir := http.Dir(s.dir)
mux.Handle("/", http.FileServer(dir))

handler := withIndex(string(dir), s.dot, http.Handler(mux))
if !s.dot {
handler = excludeDot(handler)
}
if s.cors {
handler = cors.Default().Handler(handler)
}

fmt.Printf("Serving %s on http://localhost:%d/\n", s.dir, s.port)
return http.ListenAndServe(fmt.Sprintf(":%d", s.port), handler)
}
16 changes: 16 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# host

Serve files via HTTP.

```
Usage: host <dir>
Arguments:
<dir> Serve files from this directory.
Flags:
-h, --help Show context-sensitive help.
--port=4000 Listen on this port.
--[no-]cors Include CORS support (on by default).
--dot Serve dot files (files prefixed with a '.')
```

0 comments on commit 2df5c7c

Please sign in to comment.