Go調用注冊到Nacos中的服務

服務調用客戶端

package util

import (
    "fmt"
    "math/rand/v2"
    "net/http"
    "net/url"

    "github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
    "github.com/nacos-group/nacos-sdk-go/v2/vo"
)

type ServiceClient struct {
    namingClient naming_client.INamingClient
    webClient    *WebClient
}

func NewServiceClient(namingClient naming_client.INamingClient, webClient *WebClient) *ServiceClient {
    return &ServiceClient{
        namingClient: namingClient,
        webClient:    webClient,
    }
}

func (m *ServiceClient) Get(serviceName string, path string, urlValues url.Values) (int, []byte, error) {
    _, code, bytees, err := m.Do(serviceName, "GET", "application/json;charset=UTF-8", path, urlValues, nil)

    return code, bytees, err
}

func (m *ServiceClient) Post(serviceName string, path string, bodyValue any) (int, []byte, error) {
    _, code, bytees, err := m.Do(serviceName, "POST", "application/json;charset=UTF-8", path, nil, bodyValue)

    return code, bytees, err
}

func (m *ServiceClient) Put(serviceName string, path string, urlValues url.Values, bodyValue any) (int, []byte, error) {
    _, code, bytees, err := m.Do(serviceName, "PUT", "application/json;charset=UTF-8", path, urlValues, bodyValue)

    return code, bytees, err
}

func (m *ServiceClient) Delete(serviceName string, path string, urlValues url.Values, bodyValue any) (int, []byte, error) {
    _, code, bytees, err := m.Do(serviceName, "DELETE", "application/json;charset=UTF-8", path, urlValues, bodyValue)

    return code, bytees, err
}

func (m *ServiceClient) Do(
    serviceName string,
    method string,
    contentType string,
    path string, urlValues url.Values,
    bodyValue any) (*http.Response, int, []byte, error) {
    serviceUrl, err := m.GetServiceUrl(serviceName)

    if err != nil {
        return nil, 0, nil, err
    }

    return m.webClient.Do(method, contentType, serviceUrl, path, urlValues, bodyValue)
}

func (m *ServiceClient) GetServiceUrl(serviceName string) (string, error) {
    service, err := m.namingClient.GetService(vo.GetServiceParam{ServiceName: serviceName})

    if err != nil {
        return "", err
    }

    if !service.Valid {
        return "", fmt.Errorf("服務(%s)不存在", serviceName)
    }

    urls := make([]string, 0, len(service.Hosts))

    for _, instance := range service.Hosts {
        if instance.Enable && instance.Healthy {
            urls = append(urls, fmt.Sprintf("http://%s:%d", instance.Ip, instance.Port))
        }
    }

    if len(urls) == 0 {
        return "", fmt.Errorf("服務(%s)沒有可用的實例", serviceName)
    }

    if len(urls) == 1 {
        return urls[0], nil
    }

    return urls[rand.IntN(len(urls))], nil
}

Http請求客戶端

package util

import (
    "bytes"
    "encoding/json"
    "io"
    "net/http"
    "net/url"
    "strings"
)

type WebClient struct {
    Client *http.Client
}

func NewWebClient(client *http.Client) *WebClient {
    return &WebClient{Client: client}
}

func (m *WebClient) Get(baseUrl string, path string, urlValues url.Values) (int, []byte, error) {
    _, code, bytees, err := m.Do("GET", "application/json;charset=UTF-8", baseUrl, path, urlValues, nil)

    return code, bytees, err
}

func (m *WebClient) GetRes(baseUrl string, path string, urlValues url.Values) (*http.Response, int, []byte, error) {
    res, code, bytees, err := m.Do("GET", "application/json;charset=UTF-8", baseUrl, path, urlValues, nil)

    return res, code, bytees, err
}

func (m *WebClient) Post(baseUrl string, path string, bodyValue interface{}) (int, []byte, error) {
    _, code, bytees, err := m.Do("POST", "application/json;charset=UTF-8", baseUrl, path, nil, bodyValue)

    return code, bytees, err
}

func (m *WebClient) Put(baseUrl string, path string, urlValues url.Values, bodyValue interface{}) (int, []byte, error) {
    _, code, bytees, err := m.Do("PUT", "application/json;charset=UTF-8", baseUrl, path, urlValues, bodyValue)

    return code, bytees, err
}

func (m *WebClient) Delete(baseUrl string, path string, urlValues url.Values, bodyValue interface{}) (int, []byte, error) {
    _, code, bytees, err := m.Do("DELETE", "application/json;charset=UTF-8", baseUrl, path, urlValues, bodyValue)

    return code, bytees, err
}

func (m *WebClient) Do(method string, contentType string, baseUrl string, path string, urlValues url.Values, bodyValue interface{}) (*http.Response, int, []byte, error) {
    bodyValueBytes, err1 := json.Marshal(bodyValue)

    if err1 != nil {
        return nil, 0, nil, err1
    }

    if req, err := http.NewRequest(method, m.url(baseUrl, path, urlValues), bytes.NewReader(bodyValueBytes)); err != nil {
        return nil, 0, nil, err
    } else {
        return m.doRequest(req, contentType)
    }
}

func (m *WebClient) url(baseUrl string, path string, urlValues url.Values) string {
    result, _ := url.JoinPath(baseUrl, path)

    sb := new(strings.Builder)

    sb.WriteString(result)

    if len(urlValues) > 0 {
        sb.WriteString("?")
        sb.WriteString(urlValues.Encode())
    }

    return sb.String()

}

func (m *WebClient) doRequest(req *http.Request, contentType string) (*http.Response, int, []byte, error) {
    req.Header.Set("Content-Type", contentType)

    if res, err := m.Client.Do(req); err != nil {
        return res, res.StatusCode, nil, err
    } else {
        if resBytes, err := io.ReadAll(res.Body); err != nil {
            return res, res.StatusCode, nil, err
        } else {
            return res, res.StatusCode, resBytes, nil
        }
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子碉怔,更是在濱河造成了極大的恐慌菱涤,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,204評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機趴乡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蝗拿,“玉大人晾捏,你說我怎么就攤上這事“校” “怎么了惦辛?”我有些...
    開封第一講書人閱讀 164,548評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長仓手。 經(jīng)常有香客問我胖齐,道長,這世上最難降的妖魔是什么嗽冒? 我笑而不...
    開封第一講書人閱讀 58,657評論 1 293
  • 正文 為了忘掉前任呀伙,我火速辦了婚禮,結果婚禮上添坊,老公的妹妹穿的比我還像新娘剿另。我一直安慰自己,他們只是感情好贬蛙,可當我...
    茶點故事閱讀 67,689評論 6 392
  • 文/花漫 我一把揭開白布雨女。 她就那樣靜靜地躺著,像睡著了一般阳准。 火紅的嫁衣襯著肌膚如雪氛堕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,554評論 1 305
  • 那天野蝇,我揣著相機與錄音岔擂,去河邊找鬼位喂。 笑死浪耘,一個胖子當著我的面吹牛乱灵,可吹牛的內容都是我干的。 我是一名探鬼主播七冲,決...
    沈念sama閱讀 40,302評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼痛倚,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了澜躺?” 一聲冷哼從身側響起蝉稳,我...
    開封第一講書人閱讀 39,216評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎掘鄙,沒想到半個月后耘戚,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,661評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡操漠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,851評論 3 336
  • 正文 我和宋清朗相戀三年收津,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片浊伙。...
    茶點故事閱讀 39,977評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡撞秋,死狀恐怖,靈堂內的尸體忽然破棺而出嚣鄙,到底是詐尸還是另有隱情吻贿,我是刑警寧澤,帶...
    沈念sama閱讀 35,697評論 5 347
  • 正文 年R本政府宣布哑子,位于F島的核電站舅列,受9級特大地震影響,放射性物質發(fā)生泄漏卧蜓。R本人自食惡果不足惜帐要,卻給世界環(huán)境...
    茶點故事閱讀 41,306評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望烦却。 院中可真熱鬧宠叼,春花似錦、人聲如沸其爵。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽摩渺。三九已至简烤,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間摇幻,已是汗流浹背横侦。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評論 1 270
  • 我被黑心中介騙來泰國打工挥萌, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人枉侧。 一個月前我還...
    沈念sama閱讀 48,138評論 3 370
  • 正文 我出身青樓引瀑,卻偏偏與公主長得像,于是被迫代替她去往敵國和親榨馁。 傳聞我的和親對象是個殘疾皇子憨栽,可洞房花燭夜當晚...
    茶點故事閱讀 44,927評論 2 355

推薦閱讀更多精彩內容