traefik/pkg/provider/rest/rest.go

73 lines
2.1 KiB
Go
Raw Normal View History

2018-12-03 10:32:05 +00:00
package rest
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/containous/mux"
"github.com/containous/traefik/pkg/config/dynamic"
2019-03-15 08:42:03 +00:00
"github.com/containous/traefik/pkg/log"
"github.com/containous/traefik/pkg/provider"
"github.com/containous/traefik/pkg/safe"
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 {
configurationChan chan<- dynamic.Message
2019-07-01 09:30:05 +00:00
EntryPoint string `description:"EntryPoint." json:"entryPoint,omitempty" toml:"entryPoint,omitempty" yaml:"entryPoint,omitempty" export:"true"`
}
// SetDefaults sets the default values.
func (p *Provider) SetDefaults() {
p.EntryPoint = "traefik"
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
}
// Append add rest provider routes on a router.
func (p *Provider) Append(systemRouter *mux.Router) {
systemRouter.
Methods(http.MethodPut).
Path("/api/providers/{provider}").
HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
if vars["provider"] != "rest" {
response.WriteHeader(http.StatusBadRequest)
fmt.Fprint(response, "Only 'rest' provider can be updated through the REST API")
return
}
2019-07-12 23:24:03 +00:00
configuration := new(dynamic.Configuration)
2018-12-03 10:32:05 +00:00
body, _ := ioutil.ReadAll(request.Body)
2019-02-05 16:10:03 +00:00
if err := json.Unmarshal(body, configuration); err != nil {
2018-12-03 10:32:05 +00:00
log.WithoutContext().Errorf("Error parsing configuration %+v", err)
http.Error(response, fmt.Sprintf("%+v", err), http.StatusBadRequest)
2019-02-05 16:10:03 +00:00
return
}
2019-07-12 23:24:03 +00:00
p.configurationChan <- dynamic.Message{ProviderName: "rest", Configuration: configuration}
2019-02-05 16:10:03 +00:00
if err := templatesRenderer.JSON(response, 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
}