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 +}