I'm trying to run any number of http reverse proxy servers listening on 
different ports based on environment variables.  The idea is to use the 
ADDR environment variables that K8 sets to redirect to various backends.

For example, the following environment variables would result in redirects 
as such:
SECOND_DEPLOYMENT_PORT_6061_TCP_ADDR=10.100.2.5   => :6061 -> 
10.100.2.5:6061
OUTSCORE_DEPLOYMENT_PORT_8080_TCP_ADDR=10.100.4.6 => :8080 -> 
10.100.4.6:8080

Here is the code that I have: https://play.golang.org/p/ZDDOoQx2jp

And for reference:

package main

import (
    "net/http"
    "net/url"
    "fmt"
    "os/exec"
    "bufio"
    "strings"
    "bytes"
    "regexp"
    "sync"
    "github.com/vulcand/oxy/forward"
)


func getAddrs() (map[string]string) {
    services := ParseRawServices(GetRawEnv())
    return services
}

func GetRawEnv() []byte {
    output, _ := exec.Command("env").Output()
    return output
}

func ParseRawServices(raw []byte) map[string]string {
    serviceMap := map[string]string{}
    scanner := bufio.NewScanner(bytes.NewReader(raw))

    scanner.Split(bufio.ScanLines)

    for scanner.Scan() {
        svc := scanner.Text()
        if !strings.Contains(svc, "ADDR") {
            continue
        }
        portre := regexp.MustCompile("_(\\d*)_")
        port := strings.Replace(portre.FindString(svc), "_", "", 2)
        ipre := regexp.MustCompile("(?:[0-9]{1,3}\\.){3}[0-9]{1,3}")
        serviceMap[port] = ipre.FindString(svc)
    }
    return serviceMap
}

func PortParse(url string) string {
     return strings.Split(url, ":")[1]
}

func main() {

    targets := getAddrs()
    fmt.Printf("Targets found: %q\n", targets)

    wg := &sync.WaitGroup{}

    for port, host := range targets {
        fmt.Printf("Serving: %q:%q\n", host,port)

        fwd, _ := forward.New()
        redirect := http.HandlerFunc(func(w http.ResponseWriter, req 
*http.Request) {
                target := fmt.Sprintf("%s:%s", host, port)
                fmt.Printf("Target: %q", target)
                req.URL = &url.URL{
                    Scheme: "http",
                    Host: target,
                }
                fwd.ServeHTTP(w, req)
        })
        
        wg.Add(1)
        go func() {
          http.ListenAndServe(fmt.Sprintf(":%s", port), &redirect)
               wg.Done()
        }()
}
    wg.Wait()
}

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to