You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.8 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

//go:build client
package main
import (
"flag"
"fmt"
"log"
"os"
"time"
"github.com/noahlann/nnet/pkg/nnet"
)
// This example demonstrates client testing interceptor validation.
// Usage:
//
// go run ./examples/interceptor/client.go -addr tcp://127.0.0.1:8084 -cmd validate -data "hello"
// go run ./examples/interceptor/client.go -addr tcp://127.0.0.1:8084 -cmd validate -data "hi" # too short
// go run ./examples/interceptor/client.go -addr tcp://127.0.0.1:8084 -cmd validate -data "forbidden" # rejected
// go run ./examples/interceptor/client.go -addr tcp://127.0.0.1:8084 -cmd echo -data "test"
// go run ./examples/interceptor/client.go -addr tcp://127.0.0.1:8084 -cmd test -data "valid data"
func main() {
addr := flag.String("addr", "tcp://127.0.0.1:8084", "server address")
cmd := flag.String("cmd", "validate", "command to send (validate, echo, test)")
data := flag.String("data", "hello world", "data to send")
timeout := flag.Duration("timeout", 3*time.Second, "request timeout")
flag.Parse()
cfg := &nnet.ClientConfig{
Addr: *addr,
ConnectTimeout: 3 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
}
c := nnet.NewClient(cfg)
defer c.Close()
if err := c.Connect(); err != nil {
log.Fatalf("connect failed: %v", err)
}
defer c.Disconnect()
// 构建请求数据
var reqData string
switch *cmd {
case "validate":
// validate命令发送"validate " + 数据
if *data != "" {
reqData = "validate " + *data
} else {
reqData = "validate"
}
case "echo", "test":
// echo和test命令只发送命令
reqData = *cmd
default:
reqData = *cmd
}
resp, err := c.Request([]byte(reqData), *timeout)
if err != nil {
fmt.Fprintf(os.Stderr, "request error: %v\n", err)
os.Exit(1)
}
fmt.Printf("response: %s\n", string(resp))
}