github.com/laof/lite-speed-test@v0.0.0-20230930011949-1f39b7037845/ping/ping.go (about)

     1  package ping
     2  
     3  import (
     4  	"context"
     5  	"flag"
     6  	"fmt"
     7  	"log"
     8  	"time"
     9  
    10  	"github.com/laof/lite-speed-test/web"
    11  )
    12  
    13  type TestResponse struct {
    14  	SuccessIndex []int
    15  	ErrorIndex   []int
    16  	Ok           bool
    17  }
    18  
    19  func Test(url string) (TestResponse, error) {
    20  	link := flag.String("link", url, "link to test")
    21  	mode := flag.String("mode", "pingonly", "speed test mode")
    22  	flag.Parse()
    23  	// link := "vmess://aHR0cHM6Ly9naXRodWIuY29tL3h4ZjA5OC9MaXRlU3BlZWRUZXN0"
    24  	if len(*link) < 1 {
    25  		log.Fatal("link required")
    26  	}
    27  	opts := web.ProfileTestOptions{
    28  		GroupName:     "Default",
    29  		SpeedTestMode: *mode,        //  pingonly speedonly all
    30  		PingMethod:    "googleping", // googleping
    31  		SortMethod:    "rspeed",     // speed rspeed ping rping
    32  		Concurrency:   2,
    33  		TestMode:      2, // 2: ALLTEST 3: RETEST
    34  		Subscription:  *link,
    35  		Language:      "en", // en cn
    36  		FontSize:      24,
    37  		Theme:         "rainbow",
    38  		Timeout:       10 * time.Second,
    39  		OutputMode:    0, // 0: base64 1:file path 2: no pic 3: json 4: txt
    40  	}
    41  	ctx := context.Background()
    42  
    43  	res := TestResponse{SuccessIndex: []int{}, ErrorIndex: []int{}, Ok: false}
    44  
    45  	nodes, err := web.TestContext(ctx, opts, &web.EmptyMessageWriter{})
    46  	if err != nil {
    47  		return res, err
    48  	}
    49  
    50  	for _, node := range nodes {
    51  		// tested node info here
    52  		if node.IsOk {
    53  			fmt.Println("SUCCESS id:", node.Id, node.Remarks, "ping:", node.Ping)
    54  			res.SuccessIndex = append(res.SuccessIndex, node.Id)
    55  		} else {
    56  			fmt.Println("ERROR id:", node.Id)
    57  			res.ErrorIndex = append(res.ErrorIndex, node.Id)
    58  		}
    59  	}
    60  
    61  	if len(res.SuccessIndex) > 0 && len(res.ErrorIndex) == 0 {
    62  		res.Ok = true
    63  	}
    64  
    65  	return res, nil
    66  }