From c7d8b6a3a4a1883137a7bc03d6dbed1ccb21bfb0 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Sun, 18 Jun 2023 17:28:29 +0300 Subject: [PATCH] handler/swagger: initial import Signed-off-by: Vasiliy Tolstov --- handler/swagger/swagger.go | 55 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 handler/swagger/swagger.go diff --git a/handler/swagger/swagger.go b/handler/swagger/swagger.go new file mode 100644 index 0000000..df85a63 --- /dev/null +++ b/handler/swagger/swagger.go @@ -0,0 +1,55 @@ +package swagger + +import ( + "io/fs" + "net/http" + + yamlcodec "go.unistack.org/micro-codec-yaml/v3" + rutil "go.unistack.org/micro/v3/util/reflect" +) + +// Handler append to generated swagger data from dst map[string]interface{} +var Handler = func(dst map[string]interface{}, fsys fs.FS) http.HandlerFunc { + c := yamlcodec.NewCodec() + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusNotFound) + return + } + + path := r.URL.Path + if len(path) > 1 && path[0] == '/' { + path = path[1:] + } + + buf, err := fs.ReadFile(fsys, path) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(err.Error())) + return + } + + var src interface{} + + if err = c.Unmarshal(buf, src); err != nil { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(err.Error())) + return + } + + if err = rutil.Merge(src, dst); err != nil { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(err.Error())) + return + } + + if buf, err = c.Marshal(src); err != nil { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(err.Error())) + return + } + + w.WriteHeader(http.StatusOK) + _, _ = w.Write(buf) + } +}