feat(links): create basic link shortening algo
This commit is contained in:
parent
fc46164556
commit
81e72cedfa
9 changed files with 144 additions and 23 deletions
46
internal/handlers/log_middleware.go
Normal file
46
internal/handlers/log_middleware.go
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (sr *statusRecorder) WriteHeader(code int) {
|
||||
sr.statusCode = code
|
||||
sr.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (sr *statusRecorder) Write(b []byte) (int, error) {
|
||||
if sr.statusCode == 0 {
|
||||
sr.statusCode = http.StatusOK
|
||||
}
|
||||
|
||||
return sr.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
func LogMiddleware(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w}
|
||||
|
||||
h.ServeHTTP(rec, r)
|
||||
duration := time.Since(start)
|
||||
|
||||
statusCode := rec.statusCode
|
||||
|
||||
log.Printf("%s %s %s from %s - %d %s in %s\n",
|
||||
r.Method,
|
||||
r.URL.Path,
|
||||
r.Proto,
|
||||
r.RemoteAddr,
|
||||
statusCode,
|
||||
http.StatusText(statusCode),
|
||||
duration.String())
|
||||
})
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue