Skip to content

Commit

Permalink
log http requests
Browse files Browse the repository at this point in the history
  • Loading branch information
maddalax committed Nov 13, 2024
1 parent 423fd3f commit b06d1b1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
27 changes: 27 additions & 0 deletions htmgo-site/internal/urlhelper/ip.go
Original file line number Diff line number Diff line change
@@ -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
}
11 changes: 8 additions & 3 deletions htmgo-site/main.go
Original file line number Diff line number Diff line change
@@ -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"
)

Expand All @@ -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
})
Expand Down

0 comments on commit b06d1b1

Please sign in to comment.