Skip to content

Commit f5801f2

Browse files
committed
Add serve command
1 parent d484880 commit f5801f2

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

internal/cmd/serve.go

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package cmd
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"log"
7+
"net"
8+
"net/http"
9+
"os"
10+
11+
"github.com/pborman/getopt"
12+
)
13+
14+
type server struct {
15+
status int
16+
includeHeaders bool
17+
includeMethod bool
18+
includeUrl bool
19+
headersIncluded bool
20+
listener net.Listener
21+
data io.ReadSeeker
22+
}
23+
24+
func init() {
25+
Commands["serve"] = serveCommand
26+
}
27+
28+
func serveHelp() {
29+
fmt.Println("Usage: please serve <PATH> [<ADDRESS>[:<PORT>]]")
30+
fmt.Println()
31+
fmt.Println("Serves the contents of PATH on the specified address and port.")
32+
fmt.Println("Requested paths will be printed to stdout.")
33+
}
34+
35+
type loggingFileSystem struct {
36+
http.FileSystem
37+
}
38+
39+
func (fsys loggingFileSystem) Open(path string) (http.File, error) {
40+
fmt.Println(path)
41+
42+
return fsys.FileSystem.Open(path)
43+
}
44+
45+
func serveCommand(args []string) {
46+
opts := getopt.CommandLine
47+
48+
opts.SetUsage(serveHelp)
49+
50+
// Deal with flags and get the path (and URL)
51+
opts.Parse(args)
52+
if opts.NArgs() < 1 {
53+
getopt.Usage()
54+
os.Exit(1)
55+
}
56+
57+
path := opts.Arg(0)
58+
59+
address := "0.0.0.0:8000"
60+
61+
if opts.NArgs() >= 2 {
62+
address = opts.Arg(1)
63+
}
64+
65+
fmt.Println("Listening on", address)
66+
67+
fsys := loggingFileSystem{http.Dir(path)}
68+
log.Fatal(http.ListenAndServe(address, http.FileServer(fsys)))
69+
}

main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ func printHelp() {
1515
fmt.Println(" request Make a web request and output the result")
1616
fmt.Println(" respond Listen for a web request and respond to it")
1717
fmt.Println(" parse Get values from structured data and convert between formats")
18+
fmt.Println(" serve Serve a folder as a web site")
1819
fmt.Println()
1920
fmt.Println("Run 'please COMMAND' for more information on a command.")
2021
}

0 commit comments

Comments
 (0)