1.路徑\src\client\main.go
2.客戶端呼叫服務端增刪改查介面:
package main
import (
"context"
"flag"
"github.com/golang/protobuf/ptypes"
v1 "goWebGin/api/proto/v1"
"google.golang.org/grpc"
"log"
"time"
)
const (
apiVersion = "v1"
)
func main() {
address := flag.String("server", "", "gRPC server in format host:port")
flag.Parse()
conn, err := grpc.Dial(*address, grpc.WithInsecure())
if err != nil {
log.Fatal("伺服器,連線不上:%s", err)
}
defer func() {
_ = conn.Close()
}()
c := v1.NewToDoServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
cancel()
}()
CreateHandle(ctx, c)
}
func CreateHandle(ctx context.Context, c v1.ToDoServiceClient) {
t := time.Now().In(time.UTC)
reminder, _ := ptypes.TimestampProto(t)
pfx := t.Format(time.RFC3339Nano)
req1 := v1.CreateRequest{
Api: apiVersion,
ToDo: &v1.ToDo{
Title: "title(" + pfx + ")",
Description: "description" + pfx,
Reminder: reminder,
},
}
res1, err := c.Create(ctx, &req1)
if err != nil {
log.Fatal("建立失敗:%v", err)
}
log.Printf("Create result:%v", res1)
}
func ReadOneByIdHandle(ctx context.Context, c v1.ToDoServiceClient, id int64) {
req2 := v1.ReadRequest{
Api: apiVersion,
Id: id,
}
res2, err := c.Read(ctx, &req2)
if err != nil {
log.Fatal("讀取失敗,%v", err)
}
log.Printf("read result: %v", res2)
}
func UpdateHandle(ctx context.Context, c v1.ToDoServiceClient, id int64) {
req3 := v1.UpdateRequest{
Api: apiVersion,
ToDo: &v1.ToDo{
Id: id,
Title: "新Title",
Description: "描述",
Reminder: ptypes.TimestampNow(),
},
}
res3, err := c.Update(ctx, &req3)
if err != nil {
log.Fatal("更新失敗 %v", err)
}
log.Printf("Update result: %v", res3)
}
func ReadAllHandle(ctx context.Context, c v1.ToDoServiceClient) {
req4 := v1.ReadAllRequest{
Api: apiVersion,
}
res4, err := c.ReadAll(ctx, &req4)
if err != nil {
log.Fatal("獲取全部資料失敗 %v", err)
}
log.Printf("ReadAll result: %v", res4)
}
func DeleteHandle(ctx context.Context, c v1.ToDoServiceClient, id int64) {
req5 := v1.DeleteRequest{
Api: apiVersion,
Id: id,
}
res5, err := c.Delete(ctx, &req5)
if err != nil {
log.Fatal("刪除失敗 %v", err)
}
log.Printf("delete result: %v", res5)
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結