Skip to content

Commit

Permalink
Refactor API handler to improve content type handling and response he…
Browse files Browse the repository at this point in the history
…ader management; update file processing for better error handling
  • Loading branch information
trheyi committed Oct 30, 2024
1 parent 4faa595 commit 1cf3dbe
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
12 changes: 8 additions & 4 deletions api/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 30,7 @@ func (path Path) defaultHandler(getArgs argsHandler) func(c *gin.Context) {
defer cancel()
path.setPayload(c)
var status int = path.Out.Status
var contentType = path.reqContentType(c)
var contentType = path.reqContentType(c) // Get the defined content type at API DSL

chRes := make(chan interface{}, 1)
go path.execProcess(ctx, chRes, c, getArgs)
Expand All @@ -43,7 43,7 @@ func (path Path) defaultHandler(getArgs argsHandler) func(c *gin.Context) {
return
}

// Set ContentType
// Set Headers and renew Content-Type
contentType = path.setResponseHeaders(c, resp, contentType)

// Format Body
Expand Down Expand Up @@ -335,22 335,26 @@ func (path Path) reqContentType(c *gin.Context) string {
}

func (path Path) setResponseHeaders(c *gin.Context, resp interface{}, contentType string) string {

// Get Content-Type
headers := map[string]string{}
if len(path.Out.Headers) > 0 {
res := any.Of(resp)

// Parse Headers
if res.IsMap() {
data := res.Map().MapStrAny.Dot()
for name, value := range path.Out.Headers {
headers[name] = value
v := helper.Bind(value, data)
if v != nil {
path.Out.Headers[name] = fmt.Sprintf("%v", v)
headers[name] = fmt.Sprintf("%v", v)
}
}
}

// Set Headers and replace Content-Type if exists
for name, value := range path.Out.Headers {
for name, value := range headers {
c.Writer.Header().Set(name, value)
if name == "Content-Type" {
contentType = value
Expand Down
7 changes: 5 additions & 2 deletions fs/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -575,12 575,15 @@ func processDownload(process *process.Process) interface{} {
process.ValidateArgNums(1)
stor := stor(process)
file := process.ArgsString(0)
reader, err := ReadCloser(stor, file)

// Get the file mime type
mimeType, err := MimeType(stor, file)
if err != nil {
exception.New(err.Error(), 500).Throw()
}

mimeType, err := MimeType(stor, file)
// Get the file reader
reader, err := ReadCloser(stor, file)
if err != nil {
exception.New(err.Error(), 500).Throw()
}
Expand Down

0 comments on commit 1cf3dbe

Please sign in to comment.