Skip to content

Commit

Permalink
support body.
Browse files Browse the repository at this point in the history
Signed-off-by: Jeff Ortel <[email protected]>
  • Loading branch information
jortel committed Sep 25, 2024
1 parent 869442d commit 79363c1
Showing 1 changed file with 51 additions and 1 deletion.
52 changes: 51 additions & 1 deletion api/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"time"

"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/konveyor/tackle2-hub/model"
)

Expand Down Expand Up @@ -194,6 +195,18 @@ func (h FileHandler) Delete(ctx *gin.Context) {

// create a file.
func (h FileHandler) create(ctx *gin.Context, name string) (m *model.File, err error) {
mode := ctx.ContentType()
switch mode {
case binding.MIMEMultipartPOSTForm:
m, err = h.createMultipart(ctx, name)
default:
m, err = h.createBody(ctx, name)
}
return
}

// create a file with multipart form.
func (h FileHandler) createMultipart(ctx *gin.Context, name string) (m *model.File, err error) {
input, err := ctx.FormFile(FileField)
if err != nil {
err = &BadRequestError{err.Error()}
Expand All @@ -211,7 +224,7 @@ func (h FileHandler) create(ctx *gin.Context, name string) (m *model.File, err e
defer func() {
if err != nil {
h.Status(ctx, http.StatusInternalServerError)
_ = h.DB(ctx).Delete(&m)
_ = db.Delete(&m)
return
}
}()
Expand Down Expand Up @@ -241,6 +254,43 @@ func (h FileHandler) create(ctx *gin.Context, name string) (m *model.File, err e
return
}

// create a file with request body.
func (h FileHandler) createBody(ctx *gin.Context, name string) (m *model.File, err error) {
m = &model.File{}
m.Name = name
m.Encoding = binding.MIMEYAML
m.CreateUser = h.BaseHandler.CurrentUser(ctx)
db := h.DB(ctx)
err = db.Create(&m).Error
if err != nil {
return
}
defer func() {
if err != nil {
h.Status(ctx, http.StatusInternalServerError)
_ = db.Delete(&m)
return
}
}()
reader := ctx.Request.Body
writer, err := os.Create(m.Path)
if err != nil {
return
}
defer func() {
_ = writer.Close()
}()
_, err = io.Copy(writer, reader)
if err != nil {
return
}
err = os.Chmod(m.Path, 0666)
if err != nil {
return
}
return
}

// delete the specified file.
func (h FileHandler) delete(ctx *gin.Context, m *model.File) (err error) {
err = os.Remove(m.Path)
Expand Down

0 comments on commit 79363c1

Please sign in to comment.