log http requests

This commit is contained in:
maddalax 2024-11-12 18:15:59 -06:00
parent 423fd3f429
commit b06d1b14bd
2 changed files with 35 additions and 3 deletions

View file

@ -0,0 +1,27 @@
package urlhelper
import (
"net/http"
"strings"
)
func GetClientIp(r *http.Request) string {
// Try to get the real client IP from the 'CF-Connecting-IP' header
if ip := r.Header.Get("CF-Connecting-IP"); ip != "" {
return ip
}
// If not available, fall back to 'X-Forwarded-For'
if ip := r.Header.Get("X-Forwarded-For"); ip != "" {
return ip
}
// Otherwise, use the default remote address (this will be Cloudflare's IP)
remote := r.RemoteAddr
if strings.HasPrefix(remote, "[::1]") {
return "localhost"
}
return remote
}

View file

@ -1,14 +1,15 @@
package main
import (
"fmt"
"github.com/maddalax/htmgo/framework/h"
"github.com/maddalax/htmgo/framework/service"
"htmgo-site/__htmgo"
"htmgo-site/internal/cache"
"htmgo-site/internal/markdown"
"htmgo-site/internal/sitemap"
"htmgo-site/internal/urlhelper"
"io/fs"
"log"
"net/http"
)
@ -20,13 +21,17 @@ func main() {
service.Set(locator, service.Singleton, markdown.NewRenderer)
service.Set(locator, service.Singleton, cache.NewSimpleCache)
fmt.Printf("starting up server2\n")
h.Start(h.AppOpts{
ServiceLocator: locator,
LiveReload: true,
Register: func(app *h.App) {
app.Use(func(ctx *h.RequestContext) {
r := ctx.Request
// Log the details of the incoming request
log.Printf("Method: %s, URL: %s, RemoteAddr: %s", r.Method, r.URL.String(), urlhelper.GetClientIp(r))
})
app.UseWithContext(func(w http.ResponseWriter, r *http.Request, context map[string]any) {
context["embeddedMarkdown"] = markdownAssets
})