API GatewayCode callsfood rpcservice

Add the following code to the addFoodHandler. go file under API /internal/handler

func AddFoodHandler(ctx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.AddFoodRequest
		iferr := httpx.Parse(r, &req); err ! =nil {
			httpx.OkJson(w, ningxi.FailureResponse(nil,err.Error(),1000))
			return
		}
		userId:=r.Header.Get("x-user-id")
		l := logic.NewAddFoodLogic(r.Context(), ctx)
		resp, err := l.AddFood(req,userId)
		iferr ! =nil {
			httpx.OkJson(w, ningxi.FailureResponse(nil,err.Error(),1000))}else {
			httpx.OkJson(w, ningxi.SuccessResponse(resp,"New success"))}}}Copy the code

As you can see, we added the x-user-ID in this code, because addfood requires authentication, and we also added the X-user-ID in the header

At the same time addFoodLogic. go we also added a parameter userID. The code generated by the original template did not have the userID parameter. However, the following business logic requires userID again, so we changed it slightly.

Edit addFoodlogic. go file under API /internal/logic, add call addfood method of food RPC

func (l *AddFoodLogic) AddFood(req types.AddFoodRequest,userid string) (*types.FoodResponse, error) {
	// todo: add your logic here and delete this line
	_,err := l.svcCtx.Food.AddFood(l.ctx,&food.AddFoodRequest{
		Userid: userid,
		Foodid: req.Id,
	})
	iferr ! =nil{
		return &types.FoodResponse{}, nil
	} else {
		return nil, err
	}
}
Copy the code

Define the database table structure and generate CRUD+cache code

Edit the food. SQL file under model and add the following contents.

CREATE TABLE `user_food` (
                             `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id'.`userid` bigint COMMENT 'user Id'.`foodid` bigint COMMENT 'food Id'.`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
                             `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                             PRIMARY KEY (`id`),
                             UNIQUE KEY `userid_index` (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
Copy the code

Run the following command in the model directory to generate the CRUD+cache code: -c indicates redis cache

goctl model mysql ddl -c -src food.sql -dir .
Copy the code

rpcCode callscrud+cachecode

Edit the servicecontext. go file under RPC /food/internal/ SVC, add the UserFoodModel variable, add the instantiation code.

type ServiceContext struct {
	Config config.Config
	Model model.FoodModel
	UserFoodModel model.UserFoodModel
}

func NewServiceContext(c config.Config) *ServiceContext {
	return &ServiceContext{
		Config: c,
		Model: model.NewFoodModel(sqlx.NewMysql(c.DataSource),c.Cache),
		UserFoodModel: model.NewUserFoodModel(sqlx.NewMysql(c.DataSource),c.Cache),
	}
}
Copy the code

Edit the addFoodlogic. go file in RPC /food/internal/logic and add the following codes

func (l *AddFoodLogic) AddFood(in *food.AddFoodRequest) (*food.StatusResponse, error) {
	newid,_ := strconv.ParseInt(in.Userid,10,64)
	newfoodid,_ := strconv.ParseInt(in.Foodid,10,64)

	_, err := l.svcCtx.UserFoodModel.Insert(model.UserFood{
		Userid: newid,
		Foodid: newfoodid,
	})
	if err != nil {
		return nil,err
	}
	return &food.StatusResponse{
		Success: 1,
	}, nil
}
Copy the code

Start the service

Start the service. Note that before starting the service, you need to make sure that the ningxi-compose used in the previous article is up and running.

Start the food RPC service. After the service runs successfully, the food RPC runs on port 8089 of the machine

➜ FoodGuides git: (master) ✗ go run foodmanage/RPC/food/food. Go - f foodmanage/RPC/food/etc/food. The yaml Starting the RPC server The at 127.0.0.1:8089...Copy the code

Start the Food API service. After successful operation, the food API will run on port 8889 of the machine

➜ FoodGuides Git :(Master) Eligible Starting Server at 0.0.20:8889...Copy the code

If the API test results are as follows, the service is running properly

➜ FoodGuides git: (master) ✗ curl, the location, the request POST 'http://localhost:8889/food/addfood' \ - the header 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTE5MzI3MDMsImlhdCI6MTYxMTg0NjMwMywidXNlcklkIjoxfQ.bdJzc4h2NaXmYwi3MrSt KJaDb84GzVYgyerLVeWilpo' \ --header 'x-user-id: 1' \ --header 'Content-Type: Application/json \ '- data - raw' {" foodId ":" 1 "} '{" code ": 1, the" message ":" new success ", "result" : {}} % ➜ FoodGuides ✗ git: (master)Copy the code

This completes the development of Food RPC-AddFood.

Go-zero Tutorial — Food Rpc-Search

The next go-Zero Tutorial — Food Rpc-deleteFood