Browse Source

add some request logging

master
David Ashby 8 months ago
parent
commit
cecb29f382
  1. 18
      handlers/response.go
  2. 2
      main.go

18
handlers/response.go

@ -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)
}

2
main.go

@ -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)
}

Loading…
Cancel
Save