portainer/api/http/handler/templates.go

74 lines
2.0 KiB
Go
Raw Normal View History

package handler
2016-12-18 05:21:29 +00:00
import (
"io/ioutil"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
httperror "github.com/portainer/portainer/http/error"
"github.com/portainer/portainer/http/security"
2016-12-18 05:21:29 +00:00
)
// TemplatesHandler represents an HTTP API handler for managing templates.
type TemplatesHandler struct {
*mux.Router
Logger *log.Logger
containerTemplatesURL string
2016-12-18 05:21:29 +00:00
}
const (
containerTemplatesURLLinuxServerIo = "http://tools.linuxserver.io/portainer.json"
)
2016-12-18 05:21:29 +00:00
// NewTemplatesHandler returns a new instance of TemplatesHandler.
func NewTemplatesHandler(bouncer *security.RequestBouncer, containerTemplatesURL string) *TemplatesHandler {
2016-12-18 05:21:29 +00:00
h := &TemplatesHandler{
Router: mux.NewRouter(),
Logger: log.New(os.Stderr, "", log.LstdFlags),
containerTemplatesURL: containerTemplatesURL,
2016-12-18 05:21:29 +00:00
}
h.Handle("/templates",
bouncer.AuthenticatedAccess(http.HandlerFunc(h.handleGetTemplates)))
2016-12-18 05:21:29 +00:00
return h
}
// handleGetTemplates handles GET requests on /templates?key=<key>
2016-12-18 05:21:29 +00:00
func (handler *TemplatesHandler) handleGetTemplates(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
httperror.WriteMethodNotAllowedResponse(w, []string{http.MethodGet})
2016-12-18 05:21:29 +00:00
return
}
key := r.FormValue("key")
if key == "" {
httperror.WriteErrorResponse(w, ErrInvalidQueryFormat, http.StatusBadRequest, handler.Logger)
return
}
var templatesURL string
if key == "containers" {
templatesURL = handler.containerTemplatesURL
} else if key == "linuxserver.io" {
templatesURL = containerTemplatesURLLinuxServerIo
} else {
httperror.WriteErrorResponse(w, ErrInvalidQueryFormat, http.StatusBadRequest, handler.Logger)
return
}
resp, err := http.Get(templatesURL)
2016-12-18 05:21:29 +00:00
if err != nil {
httperror.WriteErrorResponse(w, err, http.StatusInternalServerError, handler.Logger)
2016-12-18 05:21:29 +00:00
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
httperror.WriteErrorResponse(w, err, http.StatusInternalServerError, handler.Logger)
2016-12-18 05:21:29 +00:00
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(body)
}