Skip to content

Commit f38f0b1

Browse files
committed
add simpleHTTPServer example (similar to python -m SimpleHTTPServer)
1 parent 62b0a21 commit f38f0b1

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# simpleHTTPServer
2+
3+
many may have used the simple python web server SimpleHTTPServer:
4+
5+
```
6+
python -m SimpleHTTPServer 8080
7+
```
8+
9+
the same functionality can be recreated in Go with just a few lines of code:
10+
11+
```go
12+
package main
13+
14+
import (
15+
"log"
16+
"net/http"
17+
"os"
18+
)
19+
20+
func Log(handler http.Handler) http.Handler {
21+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
22+
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
23+
handler.ServeHTTP(w, r)
24+
})
25+
}
26+
27+
28+
func main() {
29+
// default settings
30+
port := "8080"
31+
dir := os.Getenv("PWD")
32+
33+
// get settings from command line
34+
if len(os.Args) > 1 {
35+
port = os.Args[1]
36+
if len(os.Args) > 2 {
37+
dir = os.Args[2]
38+
}
39+
}
40+
41+
// start web server with logging
42+
log.Fatal(http.ListenAndServe(":"+port, Log(http.FileServer(http.Dir(dir)))))
43+
}
44+
```
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package main
2+
3+
import (
4+
"log"
5+
"net/http"
6+
"os"
7+
)
8+
9+
func Log(handler http.Handler) http.Handler {
10+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
11+
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
12+
handler.ServeHTTP(w, r)
13+
})
14+
}
15+
16+
17+
func main() {
18+
// default settings
19+
port := "8080"
20+
dir := os.Getenv("PWD")
21+
22+
// get settings from command line
23+
if len(os.Args) > 1 {
24+
port = os.Args[1]
25+
if len(os.Args) > 2 {
26+
dir = os.Args[2]
27+
}
28+
}
29+
30+
// start web server with logging
31+
log.Fatal(http.ListenAndServe(":"+port, Log(http.FileServer(http.Dir(dir)))))
32+
}

0 commit comments

Comments
 (0)