1
0
mirror of https://github.com/bingohuang/docker-labs.git synced 2025-07-15 02:37:27 +08:00

Merge pull request #43 from franela/reverse_proxy

Add reverse proxy endpoint.
This commit is contained in:
Marcos Nils 2016-11-23 19:09:00 +02:00 committed by GitHub
commit 0f4aea4de3
4 changed files with 64 additions and 0 deletions

6
api.go
View File

@ -36,6 +36,12 @@ func main() {
}
r := mux.NewRouter()
// Reverse proxy (needs to be the first route, to make sure it is the first thing we check)
proxyHandler := handlers.NewMultipleHostReverseProxy()
r.Host(`{node:ip[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}}-{port:[0-9]*}.{tld:.*}`).Handler(proxyHandler)
r.Host(`{node:ip[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}}.{tld:.*}`).Handler(proxyHandler)
r.StrictSlash(false)
r.HandleFunc("/ping", http.HandlerFunc(handlers.Ping)).Methods("GET")

39
handlers/reverseproxy.go Normal file
View File

@ -0,0 +1,39 @@
package handlers
import (
"fmt"
"net"
"net/http"
"net/http/httputil"
"strings"
"github.com/gorilla/mux"
)
func NewMultipleHostReverseProxy() *httputil.ReverseProxy {
director := func(req *http.Request) {
v := mux.Vars(req)
node := v["node"]
port := v["port"]
if port == "" {
port = "80"
}
if strings.HasPrefix(node, "ip") {
// Node is actually an ip, need to convert underscores by dots.
ip := strings.Replace(strings.TrimPrefix(node, "ip"), "_", ".", -1)
if net.ParseIP(ip) == nil {
// Not a valid IP, so treat this is a hostname.
} else {
node = ip
}
}
// Only proxy http for now
req.URL.Scheme = "http"
req.URL.Host = fmt.Sprintf("%s:%s", node, port)
}
return &httputil.ReverseProxy{Director: director}
}

View File

@ -52,6 +52,17 @@ func CreateNetwork(name string) error {
return nil
}
func ConnectNetwork(containerId, networkId string) error {
err := c.NetworkConnect(context.Background(), networkId, containerId, &network.EndpointSettings{})
if err != nil {
log.Printf("Connection container to network err [%s]\n", err)
return err
}
return nil
}
func DeleteNetwork(id string) error {
err := c.NetworkRemove(context.Background(), id)

View File

@ -108,6 +108,14 @@ func NewSession() (*Session, error) {
log.Println("ERROR NETWORKING")
return nil, err
}
log.Printf("Network [%s] created for session [%s]\n", s.Id, s.Id)
// Connect PWD daemon to the new network
if err := ConnectNetwork("pwd", s.Id); err != nil {
log.Println("ERROR NETWORKING")
return nil, err
}
log.Printf("Connected pwd to network [%s]\n", s.Id)
// We store sessions as soon as we create one so we don't delete new sessions on an api restart
if err := saveSessionsToDisk(); err != nil {