refactor:使用指定DNS彻底解决DNS缓存导致的问题

This commit is contained in:
Mmx
2021-05-07 14:06:53 +08:00
parent 393f60786a
commit 89e3197e33
5 changed files with 35 additions and 23 deletions

View File

@@ -1,9 +1,12 @@
package Request
import (
"Mmx/Util"
"io/ioutil"
"log"
"net"
"net/http"
"time"
)
func Get(Url string, Query map[string]string) (string, error) {
@@ -20,7 +23,17 @@ func Get(Url string, Query map[string]string) (string, error) {
}
req.URL.RawQuery = q.Encode()
}
resp, err := (&http.Client{}).Do(req)
resp, err := (&http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
Resolver: &net.Resolver{
PreferGo: true,
Dial: Util.NetDailEr(),
},
}).DialContext,
},
}).Do(req)
if err != nil {
log.Println(err)
return "", err

View File

@@ -1,36 +1,23 @@
package Util
import (
"Mmx/Request"
"fmt"
"context"
"net"
"time"
)
type checker struct{}
var Checker checker
func (checker) NetOk(url string) bool {
if ip, err := net.LookupIP("www.msftconnecttest.com"); err != nil { //通过DNS确认是否在线
func (checker) NetOk() bool {
r := &net.Resolver{ //指定DNS防止本地DNS缓存影响
PreferGo: true,
Dial: NetDailEr(),
}
if ip, err := r.LookupIP(context.Background(), "ip4", "www.msftconnecttest.com"); err != nil { //通过DNS确认是否在线
return false
} else if len(ip) == 0 || ip[0].String() != "13.107.4.52" {
return false
}
{ //有些路由器有DNS缓存故进行进一步确认
body, err := Request.Get(url, map[string]string{
"callback": "jQuery1635413",
"_": fmt.Sprint(time.Now().UnixNano()),
})
ErrHandler(err)
r, err := GetResult(body)
if err != nil {
ErrHandler(err)
}
if r != "ok" {
return false
}
}
return true
}

View File

@@ -2,13 +2,16 @@ package Util
import (
"Mmx/Global"
"context"
"crypto/md5"
"crypto/sha1"
"errors"
"fmt"
"io"
"net"
"os"
"regexp"
"time"
)
func Search(reg string, content string) (string, error) {
@@ -57,3 +60,12 @@ func ErrHandler(err error) {
os.Exit(1)
}
}
func NetDailEr() func(ctx context.Context, network, address string) (net.Conn, error) {
return func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{
Timeout: 20 * time.Second,
}
return d.DialContext(ctx, "udp", "1.2.4.8:53")
}
}

View File

@@ -13,7 +13,7 @@ func main() {
Util.Log.Println("Step0: 检查状态…")
G := Global.Config.Generate()
if Global.Config.Settings.QuitIfNetOk && Util.Checker.NetOk(G.UrlCheckApi) {
if Global.Config.Settings.QuitIfNetOk && Util.Checker.NetOk() {
Util.Log.Println("网络正常,程序退出")
return
}