Search code examples
gogo-gin

How to get full server URL from any endpoint handler in Gin


I'm creating an endpoint using Go's Gin web framework. I need full server URL in my handler function. For example, if server is running on http://localhost:8080 and my endpoint is /foo then I need http://localhost:8080/foo when my handler is called.

If anyone is familiar with Python's fast API, the Request object has a method url_for(<endpoint_name>) which has the exact same functionality: https://stackoverflow.com/a/63682957/5353128

In Go, I've tried accessing context.FullPath() but that only returns my endpoint /foo and not the full URL. Other than this, I can't find appropriate method in docs: https://pkg.go.dev/github.com/gin-gonic/gin#Context

So is this possible via gin.Context object itself or are there other ways as well? I'm completely new to Go.


Solution

  • c.Request.Host+c.Request.URL.Path should work but the scheme has to be determined.

    package main
    
    import (
        "fmt"
    
        "github.com/gin-gonic/gin"
    )
    
    func main() {
        r := gin.Default()
    
        r.GET("/foo", func(c *gin.Context) {
            fmt.Println("The URL: ", c.Request.Host+c.Request.URL.Path)
        })
    
        r.Run(":8080")
    }
    

    You can determine scheme which also you may know already. But you can check as follows:

    scheme := "http"
    if c.Request.TLS != nil {
        scheme = "https"
    }
    

    If your server is behind the proxy, you can get the scheme by c.Request.Header.Get("X-Forwarded-Proto")