41 lines
1.1 KiB
Go
41 lines
1.1 KiB
Go
/* The following code has been taken from https://github.com/fogleman/serve and it is used on this project as a library */
|
|
/* Attribution goes to its original author */
|
|
package aya
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
// ResponseWriter wraps http.ResponseWriter to capture the HTTP status code
|
|
type ResponseWriter struct {
|
|
http.ResponseWriter
|
|
StatusCode int
|
|
}
|
|
|
|
func (w *ResponseWriter) WriteHeader(statusCode int) {
|
|
w.StatusCode = statusCode
|
|
w.ResponseWriter.WriteHeader(statusCode)
|
|
}
|
|
|
|
// Handler wraps http.Handler to log served files
|
|
type Handler struct {
|
|
http.Handler
|
|
}
|
|
|
|
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
rw := &ResponseWriter{w, 0}
|
|
h.Handler.ServeHTTP(rw, r)
|
|
log.Println(r.RemoteAddr, r.Method, rw.StatusCode, r.URL)
|
|
}
|
|
|
|
// This function is called by the `aya serve` subcommand
|
|
func HttpServe(Dir string, Port int) {
|
|
handler := &Handler{http.FileServer(http.Dir(Dir))}
|
|
http.Handle("/", handler)
|
|
addr := fmt.Sprintf("127.0.0.1:%d", Port)
|
|
log.Printf("[aya.HttpServe] Listening on %s\n", addr)
|
|
log.Fatal(http.ListenAndServe(addr, nil))
|
|
}
|