Skip to content

Commit

Permalink
Create subpackage handlers, refactor getRootURL
Browse files Browse the repository at this point in the history
  • Loading branch information
fawick committed Oct 29, 2017
1 parent 26cbf59 commit d888e4b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 11 deletions.
44 changes: 44 additions & 0 deletions handlers/handlers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package handlers

import (
"fmt"
"net/http"
)

// RootURL returns the root URL of the HTTP request. Optionally, a domain and a
// base path may be provided which will be used to construct the root URL if
// they are not empty. Otherwise the hostname will be determined from the
// request and the path will be empty.
func RootURL(r *http.Request, domain, path string) string {
host := r.Host
if len(domain) > 0 {
host = domain
}

root := fmt.Sprintf("%s://%s", Scheme(r), host)
if len(path) > 0 {
root = fmt.Sprintf("%s/%s", root, path)
}

return root
}

// Scheme returns the underlying URL scheme of the original request.
func Scheme(r *http.Request) string {
if r.TLS != nil {
return "https"
}
if scheme := r.Header.Get("X-Forwarded-Proto"); scheme != "" {
return scheme
}
if scheme := r.Header.Get("X-Forwarded-Protocol"); scheme != "" {
return scheme
}
if ssl := r.Header.Get("X-Forwarded-Ssl"); ssl == "on" {
return "https"
}
if scheme := r.Header.Get("X-Url-Scheme"); scheme != "" {
return scheme
}
return "http"
}
16 changes: 5 additions & 11 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import (
_ "github.com/mattn/go-sqlite3"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"

"github.com/consbio/mbtileserver/handlers"
)

type ServiceInfo struct {
Expand Down Expand Up @@ -336,18 +338,10 @@ func getServiceOr404(c echo.Context) (string, error) {
return id, nil
}

// getRootURL is a convenience function to determine the root URL from the
// echo.Context.
func getRootURL(c echo.Context) string {
host := c.Request().Host
if len(domain) > 0 {
host = domain
}

root := fmt.Sprintf("%s://%s", c.Scheme(), host)
if len(path) > 0 {
root = fmt.Sprintf("%s/%s", root, path)
}

return root
return handlers.RootURL(c.Request(), domain, path)
}

func ListServices(c echo.Context) error {
Expand Down

0 comments on commit d888e4b

Please sign in to comment.