From 1cf3dbe9d250475edc6cca0c58d56db798596152 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 30 Oct 2024 18:02:01 +0800 Subject: [PATCH] Refactor API handler to improve content type handling and response header management; update file processing for better error handling --- api/handler.go | 12 ++++++++---- fs/process.go | 7 +++++-- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/api/handler.go b/api/handler.go index 9f55c08..ab34456 100644 --- a/api/handler.go +++ b/api/handler.go @@ -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) @@ -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 @@ -335,6 +335,9 @@ 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) @@ -342,15 +345,16 @@ func (path Path) setResponseHeaders(c *gin.Context, resp interface{}, contentTyp 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 diff --git a/fs/process.go b/fs/process.go index c1524c9..c00fc7e 100644 --- a/fs/process.go +++ b/fs/process.go @@ -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() }