add some request logging

This commit is contained in:
David 2021-10-24 16:52:13 -04:00
parent cbde81e759
commit cecb29f382
2 changed files with 16 additions and 4 deletions

View File

@ -35,13 +35,19 @@ var responseCodes = map[string]int{
"CERTIFICATENOTVALID": 62,
}
func NewResponse(conn net.Conn) *Response {
type log interface {
Info(...interface{})
}
func NewResponse(conn net.Conn, logger log) *Response {
return &Response{
conn: conn,
logger: logger,
conn: conn,
}
}
type Response struct {
logger log
statusSent bool
status int
meta string
@ -50,7 +56,7 @@ type Response struct {
func (w *Response) WriteStatus(code int, meta string) (int, error) {
if w.statusSent {
return 0, fmt.Errorf("Cannot set status after start of response")
return 0, fmt.Errorf("cannot set status after start of response")
}
w.status = code
w.meta = meta
@ -83,6 +89,7 @@ type StaticHandler struct {
}
func (h StaticHandler) Handle(w *Response, r *Request) {
w.logger.Info(fmt.Sprintf("static response: %v", r.url))
w.WriteStatus(responseCodes["SUCCESS"], "text/gemini")
w.Write([]byte(h.Response))
}
@ -133,9 +140,11 @@ func (h FileHandler) Handle(w *Response, r *Request) {
} else if h.DirectoryListing {
b, err := genIndex(req, filepath.Clean(r.GetURL().Path))
if err != nil {
w.logger.Info(fmt.Sprintf("request: %v; result: %d", r.url, responseCodes["NOTFOUND"]))
w.WriteStatus(responseCodes["NOTFOUND"], "File not found")
return
}
w.logger.Info(fmt.Sprintf("request: %v; result: %d", r.url, responseCodes["SUCCESS"]))
w.WriteStatus(responseCodes["SUCCESS"], "text/gemini")
w.Write(b)
return
@ -143,18 +152,21 @@ func (h FileHandler) Handle(w *Response, r *Request) {
}
if !sourceFileStat.Mode().IsRegular() {
w.logger.Info(fmt.Sprintf("request: %v; result: %d", r.url, responseCodes["NOTFOUND"]))
w.WriteStatus(responseCodes["NOTFOUND"], "File not found")
return
}
source, err := os.Open(req)
if err != nil {
w.logger.Info(fmt.Sprintf("request: %v; result: %d", r.url, responseCodes["TEMPORARYFAILURE"]))
w.WriteStatus(responseCodes["TEMPORARYFAILURE"], "Internal Error")
return
}
defer source.Close()
mime := mime.TypeByExtension(filepath.Ext(req))
w.logger.Info(fmt.Sprintf("request: %v; result: %d", r.url, responseCodes["SUCCESS"]))
w.WriteStatus(responseCodes["SUCCESS"], mime)
io.Copy(w, source)
}

View File

@ -23,7 +23,7 @@ func handleConnection(log logger.Logger, conn net.Conn, h handlers.Handler) {
if err != nil {
log.Debug(err)
}
w := handlers.NewResponse(conn)
w := handlers.NewResponse(conn, log)
r := handlers.NewRequest(u)
handlers.RecoveryHandler(log, h).Handle(w, r)
}