Created
June 29, 2015 18:10
-
-
Save axdg/19aa50c6d66050d1b1f0 to your computer and use it in GitHub Desktop.
Example subdomain routing in github.com/labstack/echo v1.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"github.com/labstack/echo" | |
) | |
type Hosts map[string]http.Handler | |
// Implement a ServeHTTP method for Hosts type. | |
func (h Hosts) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
// Check for host x in the Hosts map. | |
if handler := h[r.Host]; handler != nil { | |
handler.ServeHTTP(w, r) | |
} else { | |
// No handler is registered so redirect. | |
// Not sure redirect is appropriate here? | |
// This is just for illustration, else branch could just as easily return | |
// an error for bad port, notFound for bad subdomain etc. | |
http.Redirect(w, r, "http://a.localhost:8080", http.StatusTemporaryRedirect) | |
} | |
} | |
func main() { | |
// Some subdomains | |
a := echo.New() | |
b := echo.New() | |
// Host maps. | |
hosts := make(Hosts) | |
hosts["a.localhost:8080"] = a | |
hosts["b.localhost:8080"] = b | |
// Handler for subdomain a. | |
a.Get("/", func(c *echo.Context) error { | |
c.String(http.StatusOK, "Welcome to host a...") | |
return nil | |
}) | |
// Handler for subdomain b. | |
b.Get("/", func(c *echo.Context) error { | |
c.String(http.StatusOK, "Welcome to host b...") | |
return nil | |
}) | |
http.ListenAndServe(":8080", hosts) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment