The API Gateway code invokes the User RPC service

With the introduction of the previous article, we are going to speed up development.

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

func RegisterHandler(ctx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.RegisterRequest
		iferr := httpx.Parse(r, &req); err ! =nil {
			httpx.OkJson(w, ningxi.FailureResponse(nil,err.Error(),1000))
			return
		}

		l := logic.NewRegisterLogic(r.Context(), ctx)
		resp, err := l.Register(req)
		iferr ! =nil {
			httpx.OkJson(w, ningxi.FailureResponse(nil,err.Error(),1000))}else {
			httpx.OkJson(w, ningxi.SuccessResponse(resp,"Registration successful"))}}}Copy the code

Edit the registerlogic.go file under API /internal/logic and add the following code

func (l *RegisterLogic) Register(req types.RegisterRequest) (*types.RegisterResponse, error) {
	
	resp,err := l.svcCtx.User.Register(l.ctx,&user.RegisterRequest{
		Username: req.Username,
		Email: req.Email,
		Password: req.Password,
	})
	
	iferr ! =nil {
		return nil, err
	}

	token := types.JwtToken{
		AccessToken: resp.AccessToken,
		AccessExpire: resp.AccessExpire,
		RefreshAfter: resp.RefreshAfter,
	}

	response := types.UserReply{
		Id: resp.Id,
		Email: resp.Email,
		JwtToken: token,
	}

	return &types.RegisterResponse{
		response,
	},nil
}
Copy the code

rpcCode callscrud+cachecode

Edit the registerlogic.go file in RPC /user/internal/logic and add the following code

func (l *RegisterLogic) Register(in *user.RegisterRequest) (*user.Response, error) { _, err := l.svcCtx.Model.FindOneByEmail(in.Email) if err == model.ErrNotFound { newuser := model.User{ Name: in.Username, Email: in.Email, Password: ningxi.PasswordEncrypt(l.svcCtx.Config.Salt,in.Password), } if result ,err := l.svcCtx.Model.Insert(newuser); err ! = nil { return nil, err } else { newuser.Id , err = result.LastInsertId() if err ! = nil { return nil, err } else { now := time.Now().Unix() accessExpire := l.svcCtx.Config.AccessExpire jwtToken, err := ningxi.GetJwtToken(l.svcCtx.Config.AccessSecret, now, accessExpire, newuser.Id) if err ! = nil { return nil, err } response := user.Response{ Email: newuser.Email, Id: newuser.Id, AccessToken: jwtToken, AccessExpire: now + accessExpire, RefreshAfter: now + accessExpire/2, } return &response, nil } } } else if err == nil { return nil, Errors. New(" the user already exists ")} else {return nil, err}}Copy the code

The GetJwtToken method is a common one, so we wrote it in ningxi.go

package ningxi import ( "fmt" "github.com/dgrijalva/jwt-go" "golang.org/x/crypto/scrypt" ) type HttpResponse struct { Code int `json:"code"` Message string `json:"message"` Result interface{} `json:"result"` } func SuccessResponse(resData  interface{},message string) HttpResponse { return HttpResponse{Code:1,Message: message,Result: resData} } func FailureResponse(resData interface{},message string,code int) HttpResponse { return HttpResponse{Code:code,Message: message,Result: resData} } func PasswordEncrypt(salt,password string) string { dk,_ := scrypt.Key([]byte(password), []byte(salt), 32768, 8, 1, 32) return fmt.Sprintf("%x",string(dk)) } func GetJwtToken(secretKey string, iat, seconds, userId int64) (string, error) { claims := make(jwt.MapClaims) claims["exp"] = iat + seconds claims["iat"] = iat claims["userId"] = userId token  := jwt.New(jwt.SigningMethodHS256) token.Claims = claims return token.SignedString([]byte(secretKey)) }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.

After the user RPC service is successfully started, the User RPC runs on port 8080 of the local host

➜ FoodGuides git: (master) ✗ go run usermanage/RPC/user/user. The go - f usermanage/RPC/user/etc/user. The yaml Starting the RPC server The at 127.0.0.1:8080...Copy the code

After the user API service is successfully started, the user API is running on port 8888 of the local host

➜ FoodGuides git:(master) qualify go run usermanage/ API /user.go -f usermanage/ API /etc/user-api.yaml Starting server at 0.0.0.0:8888...Copy the code

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

➜ ~ curl http://localhost:8888/users/register - X POST - d '{" username ":" ningxi3 ", "email" : "[email protected]","password": "ningixi3"}' --header "Content-Type: application/json" {" code ": 1, the" message ":" registration ", "result" : {" id ": 3," username ":" ", "email" : "[email protected]", "accessToken" : "eyJhbGciOiJIUzI1Ni IsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTE1NTM5MjAsImlhdCI6MTYxMTQ2NzUyMCwidXNlcklkIjozfQ.exhP3C79W35OlSHL4JFsCgpWdebtuCQzxJGsYQ WI3xo accessExpire ", "" : 1611553920," refreshAfter ": 1611510720}} % ➜ ~Copy the code

This completes the development of the User RPC-Register.

Go-zero tutorial — User Rpc-Login

The next go-Zero tutorial — User Rpc-userInfo