From 9c3d761d97c0c9106aa303f89e9d617cc9117e23 Mon Sep 17 00:00:00 2001 From: mountain Date: Thu, 5 Oct 2023 12:08:50 +0900 Subject: [PATCH] =?UTF-8?q?CallInternalServiceAPI=20=EB=A5=BC=20gocommon?= =?UTF-8?q?=20=EC=9C=BC=EB=A1=9C=20=EC=9D=B4=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server.go | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/server.go b/server.go index e9a46f5..08e8ec4 100644 --- a/server.go +++ b/server.go @@ -779,3 +779,71 @@ func (hc *HttpApiBroker) Call(funcname string, w http.ResponseWriter, r *http.Re logger.Println("api is not found :", funcname) } } + +func CallInternalServiceAPI[T any](url string, apitoken string, method string, data T) error { + reqURL := fmt.Sprintf("%s/api?call=%s", url, method) + + buff := new(bytes.Buffer) + enc := gob.NewEncoder(buff) + enc.Encode(data) + + req, err := http.NewRequest("POST", reqURL, buff) + if err != nil { + return err + } + + req.Header.Set("MG-X-API-TOKEN", apitoken) + req.Header.Set("Content-Type", "application/gob") + + resp, err := http.DefaultClient.Do(req) + defer func() { + if resp != nil && resp.Body != nil { + resp.Body.Close() + } + }() + + if err == nil { + if resp.StatusCode != http.StatusOK { + return &ErrorWithStatus{StatusCode: resp.StatusCode} + } + } + + return err +} + +func CallInternalServiceAPIAs[Tin any, Tout any](url string, apitoken string, method string, data Tin, out *Tout) error { + reqURL := fmt.Sprintf("%s/api?call=%s", url, method) + + buff := new(bytes.Buffer) + enc := gob.NewEncoder(buff) + enc.Encode(data) + + req, err := http.NewRequest("POST", reqURL, buff) + if err != nil { + return err + } + + req.Header.Set("MG-X-API-TOKEN", apitoken) + req.Header.Set("Content-Type", "application/gob") + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return err + } + + if resp.StatusCode != http.StatusOK { + return &ErrorWithStatus{StatusCode: resp.StatusCode} + } + + defer func() { + if resp != nil && resp.Body != nil { + resp.Body.Close() + } + }() + + if out != nil && resp.Body != nil { + dec := gob.NewDecoder(resp.Body) + return dec.Decode(out) + } + return nil +}