Skip to content

Commit

Permalink
deploy crufty tunnel
Browse files Browse the repository at this point in the history
  • Loading branch information
asim committed Mar 21, 2022
1 parent 143a999 commit cff9117
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 3 deletions.
35 changes: 35 additions & 0 deletions tunnel/function/tunnel.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package tunnel

import (
"os"

"net/http"
"net/http/httputil"
"net/url"
)

var (
token = os.Getenv("TOKEN")
)

func Send(w http.ResponseWriter, r *http.Request) {
// check the auth token
x := r.Header.Get("Micro-Token")
if x != token {
http.Error(w, "unauthorized", 401)
return
}

// don't forward the token
r.Header.Del("Micro-Token")

url, err := url.Parse(r.Host)
if err != nil {
http.Error(w, err.Error(), 500)
return
}

// reverse proxy the request
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ServeHTTP(w, r)
}
27 changes: 24 additions & 3 deletions tunnel/handler/tunnel.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import (
)

type Tunnel struct {
Proxy string
Token string
Blocklist map[string]bool
}

Expand All @@ -42,9 +44,13 @@ func loadFile(p string) (string, error) {
}

func New() *Tunnel {
v, err := config.Get("tunnel.proxy")
if err != nil {
logger.Fatalf("failed to get blocklist: %v", err)
}
proxy := v.String("")

// get the ip city database
v, err := config.Get("tunnel.blocklist")
v, err = config.Get("tunnel.blocklist")
if err != nil {
logger.Fatalf("failed to get blocklist: %v", err)
}
Expand Down Expand Up @@ -72,6 +78,7 @@ func New() *Tunnel {

return &Tunnel{
Blocklist: blocklist,
Proxy: proxy,
}
}

Expand Down Expand Up @@ -140,8 +147,22 @@ func (e *Tunnel) Send(ctx context.Context, req *pb.SendRequest, rsp *pb.SendResp

logger.Infof("Making request %s %s", req.Method, uri.String())

// set client as default http client
client := http.DefaultClient

// use a proxy if specified
if len(e.Proxy) > 0 {
proxyUrl, _ := url.Parse(e.Proxy)
client = &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}}
}

// set the authorization token
if len(e.Token) > 0 {
hreq.Header.Set("Micro-Token", e.Token)
}

// make the request
hrsp, err := http.DefaultClient.Do(hreq)
hrsp, err := client.Do(hreq)
if err != nil {
return errors.InternalServerError("tunnel.send", err.Error())
}
Expand Down

0 comments on commit cff9117

Please sign in to comment.