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

     1  package choice
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"strings"
     7  
     8  	"github.com/sirkon/goproxy/internal/errors"
     9  
    10  	"github.com/sirkon/goproxy"
    11  )
    12  
    13  // New plugin which tries to return a source with each plugin consequently until success. Made specially for
    14  // apriori plugin
    15  func New(plugins ...goproxy.Plugin) goproxy.Plugin {
    16  	return &choice{
    17  		plugs: plugins,
    18  	}
    19  }
    20  
    21  type choice struct {
    22  	plugs []goproxy.Plugin
    23  }
    24  
    25  func (c *choice) String() string {
    26  	plugs := make([]string, len(c.plugs))
    27  	for i, plug := range c.plugs {
    28  		plugs[i] = plug.String()
    29  	}
    30  	return fmt.Sprintf("choice(%s)", strings.Join(plugs, ", "))
    31  }
    32  
    33  func (c *choice) Module(req *http.Request, prefix string) (goproxy.Module, error) {
    34  	for _, plug := range c.plugs {
    35  		src, err := plug.Module(req, prefix)
    36  		if err != nil {
    37  			continue
    38  		}
    39  		return src, nil
    40  	}
    41  	return nil, errors.Newf("no suitable plugin found for request to %s", req.URL.Path)
    42  }
    43  
    44  func (c *choice) Leave(source goproxy.Module) error {
    45  	return nil
    46  }
    47  
    48  func (c *choice) Close() error {
    49  	return nil
    50  }