functionbuilder

This commit is contained in:
Nathan Coad
2023-02-10 15:15:53 +11:00
parent 7504ea61e8
commit 329f1e518c
27 changed files with 3343 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
)
// DeleteHandlerFunc turns a function with the right signature into a delete handler
type DeleteHandlerFunc func(DeleteParams) middleware.Responder
// Handle executing the request and returning a response
func (fn DeleteHandlerFunc) Handle(params DeleteParams) middleware.Responder {
return fn(params)
}
// DeleteHandler interface for that can handle valid delete params
type DeleteHandler interface {
Handle(DeleteParams) middleware.Responder
}
// NewDelete creates a new http.Handler for the delete operation
func NewDelete(ctx *middleware.Context, handler DeleteHandler) *Delete {
return &Delete{Context: ctx, Handler: handler}
}
/* Delete swagger:route DELETE / delete
Delete delete API
*/
type Delete struct {
Context *middleware.Context
Handler DeleteHandler
}
func (o *Delete) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewDeleteParams()
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -0,0 +1,74 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
)
// NewDeleteParams creates a new DeleteParams object
//
// There are no default values defined in the spec.
func NewDeleteParams() DeleteParams {
return DeleteParams{}
}
// DeleteParams contains all the bound params for the delete operation
// typically these are obtained from a http.Request
//
// swagger:parameters Delete
type DeleteParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*On cancel Direktiv sends a DELETE request to
the action with id in the header
In: header
*/
DirektivActionID *string
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewDeleteParams() beforehand.
func (o *DeleteParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if err := o.bindDirektivActionID(r.Header[http.CanonicalHeaderKey("Direktiv-ActionID")], true, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindDirektivActionID binds and validates parameter DirektivActionID from header.
func (o *DeleteParams) bindDirektivActionID(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: false
if raw == "" { // empty values pass all other validations
return nil
}
o.DirektivActionID = &raw
return nil
}

View File

@@ -0,0 +1,36 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
)
// DeleteOKCode is the HTTP code returned for type DeleteOK
const DeleteOKCode int = 200
/*DeleteOK delete o k
swagger:response deleteOK
*/
type DeleteOK struct {
}
// NewDeleteOK creates DeleteOK with default headers values
func NewDeleteOK() *DeleteOK {
return &DeleteOK{}
}
// WriteResponse to the client
func (o *DeleteOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(200)
}

View File

@@ -0,0 +1,58 @@
package operations
import (
"context"
"fmt"
"github.com/direktiv/apps/go/pkg/apps"
"github.com/go-openapi/runtime/middleware"
)
func DeleteDirektivHandle(params DeleteParams) middleware.Responder {
actionId := *params.DirektivActionID
// defer sm.Delete(actionId)
if actionId == "" {
return NewDeleteOK()
}
ri, err := apps.RequestinfoFromRequest(params.HTTPRequest)
if err != nil {
fmt.Println("can not create ri from request")
return NewDeleteOK()
}
// cancel, ok := sm.Load(actionId)
ci, ok := sm.Load(actionId)
if !ok {
ri.Logger().Infof("can not load context for action id1", err)
return NewDeleteOK()
}
cinfo, ok := ci.(*ctxInfo)
if !ok {
ri.Logger().Infof("can not load context for action id2")
return NewDeleteOK()
}
// set to cancelled
cinfo.cancelled = true
ri.Logger().Infof("cancelling action id %v", actionId)
cinfo.cf()
cmd, err := templateString("echo 'cancel {{ .DirektivActionID }}'", params)
if err != nil {
ri.Logger().Infof("can not template cancel command: %v", err)
return NewDeleteOK()
}
_, err = runCmd(context.Background(), cmd, []string{}, "", false, true, ri)
if err != nil {
ri.Logger().Infof("error running cancel function: %v", err)
}
return NewDeleteOK()
}

View File

@@ -0,0 +1,279 @@
package operations
import (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"html"
"html/template"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"github.com/Masterminds/sprig"
"github.com/direktiv/apps/go/pkg/apps"
"github.com/mattn/go-shellwords"
"golang.org/x/net/publicsuffix"
)
func fileExists(file string) bool {
_, err := os.Open(file)
if err != nil {
return false
}
return true
}
func file64(path string) string {
b, err := os.ReadFile(path)
if err != nil {
return err.Error()
}
return base64.StdEncoding.EncodeToString(b)
}
func deref(dd interface{}) interface{} {
switch p := dd.(type) {
case *string:
return *p
case *int:
return *p
default:
return p
}
}
func templateString(tmplIn string, data interface{}) (string, error) {
tmpl, err := template.New("base").Funcs(sprig.FuncMap()).Funcs(template.FuncMap{
"fileExists": fileExists,
"deref": deref,
"file64": file64,
}).Parse(tmplIn)
if err != nil {
return "", err
}
var b bytes.Buffer
err = tmpl.Execute(&b, data)
if err != nil {
return "", err
}
v := b.String()
if v == "<no value>" {
v = ""
}
return html.UnescapeString(v), nil
}
func convertTemplateToBool(template string, data interface{}, defaultValue bool) bool {
out, err := templateString(template, data)
if err != nil {
return defaultValue
}
ins, err := strconv.ParseBool(out)
if err != nil {
return defaultValue
}
return ins
}
func runCmd(ctx context.Context, cmdString string, envs []string,
output string, silent, print bool, ri *apps.RequestInfo) (map[string]interface{}, error) {
ir := make(map[string]interface{})
ir[successKey] = false
a, err := shellwords.Parse(cmdString)
if err != nil {
ir[resultKey] = err.Error()
return ir, err
}
if len(a) == 0 {
return ir, fmt.Errorf("command '%v' parsed to empty array", cmdString)
}
// get the binary and args
bin := a[0]
argsIn := []string{}
if len(a) > 1 {
argsIn = a[1:]
}
logger := io.Discard
stdo := io.Discard
if !silent {
logger = ri.LogWriter()
stdo = os.Stdout
}
var o bytes.Buffer
var oerr bytes.Buffer
mwStdout := io.MultiWriter(stdo, &o, logger)
mwStdErr := io.MultiWriter(os.Stdout, &oerr, logger)
cmd := exec.CommandContext(ctx, bin, argsIn...)
cmd.Stdout = mwStdout
cmd.Stderr = mwStdErr
cmd.Dir = ri.Dir()
// change HOME
curEnvs := append(os.Environ(), fmt.Sprintf("HOME=%s", ri.Dir()))
cmd.Env = append(curEnvs, envs...)
if print {
ri.Logger().Infof("running command %v", cmd)
}
err = cmd.Run()
if err != nil {
ir[resultKey] = string(oerr.String())
if oerr.String() == "" {
ir[resultKey] = err.Error()
} else {
ri.Logger().Errorf(oerr.String())
err = fmt.Errorf(oerr.String())
}
return ir, err
}
// successful here
ir[successKey] = true
// output check
b := o.Bytes()
if output != "" {
b, err = os.ReadFile(output)
if err != nil {
ir[resultKey] = err.Error()
return ir, err
}
}
var rj interface{}
err = json.Unmarshal(b, &rj)
if err != nil {
rj = apps.ToJSON(string(b))
}
ir[resultKey] = rj
return ir, nil
}
func doHttpRequest(debug bool, method, u, user, pwd string,
headers map[string]string, insecure, errNo200 bool,
data []byte) (map[string]interface{}, error) {
ir := make(map[string]interface{})
ir[successKey] = false
urlParsed, err := url.Parse(u)
if err != nil {
ir[resultKey] = err.Error()
return ir, err
}
v, err := url.ParseQuery(urlParsed.RawQuery)
if err != nil {
ir[resultKey] = err.Error()
return ir, err
}
urlParsed.RawQuery = v.Encode()
req, err := http.NewRequest(strings.ToUpper(method), urlParsed.String(), bytes.NewReader(data))
if err != nil {
ir[resultKey] = err.Error()
return ir, err
}
req.Close = true
for k, v := range headers {
req.Header.Add(k, v)
}
if user != "" {
req.SetBasicAuth(user, pwd)
}
jar, err := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
cr := http.DefaultTransport.(*http.Transport).Clone()
cr.TLSClientConfig = &tls.Config{
InsecureSkipVerify: insecure,
}
client := &http.Client{
Jar: jar,
Transport: cr,
}
if debug {
fmt.Printf("method: %s, insecure: %v\n", method, insecure)
fmt.Printf("url: %s\n", req.URL.String())
fmt.Println("Headers:")
for k, v := range headers {
fmt.Printf("%v = %v\n", k, v)
}
}
resp, err := client.Do(req)
if err != nil {
ir[resultKey] = err.Error()
return ir, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
ir[resultKey] = err.Error()
return ir, err
}
if errNo200 && (resp.StatusCode < 200 || resp.StatusCode > 299) {
err = fmt.Errorf("response status is not between 200-299: %v (%v)", resp.StatusCode, resp.Status)
ir[resultKey] = err.Error()
return ir, err
}
// from here on it is successful
ir[successKey] = true
ir[statusKey] = resp.Status
ir[codeKey] = resp.StatusCode
ir[headersKey] = resp.Header
var rj interface{}
err = json.Unmarshal(b, &rj)
ir[resultKey] = rj
// if the response is not json, base64 the result
if err != nil {
ir[resultKey] = base64.StdEncoding.EncodeToString(b)
}
return ir, nil
}

View File

@@ -0,0 +1,251 @@
package operations
import (
"context"
"fmt"
"strings"
"sync"
"github.com/direktiv/apps/go/pkg/apps"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
"app/models"
)
const (
successKey = "success"
resultKey = "result"
// http related
statusKey = "status"
codeKey = "code"
headersKey = "headers"
)
var sm sync.Map
const (
cmdErr = "io.direktiv.command.error"
outErr = "io.direktiv.output.error"
riErr = "io.direktiv.ri.error"
)
type accParams struct {
PostParams
Commands []interface{}
DirektivDir string
}
type accParamsTemplate struct {
models.PostParamsBody
Commands []interface{}
DirektivDir string
}
type ctxInfo struct {
cf context.CancelFunc
cancelled bool
}
func PostDirektivHandle(params PostParams) middleware.Responder {
resp := &models.PostOKBody{}
var (
err error
ret interface{}
cont bool
)
ri, err := apps.RequestinfoFromRequest(params.HTTPRequest)
if err != nil {
return generateError(riErr, err)
}
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
sm.Store(*params.DirektivActionID, &ctxInfo{
cancel,
false,
})
defer sm.Delete(*params.DirektivActionID)
var responses []interface{}
var paramsCollector []interface{}
accParams := accParams{
params,
nil,
ri.Dir(),
}
ret, err = runCommand0(ctx, accParams, ri)
responses = append(responses, ret)
// if foreach returns an error there is no continue
//
// default we do not continue
cont = convertTemplateToBool("<no value>", accParams, false)
// cont = convertTemplateToBool("<no value>", accParams, true)
//
if err != nil && !cont {
errName := cmdErr
// if the delete function added the cancel tag
ci, ok := sm.Load(*params.DirektivActionID)
if ok {
cinfo, ok := ci.(*ctxInfo)
if ok && cinfo.cancelled {
errName = "direktiv.actionCancelled"
err = fmt.Errorf("action got cancel request")
}
}
return generateError(errName, err)
}
paramsCollector = append(paramsCollector, ret)
accParams.Commands = paramsCollector
ret, err = runCommand1(ctx, accParams, ri)
responses = append(responses, ret)
// if foreach returns an error there is no continue
//
// default we do not continue
cont = convertTemplateToBool("<no value>", accParams, false)
// cont = convertTemplateToBool("<no value>", accParams, true)
//
if err != nil && !cont {
errName := cmdErr
// if the delete function added the cancel tag
ci, ok := sm.Load(*params.DirektivActionID)
if ok {
cinfo, ok := ci.(*ctxInfo)
if ok && cinfo.cancelled {
errName = "direktiv.actionCancelled"
err = fmt.Errorf("action got cancel request")
}
}
return generateError(errName, err)
}
paramsCollector = append(paramsCollector, ret)
accParams.Commands = paramsCollector
s, err := templateString(`{
"export-excel": {{ (index . 1).result | toJson }}
}
`, responses)
if err != nil {
return generateError(outErr, err)
}
responseBytes := []byte(s)
// validate
resp.UnmarshalBinary(responseBytes)
err = resp.Validate(strfmt.Default)
if err != nil {
return generateError(outErr, err)
}
return NewPostOK().WithPayload(resp)
}
// exec
func runCommand0(ctx context.Context,
params accParams, ri *apps.RequestInfo) (map[string]interface{}, error) {
ir := make(map[string]interface{})
ir[successKey] = false
at := accParamsTemplate{
*params.Body,
params.Commands,
params.DirektivDir,
}
cmd, err := templateString(`/bin/json2excel -inFile input.json -worksheetName "{{ .WorksheetName }}" -outputFilename '{{ .OutFilename }}'`, at)
if err != nil {
ri.Logger().Infof("error executing command: %v", err)
ir[resultKey] = err.Error()
return ir, err
}
cmd = strings.Replace(cmd, "\n", "", -1)
silent := convertTemplateToBool("false", at, false)
print := convertTemplateToBool("true", at, true)
output := ""
envs := []string{}
return runCmd(ctx, cmd, envs, output, silent, print, ri)
}
// end commands
// exec
func runCommand1(ctx context.Context,
params accParams, ri *apps.RequestInfo) (map[string]interface{}, error) {
ir := make(map[string]interface{})
ir[successKey] = false
at := accParamsTemplate{
*params.Body,
params.Commands,
params.DirektivDir,
}
cmd, err := templateString(`base64 -w 0 /tmp/{{ .OutFilename }}`, at)
if err != nil {
ri.Logger().Infof("error executing command: %v", err)
ir[resultKey] = err.Error()
return ir, err
}
cmd = strings.Replace(cmd, "\n", "", -1)
silent := convertTemplateToBool("<no value>", at, false)
print := convertTemplateToBool("<no value>", at, true)
output := ""
envs := []string{}
return runCmd(ctx, cmd, envs, output, silent, print, ri)
}
// end commands
func generateError(code string, err error) *PostDefault {
d := NewPostDefault(0).WithDirektivErrorCode(code).
WithDirektivErrorMessage(err.Error())
errString := err.Error()
errResp := models.Error{
ErrorCode: &code,
ErrorMessage: &errString,
}
d.SetPayload(&errResp)
return d
}
func HandleShutdown() {
// nothing for generated functions
}

View File

@@ -0,0 +1,313 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"net/http"
"strings"
"github.com/go-openapi/errors"
"github.com/go-openapi/loads"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/runtime/security"
"github.com/go-openapi/spec"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// NewExportXlsxAPI creates a new ExportXlsx instance
func NewExportXlsxAPI(spec *loads.Document) *ExportXlsxAPI {
return &ExportXlsxAPI{
handlers: make(map[string]map[string]http.Handler),
formats: strfmt.Default,
defaultConsumes: "application/json",
defaultProduces: "application/json",
customConsumers: make(map[string]runtime.Consumer),
customProducers: make(map[string]runtime.Producer),
PreServerShutdown: func() {},
ServerShutdown: func() {},
spec: spec,
useSwaggerUI: false,
ServeError: errors.ServeError,
BasicAuthenticator: security.BasicAuth,
APIKeyAuthenticator: security.APIKeyAuth,
BearerAuthenticator: security.BearerAuth,
JSONConsumer: runtime.JSONConsumer(),
JSONProducer: runtime.JSONProducer(),
DeleteHandler: DeleteHandlerFunc(func(params DeleteParams) middleware.Responder {
return middleware.NotImplemented("operation Delete has not yet been implemented")
}),
PostHandler: PostHandlerFunc(func(params PostParams) middleware.Responder {
return middleware.NotImplemented("operation Post has not yet been implemented")
}),
}
}
/*ExportXlsxAPI Transform json input to xlsx spreadsheet */
type ExportXlsxAPI struct {
spec *loads.Document
context *middleware.Context
handlers map[string]map[string]http.Handler
formats strfmt.Registry
customConsumers map[string]runtime.Consumer
customProducers map[string]runtime.Producer
defaultConsumes string
defaultProduces string
Middleware func(middleware.Builder) http.Handler
useSwaggerUI bool
// BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function.
// It has a default implementation in the security package, however you can replace it for your particular usage.
BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator
// APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function.
// It has a default implementation in the security package, however you can replace it for your particular usage.
APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator
// BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function.
// It has a default implementation in the security package, however you can replace it for your particular usage.
BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator
// JSONConsumer registers a consumer for the following mime types:
// - application/json
JSONConsumer runtime.Consumer
// JSONProducer registers a producer for the following mime types:
// - application/json
JSONProducer runtime.Producer
// DeleteHandler sets the operation handler for the delete operation
DeleteHandler DeleteHandler
// PostHandler sets the operation handler for the post operation
PostHandler PostHandler
// ServeError is called when an error is received, there is a default handler
// but you can set your own with this
ServeError func(http.ResponseWriter, *http.Request, error)
// PreServerShutdown is called before the HTTP(S) server is shutdown
// This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic
PreServerShutdown func()
// ServerShutdown is called when the HTTP(S) server is shut down and done
// handling all active connections and does not accept connections any more
ServerShutdown func()
// Custom command line argument groups with their descriptions
CommandLineOptionsGroups []swag.CommandLineOptionsGroup
// User defined logger function.
Logger func(string, ...interface{})
}
// UseRedoc for documentation at /docs
func (o *ExportXlsxAPI) UseRedoc() {
o.useSwaggerUI = false
}
// UseSwaggerUI for documentation at /docs
func (o *ExportXlsxAPI) UseSwaggerUI() {
o.useSwaggerUI = true
}
// SetDefaultProduces sets the default produces media type
func (o *ExportXlsxAPI) SetDefaultProduces(mediaType string) {
o.defaultProduces = mediaType
}
// SetDefaultConsumes returns the default consumes media type
func (o *ExportXlsxAPI) SetDefaultConsumes(mediaType string) {
o.defaultConsumes = mediaType
}
// SetSpec sets a spec that will be served for the clients.
func (o *ExportXlsxAPI) SetSpec(spec *loads.Document) {
o.spec = spec
}
// DefaultProduces returns the default produces media type
func (o *ExportXlsxAPI) DefaultProduces() string {
return o.defaultProduces
}
// DefaultConsumes returns the default consumes media type
func (o *ExportXlsxAPI) DefaultConsumes() string {
return o.defaultConsumes
}
// Formats returns the registered string formats
func (o *ExportXlsxAPI) Formats() strfmt.Registry {
return o.formats
}
// RegisterFormat registers a custom format validator
func (o *ExportXlsxAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) {
o.formats.Add(name, format, validator)
}
// Validate validates the registrations in the ExportXlsxAPI
func (o *ExportXlsxAPI) Validate() error {
var unregistered []string
if o.JSONConsumer == nil {
unregistered = append(unregistered, "JSONConsumer")
}
if o.JSONProducer == nil {
unregistered = append(unregistered, "JSONProducer")
}
if o.DeleteHandler == nil {
unregistered = append(unregistered, "DeleteHandler")
}
if o.PostHandler == nil {
unregistered = append(unregistered, "PostHandler")
}
if len(unregistered) > 0 {
return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", "))
}
return nil
}
// ServeErrorFor gets a error handler for a given operation id
func (o *ExportXlsxAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) {
return o.ServeError
}
// AuthenticatorsFor gets the authenticators for the specified security schemes
func (o *ExportXlsxAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator {
return nil
}
// Authorizer returns the registered authorizer
func (o *ExportXlsxAPI) Authorizer() runtime.Authorizer {
return nil
}
// ConsumersFor gets the consumers for the specified media types.
// MIME type parameters are ignored here.
func (o *ExportXlsxAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer {
result := make(map[string]runtime.Consumer, len(mediaTypes))
for _, mt := range mediaTypes {
switch mt {
case "application/json":
result["application/json"] = o.JSONConsumer
}
if c, ok := o.customConsumers[mt]; ok {
result[mt] = c
}
}
return result
}
// ProducersFor gets the producers for the specified media types.
// MIME type parameters are ignored here.
func (o *ExportXlsxAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer {
result := make(map[string]runtime.Producer, len(mediaTypes))
for _, mt := range mediaTypes {
switch mt {
case "application/json":
result["application/json"] = o.JSONProducer
}
if p, ok := o.customProducers[mt]; ok {
result[mt] = p
}
}
return result
}
// HandlerFor gets a http.Handler for the provided operation method and path
func (o *ExportXlsxAPI) HandlerFor(method, path string) (http.Handler, bool) {
if o.handlers == nil {
return nil, false
}
um := strings.ToUpper(method)
if _, ok := o.handlers[um]; !ok {
return nil, false
}
if path == "/" {
path = ""
}
h, ok := o.handlers[um][path]
return h, ok
}
// Context returns the middleware context for the export xlsx API
func (o *ExportXlsxAPI) Context() *middleware.Context {
if o.context == nil {
o.context = middleware.NewRoutableContext(o.spec, o, nil)
}
return o.context
}
func (o *ExportXlsxAPI) initHandlerCache() {
o.Context() // don't care about the result, just that the initialization happened
if o.handlers == nil {
o.handlers = make(map[string]map[string]http.Handler)
}
if o.handlers["DELETE"] == nil {
o.handlers["DELETE"] = make(map[string]http.Handler)
}
o.handlers["DELETE"][""] = NewDelete(o.context, o.DeleteHandler)
if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler)
}
o.handlers["POST"][""] = NewPost(o.context, o.PostHandler)
}
// Serve creates a http handler to serve the API over HTTP
// can be used directly in http.ListenAndServe(":8000", api.Serve(nil))
func (o *ExportXlsxAPI) Serve(builder middleware.Builder) http.Handler {
o.Init()
if o.Middleware != nil {
return o.Middleware(builder)
}
if o.useSwaggerUI {
return o.context.APIHandlerSwaggerUI(builder)
}
return o.context.APIHandler(builder)
}
// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit
func (o *ExportXlsxAPI) Init() {
if len(o.handlers) == 0 {
o.initHandlerCache()
}
}
// RegisterConsumer allows you to add (or override) a consumer for a media type.
func (o *ExportXlsxAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) {
o.customConsumers[mediaType] = consumer
}
// RegisterProducer allows you to add (or override) a producer for a media type.
func (o *ExportXlsxAPI) RegisterProducer(mediaType string, producer runtime.Producer) {
o.customProducers[mediaType] = producer
}
// AddMiddlewareFor adds a http middleware to existing handler
func (o *ExportXlsxAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) {
um := strings.ToUpper(method)
if path == "/" {
path = ""
}
o.Init()
if h, ok := o.handlers[um][path]; ok {
o.handlers[method][path] = builder(h)
}
}

View File

@@ -0,0 +1,56 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
)
// PostHandlerFunc turns a function with the right signature into a post handler
type PostHandlerFunc func(PostParams) middleware.Responder
// Handle executing the request and returning a response
func (fn PostHandlerFunc) Handle(params PostParams) middleware.Responder {
return fn(params)
}
// PostHandler interface for that can handle valid post params
type PostHandler interface {
Handle(PostParams) middleware.Responder
}
// NewPost creates a new http.Handler for the post operation
func NewPost(ctx *middleware.Context, handler PostHandler) *Post {
return &Post{Context: ctx, Handler: handler}
}
/* Post swagger:route POST / post
Post post API
*/
type Post struct {
Context *middleware.Context
Handler PostHandler
}
func (o *Post) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewPostParams()
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -0,0 +1,149 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/validate"
"app/models"
)
// NewPostParams creates a new PostParams object
// with the default values initialized.
func NewPostParams() PostParams {
var (
// initialize parameters with default values
direktivActionIDDefault = string("development")
direktivTempDirDefault = string("/tmp")
)
return PostParams{
DirektivActionID: &direktivActionIDDefault,
DirektivTempDir: &direktivTempDirDefault,
}
}
// PostParams contains all the bound params for the post operation
// typically these are obtained from a http.Request
//
// swagger:parameters Post
type PostParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*direktiv action id is an UUID.
For development it can be set to 'development'
In: header
Default: "development"
*/
DirektivActionID *string
/*direktiv temp dir is the working directory for that request
For development it can be set to e.g. '/tmp'
In: header
Default: "/tmp"
*/
DirektivTempDir *string
/*
In: body
*/
Body *models.PostParamsBody
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewPostParams() beforehand.
func (o *PostParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if err := o.bindDirektivActionID(r.Header[http.CanonicalHeaderKey("Direktiv-ActionID")], true, route.Formats); err != nil {
res = append(res, err)
}
if err := o.bindDirektivTempDir(r.Header[http.CanonicalHeaderKey("Direktiv-TempDir")], true, route.Formats); err != nil {
res = append(res, err)
}
if runtime.HasBody(r) {
defer r.Body.Close()
var body models.PostParamsBody
if err := route.Consumer.Consume(r.Body, &body); err != nil {
res = append(res, errors.NewParseError("body", "body", "", err))
} else {
// validate body object
if err := body.Validate(route.Formats); err != nil {
res = append(res, err)
}
// direktiv: add request to context so we can use in validate
baseCtx := context.WithValue(r.Context(), "req", r)
ctx := validate.WithOperationRequest(baseCtx)
if err := body.ContextValidate(ctx, route.Formats); err != nil {
res = append(res, err)
}
if len(res) == 0 {
o.Body = &body
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindDirektivActionID binds and validates parameter DirektivActionID from header.
func (o *PostParams) bindDirektivActionID(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: false
if raw == "" { // empty values pass all other validations
// Default values have been previously initialized by NewPostParams()
return nil
}
o.DirektivActionID = &raw
return nil
}
// bindDirektivTempDir binds and validates parameter DirektivTempDir from header.
func (o *PostParams) bindDirektivTempDir(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: false
if raw == "" { // empty values pass all other validations
// Default values have been previously initialized by NewPostParams()
return nil
}
o.DirektivTempDir = &raw
return nil
}

View File

@@ -0,0 +1,160 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"app/models"
)
// PostOKCode is the HTTP code returned for type PostOK
const PostOKCode int = 200
/*PostOK List of executed commands.
swagger:response postOK
*/
type PostOK struct {
/*
In: Body
*/
Payload *models.PostOKBody `json:"body,omitempty"`
}
// NewPostOK creates PostOK with default headers values
func NewPostOK() *PostOK {
return &PostOK{}
}
// WithPayload adds the payload to the post o k response
func (o *PostOK) WithPayload(payload *models.PostOKBody) *PostOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the post o k response
func (o *PostOK) SetPayload(payload *models.PostOKBody) {
o.Payload = payload
}
// WriteResponse to the client
func (o *PostOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
/*PostDefault generic error response
swagger:response postDefault
*/
type PostDefault struct {
_statusCode int
/*
*/
DirektivErrorCode string `json:"Direktiv-ErrorCode"`
/*
*/
DirektivErrorMessage string `json:"Direktiv-ErrorMessage"`
/*
In: Body
*/
Payload *models.Error `json:"body,omitempty"`
}
// NewPostDefault creates PostDefault with default headers values
func NewPostDefault(code int) *PostDefault {
if code <= 0 {
code = 500
}
return &PostDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the post default response
func (o *PostDefault) WithStatusCode(code int) *PostDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the post default response
func (o *PostDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithDirektivErrorCode adds the direktivErrorCode to the post default response
func (o *PostDefault) WithDirektivErrorCode(direktivErrorCode string) *PostDefault {
o.DirektivErrorCode = direktivErrorCode
return o
}
// SetDirektivErrorCode sets the direktivErrorCode to the post default response
func (o *PostDefault) SetDirektivErrorCode(direktivErrorCode string) {
o.DirektivErrorCode = direktivErrorCode
}
// WithDirektivErrorMessage adds the direktivErrorMessage to the post default response
func (o *PostDefault) WithDirektivErrorMessage(direktivErrorMessage string) *PostDefault {
o.DirektivErrorMessage = direktivErrorMessage
return o
}
// SetDirektivErrorMessage sets the direktivErrorMessage to the post default response
func (o *PostDefault) SetDirektivErrorMessage(direktivErrorMessage string) {
o.DirektivErrorMessage = direktivErrorMessage
}
// WithPayload adds the payload to the post default response
func (o *PostDefault) WithPayload(payload *models.Error) *PostDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the post default response
func (o *PostDefault) SetPayload(payload *models.Error) {
o.Payload = payload
}
// WriteResponse to the client
func (o *PostDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
// response header Direktiv-ErrorCode
direktivErrorCode := o.DirektivErrorCode
if direktivErrorCode != "" {
rw.Header().Set("Direktiv-ErrorCode", direktivErrorCode)
}
// response header Direktiv-ErrorMessage
direktivErrorMessage := o.DirektivErrorMessage
if direktivErrorMessage != "" {
rw.Header().Set("Direktiv-ErrorMessage", direktivErrorMessage)
}
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}