grpc-mocker/client/main.go

50 lines
1.1 KiB
Go

package main;
import (
"fmt"
"log"
"net/http"
"strconv"
pb "git.strikerlulu.me/strikerlulu/grpc-mocker/pb"
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
)
func main() {
conn, err := grpc.Dial("grpc-server:3000", grpc.WithInsecure())
if err != nil {
log.Fatalf("Dial failed: %v", err)
}
client := pb.NewCalcServiceClient(conn)
r := gin.Default()
r.GET("/add/:x/:y", func(c *gin.Context) {
x, err := strconv.ParseUint(c.Param("x"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid parameter X"})
return
}
y, err := strconv.ParseUint(c.Param("y"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid parameter Y"})
return
}
req := &pb.AdditionRequest{X: x,Y: y}
if res, err := client.Add(c, req); err == nil {
c.JSON(http.StatusOK, gin.H{
"result": fmt.Sprint(res.Result),
})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
})
if err := r.Run(":3000"); err != nil {
log.Fatalf("Failed to run server: %v", err)
}
}