背景
專案在做三方推送時需要先判斷三方服務是否存活,以避免不必要的錯誤推送
原理
利用HTTP的OPTIONS:這個方法極少使用,它用于獲取當前URL所支持的方法,若請求成功,則它會在HTTP頭中包含一個名為“Allow”的頭,其中的值是所支持的方法,如“GET, POST”,這樣就能夠檢測出服務是否支持該方法繼而檢測存活
示例代碼
package httputils
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"os"
)
//http 探針
func HttpProbe(httpPool *hcpool.Pool, url string) bool {
req, _ := http.NewRequest("OPTIONS", url, nil)
resp, _ := httpPool.Do(req)
if resp != nil{
defer resp.Body.Close()
//fmt.Println("response code",resp.StatusCode)
if resp.StatusCode == 200 {
//ioutil.ReadAll(resp.Body)
return true
}
}
return false
}
//http檢測
func httpProbe() {
iotlogger.Info("啟動探針")
for {
if cfg, ok := getPushCfg(config.System.Cid); ok == true {
//推送資料
if len(cfg.PushUrl) == 0 {
iotlogger.Info("httpProbe pushUrl is null")
continue
}
if httputils.HttpProbe(httpPool, cfg.PushUrl) {
isLive = true
} else {
isLive = false
}
iotlogger.Debug("探測地址->%s ,是否存活->%t", cfg.PushUrl, isLive)
}
time.Sleep(time.Second * 10)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/236645.html
標籤:區塊鏈
