Skip to content

Instantly share code, notes, and snippets.

@erancihan
Created April 20, 2020 17:38
Show Gist options
  • Save erancihan/4a144f26d5c1be226a5bd8f96ef9d782 to your computer and use it in GitHub Desktop.
Save erancihan/4a144f26d5c1be226a5bd8f96ef9d782 to your computer and use it in GitHub Desktop.
simple subdomain based Proxy to a url
package main
import (
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"net/url"
"strings"
)
var ServerPort = ":8000"
type (
Balancer struct {
M map[string]*middleware.ProxyTarget
middleware.ProxyBalancer
}
)
func NewBalancer(targets []*middleware.ProxyTarget) middleware.ProxyBalancer {
b := Balancer{
M: make(map[string]*middleware.ProxyTarget),
}
for i := range targets {
key := strings.ToUpper(targets[i].Name)
b.M[key] = targets[i]
}
return b
}
func (balancer Balancer) AddTarget(target *middleware.ProxyTarget) bool {
return false
}
func (balancer Balancer) RemoveTarget(str string) bool { return false }
func (balancer Balancer) Next(ctx echo.Context) *middleware.ProxyTarget {
host := ctx.Request().Host
host = strings.ReplaceAll(host, ".localhost"+ServerPort, "")
hostInfo := strings.Split(host, ".")
if len(hostInfo) == 2 {
key := strings.Split(host, ".")[1]
key = strings.ToUpper(key)
if val, ok := balancer.M[key]; ok {
return val
}
}
return balancer.M["S1"]
}
func main() {
e := echo.New()
e.Use(middleware.Recover())
e.Use(middleware.Logger())
s1, err := url.Parse("http://localhost:5000")
if err != nil {
e.Logger.Fatal(err)
}
s2, err := url.Parse("http://localhost:5001")
if err != nil {
e.Logger.Fatal(err)
}
targets := []*middleware.ProxyTarget{
{
Name: "S1",
URL: s1,
},
{
Name: "S2",
URL: s2,
},
}
e.Use(middleware.Proxy(NewBalancer(targets)))
e.Logger.Fatal(e.Start(ServerPort))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment