simpleserver/server.go

46 lines
1.1 KiB
Go
Raw Normal View History

2018-12-09 00:51:40 +01:00
package simpleserver
import (
"fmt"
2020-10-11 13:26:11 +02:00
"io/ioutil"
2018-12-09 00:51:40 +01:00
"net/http"
"os"
"os/signal"
"path/filepath"
2018-12-09 00:51:40 +01:00
)
func viewHandler(root string, w http.ResponseWriter, r *http.Request) {
file := filepath.Join(root, filepath.FromSlash(r.URL.Path[1:]))
2018-12-09 00:51:40 +01:00
info, err := os.Stat(file)
if err != nil {
fmt.Fprint(w, err)
return
}
if info.IsDir() {
file = filepath.Join(file, "index.html")
2018-12-09 00:51:40 +01:00
}
fmt.Println("GET " + file)
2020-10-11 13:26:11 +02:00
content, _ := ioutil.ReadFile(file)
fmt.Fprint(w, string(content))
2018-12-09 00:51:40 +01:00
}
func Serve(root string) {
address := "127.0.0.1:8000"
fmt.Println("Serving " + root + " at http://" + address + " ...")
2018-12-09 00:51:40 +01:00
fmt.Println("Use Ctrl+C to exit")
fmt.Println("(This is not a production web server, don't get any funny ideas)")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { viewHandler(root, w, r) })
srv := &http.Server{Addr: address}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
fmt.Println("Received interrupt, closing...")
srv.Close()
}()
err := srv.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
fmt.Fprintln(os.Stderr, err)
}
}