Skip to content

Commit

Permalink
Inputs for HTTP api
Browse files Browse the repository at this point in the history
  • Loading branch information
qbart committed Dec 31, 2021
1 parent 58d4f90 commit d2514cb
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
19 changes: 17 additions & 2 deletions krabapi/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,14 @@ func (a *Agent) Run() error {
switch cmd.HttpMethod() {
case http.MethodPost:
api.POST(path, func(c *gin.Context) {
resp, err := cmd.Do(c.Request.Context(), krab.CmdOpts{})

inputs, err := bindInputs(c)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
return
}

resp, err := cmd.Do(c.Request.Context(), krab.CmdOpts{Inputs: inputs})
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
return
Expand All @@ -38,7 +45,15 @@ func (a *Agent) Run() error {
})
case http.MethodGet:
api.GET(path, func(c *gin.Context) {
resp, err := cmd.Do(c.Request.Context(), krab.CmdOpts{})
c.Header("Cache-Control", "no-store")

inputs, err := bindInputs(c)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
return
}

resp, err := cmd.Do(c.Request.Context(), krab.CmdOpts{Inputs: inputs})
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
return
Expand Down
29 changes: 29 additions & 0 deletions krabapi/params.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package krabapi

import (
"fmt"

"github.com/gin-gonic/gin"
"github.com/ohkrab/krab/krab"
)

func bindInputs(c *gin.Context) (krab.Inputs, error) {
params := map[string]interface{}{}
if c.Request.ContentLength == 0 {
return krab.Inputs{}, nil
}
err := c.BindJSON(&params)
if err != nil {
return krab.Inputs{}, fmt.Errorf("Can't bind inputs: %w", err)
}
inputs, ok := params["inputs"]
if !ok {
return krab.Inputs{}, nil
}

if inputs, ok := inputs.(map[string]interface{}); ok {
return krab.Inputs(inputs), nil
}

return krab.Inputs{}, fmt.Errorf("Failed to fetch inputs")
}

0 comments on commit d2514cb

Please sign in to comment.