harness-drone/handler/api/template/create.go

73 lines
1.5 KiB
Go
Raw Normal View History

2021-05-19 13:18:24 +00:00
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package template
import (
"encoding/json"
2021-06-01 09:29:58 +00:00
"net/http"
"path/filepath"
2021-06-01 09:29:58 +00:00
2021-05-19 13:18:24 +00:00
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/errors"
2021-05-19 13:18:24 +00:00
"github.com/drone/drone/handler/api/render"
"github.com/go-chi/chi"
)
var (
errTemplateExtensionInvalid = errors.New("Template extension invalid. Must be yaml, starlark or jsonnet")
2021-05-19 13:18:24 +00:00
)
type templateInput struct {
Name string `json:"name"`
Data string `json:"data"`
2021-05-19 13:18:24 +00:00
}
// HandleCreate returns an http.HandlerFunc that processes http
// requests to create a new template.
func HandleCreate(templateStore core.TemplateStore) http.HandlerFunc {
2021-05-19 13:18:24 +00:00
return func(w http.ResponseWriter, r *http.Request) {
namespace := chi.URLParam(r, "namespace")
2021-05-19 13:18:24 +00:00
in := new(templateInput)
err := json.NewDecoder(r.Body).Decode(in)
if err != nil {
render.BadRequest(w, err)
return
}
// check valid template extension type
switch filepath.Ext(in.Name) {
case ".yml", ".yaml":
case ".star", ".starlark", ".script":
case ".jsonnet":
default:
render.BadRequest(w, errTemplateExtensionInvalid)
return
}
2021-05-19 13:18:24 +00:00
t := &core.Template{
Name: in.Name,
Data: in.Data,
Namespace: namespace,
2021-05-19 13:18:24 +00:00
}
err = t.Validate()
if err != nil {
render.BadRequest(w, err)
return
}
err = templateStore.Create(r.Context(), t)
2021-05-19 13:18:24 +00:00
if err != nil {
render.InternalError(w, err)
return
}
render.JSON(w, t, 200)
}
}