traefik/pkg/provider/rest/rest.go

68 lines
2.1 KiB
Go
Raw Normal View History

2018-12-03 10:32:05 +00:00
package rest
import (
"encoding/json"
"fmt"
"net/http"
2019-08-03 01:58:23 +00:00
"github.com/containous/traefik/v2/pkg/config/dynamic"
"github.com/containous/traefik/v2/pkg/log"
"github.com/containous/traefik/v2/pkg/provider"
"github.com/containous/traefik/v2/pkg/safe"
"github.com/gorilla/mux"
2018-12-03 10:32:05 +00:00
"github.com/unrolled/render"
)
var _ provider.Provider = (*Provider)(nil)
// Provider is a provider.Provider implementation that provides a Rest API.
type Provider struct {
2019-09-06 13:08:04 +00:00
Insecure bool `description:"Activate REST Provider directly on the entryPoint named traefik." json:"insecure,omitempty" toml:"insecure,omitempty" yaml:"insecure,omitempty" export:"true"`
configurationChan chan<- dynamic.Message
}
// SetDefaults sets the default values.
func (p *Provider) SetDefaults() {}
2018-12-03 10:32:05 +00:00
var templatesRenderer = render.New(render.Options{Directory: "nowhere"})
// Init the provider.
func (p *Provider) Init() error {
return nil
}
2020-05-11 10:06:07 +00:00
// CreateRouter creates a router for the Rest API.
func (p *Provider) CreateRouter() *mux.Router {
2019-09-06 13:08:04 +00:00
router := mux.NewRouter()
router.Methods(http.MethodPut).Path("/api/providers/{provider}").Handler(p)
2019-09-06 13:08:04 +00:00
return router
}
func (p *Provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
if vars["provider"] != "rest" {
http.Error(rw, "Only 'rest' provider can be updated through the REST API", http.StatusBadRequest)
return
}
2018-12-03 10:32:05 +00:00
configuration := new(dynamic.Configuration)
2019-02-05 16:10:03 +00:00
if err := json.NewDecoder(req.Body).Decode(configuration); err != nil {
log.WithoutContext().Errorf("Error parsing configuration %+v", err)
http.Error(rw, fmt.Sprintf("%+v", err), http.StatusBadRequest)
return
}
2019-02-05 16:10:03 +00:00
p.configurationChan <- dynamic.Message{ProviderName: "rest", Configuration: configuration}
if err := templatesRenderer.JSON(rw, http.StatusOK, configuration); err != nil {
log.WithoutContext().Error(err)
}
2018-12-03 10:32:05 +00:00
}
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error {
2018-12-03 10:32:05 +00:00
p.configurationChan = configurationChan
return nil
}