github.com/sirkon/goproxy@v1.4.8/plugin/cascade/plugin.go (about)

     1  package cascade
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/sirkon/goproxy/internal/errors"
     7  
     8  	"github.com/sirkon/goproxy"
     9  	"github.com/sirkon/goproxy/internal/module"
    10  )
    11  
    12  // NewPlugin plugin returning source pointing to another proxy
    13  func NewPlugin(url string) goproxy.Plugin {
    14  	return &plugin{url: url, client: &http.Client{}, passCreds: nil}
    15  }
    16  
    17  // NewPluginPassCreds this gets a function deciding is it worth to pass BasicAuth further
    18  func NewPluginPassCreds(url string, passCreds func(r *http.Request) bool) goproxy.Plugin {
    19  	return &plugin{url: url, client: &http.Client{}, passCreds: passCreds}
    20  }
    21  
    22  // plugin of sources for another go proxy
    23  type plugin struct {
    24  	client    *http.Client
    25  	url       string
    26  	passCreds func(req *http.Request) bool
    27  }
    28  
    29  func (f *plugin) String() string {
    30  	return "cascade"
    31  }
    32  
    33  func (f *plugin) Module(req *http.Request, prefix string) (goproxy.Module, error) {
    34  	path, _, err := goproxy.GetModInfo(req, prefix)
    35  	if err != nil {
    36  		return nil, errors.Wrapf(err, "cascade getting module data from %s", req.URL.Path)
    37  	}
    38  	reqPath, err := module.EncodePath(path)
    39  	if err != nil {
    40  		return nil, errors.Wrapf(err, "cascade encoding input module path for %s", req.URL.Path)
    41  	}
    42  
    43  	res := &cascadeModule{
    44  		mod:    path,
    45  		reqMod: reqPath,
    46  		url:    f.url,
    47  		client: f.client,
    48  	}
    49  	if f.passCreds != nil {
    50  		if user, pass, ok := req.BasicAuth(); ok && f.passCreds(req) {
    51  			res.basicAuth.ok = true
    52  			res.basicAuth.user = user
    53  			res.basicAuth.password = pass
    54  		}
    55  	}
    56  
    57  	return res, nil
    58  }
    59  
    60  func (f *plugin) Leave(source goproxy.Module) error {
    61  	return nil
    62  }
    63  
    64  func (f *plugin) Close() error {
    65  	return nil
    66  }