CallInternalServiceAPI 를 gocommon 으로 이동

This commit is contained in:
2023-10-05 12:08:50 +09:00
parent 06ca411e03
commit 9c3d761d97

View File

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