Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(gomall/tutorial):ch09 #69

Merged
merged 2 commits into from
Jun 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions gomall/tutorial/ch09/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
app/*/tmp
app/*/.env
12 changes: 6 additions & 6 deletions gomall/tutorial/ch09/Makefile
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
export ROOT_MOD=github.com/cloudwego/biz-demo/gomall
.PHONY: gen-demo-proto
gen-demo-proto:
@cd demo/demo_proto && cwgo server -I ../../idl --module github.com/cloudwego/biz-demo/gomall/demo/demo_proto --service demo_proto --idl ../../idl/echo.proto
@cd demo/demo_proto && cwgo server -I ../../idl --module ${ROOT_MOD}/demo/demo_proto --service demo_proto --idl ../../idl/echo.proto

.PHONY: gen-demo-thrift
gen-demo-thrift:
@cd demo/demo_thrift && cwgo server --module github.com/cloudwego/biz-demo/gomall/demo/demo_thrift --service demo_thrift --idl ../../idl/echo.thrift
@cd demo/demo_thrift && cwgo server --module ${ROOT_MOD}/demo/demo_thrift --service demo_thrift --idl ../../idl/echo.thrift

.PHONY: demo-link-fix
demo-link-fix:
cd demo/demo_proto && golangci-lint run -E gofumpt --path-prefix=. --fix --timeout=5m

.PHONY: gen-frontend
gen-frontend:
@cd app/frontend && cwgo server -I ../../idl --type HTTP --service frontend --module github.com/cloudwego/biz-demo/gomall/app/frontend --idl ../../idl/frontend/auth_page.proto
@cd app/frontend && cwgo server -I ../../idl --type HTTP --service frontend --module ${ROOT_MOD}/app/frontend --idl ../../idl/frontend/auth_page.proto

.PHONY: gen-user
gen-user:
@cd rpc_gen && cwgo client --type RPC --service user --module ${ROOT_MOD}/rpc_gen -I ../idl --idl ../idl/user.proto
@cd app/user && cwgo server --type RPC --service user --module ${ROOT_MOD}/app/user --pass "-use ${ROOT_MOD}/rpc_gen/kitex_gen" -I ../../idl --idl ../../idl/user.proto
gen-user:
@cd app/user && cwgo server --type RPC --service user --module ${ROOT_MOD}/app/user --pass "-use ${ROOT_MOD}/rpc_gen/kitex_gen" -I ../../idl --idl ../../idl/user.proto
@cd rpc_gen && cwgo client --type RPC --service user --module ${ROOT_MOD}/rpc_gen --I ../idl --idl ../idl/user.proto
35 changes: 16 additions & 19 deletions gomall/tutorial/ch09/app/frontend/biz/handler/auth/auth_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,47 +22,45 @@ import (
auth "github.com/cloudwego/biz-demo/gomall/app/frontend/hertz_gen/frontend/auth"
common "github.com/cloudwego/biz-demo/gomall/app/frontend/hertz_gen/frontend/common"
"github.com/cloudwego/hertz/pkg/app"
hertzUtils "github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/protocol/consts"
)

// Register .
// @router /auth/register [POST]
func Register(ctx context.Context, c *app.RequestContext) {
// Login .
// @router /auth/login [POST]
func Login(ctx context.Context, c *app.RequestContext) {
var err error
var req auth.RegisterReq
var req auth.LoginReq
err = c.BindAndValidate(&req)
if err != nil {
utils.SendErrResponse(ctx, c, consts.StatusOK, err)
return
}

_, err = service.NewRegisterService(ctx, c).Run(&req)
redirect, err := service.NewLoginService(ctx, c).Run(&req)
if err != nil {
c.HTML(consts.StatusOK, "sign-up", hertzUtils.H{"error": err})
utils.SendErrResponse(ctx, c, consts.StatusOK, err)
return
}
c.Redirect(consts.StatusFound, []byte("/"))
c.Redirect(consts.StatusFound, []byte(redirect))
}

// Login .
// @router /auth/login [POST]
func Login(ctx context.Context, c *app.RequestContext) {
// Register .
// @router /auth/register [POST]
func Register(ctx context.Context, c *app.RequestContext) {
var err error
var req auth.LoginReq
var req auth.RegisterReq
err = c.BindAndValidate(&req)
if err != nil {
utils.SendErrResponse(ctx, c, consts.StatusOK, err)
return
}

resp, err := service.NewLoginService(ctx, c).Run(&req)
_, err = service.NewRegisterService(ctx, c).Run(&req)

if err != nil {
utils.SendErrResponse(ctx, c, consts.StatusOK, err)
return
}

c.Redirect(consts.StatusFound, []byte(resp))
c.Redirect(consts.StatusFound, []byte("/"))
}

// Logout .
Expand All @@ -77,11 +75,10 @@ func Logout(ctx context.Context, c *app.RequestContext) {
}

_, err = service.NewLogoutService(ctx, c).Run(&req)

if err != nil {
utils.SendErrResponse(ctx, c, consts.StatusOK, err)
return
}
redirect := "/"

c.Redirect(consts.StatusFound, []byte(redirect))
c.Redirect(consts.StatusFound, []byte("/"))
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ import (
"github.com/cloudwego/hertz/pkg/common/ut"
)

func TestRegister(t *testing.T) {
func TestLogin(t *testing.T) {
h := server.Default()
h.POST("/auth/register", Register)
path := "/auth/register" // todo: you can customize query
h.POST("/auth/login", Login)
path := "/auth/login" // todo: you can customize query
body := &ut.Body{Body: bytes.NewBufferString(""), Len: 1} // todo: you can customize body
header := ut.Header{} // todo: you can customize header
w := ut.PerformRequest(h.Engine, "POST", path, body, header)
Expand All @@ -38,10 +38,10 @@ func TestRegister(t *testing.T) {
// assert.DeepEqual(t, "null", string(resp.Body()))
}

func TestLogin(t *testing.T) {
func TestRegister(t *testing.T) {
h := server.Default()
h.POST("/auth/login", Login)
path := "/auth/login" // todo: you can customize query
h.POST("/auth/register", Register)
path := "/auth/register" // todo: you can customize query
body := &ut.Body{Body: bytes.NewBufferString(""), Len: 1} // todo: you can customize body
header := ut.Header{} // todo: you can customize header
w := ut.PerformRequest(h.Engine, "POST", path, body, header)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,10 @@ func Home(ctx context.Context, c *app.RequestContext) {
return
}

// resp, err :=
resp, err := service.NewHomeService(ctx, c).Run(&req)
if err != nil {
utils.SendErrResponse(ctx, c, consts.StatusOK, err)
return
}

c.HTML(consts.StatusOK, "home", utils.WarpResponse(ctx, c, resp))
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 17 additions & 5 deletions gomall/tutorial/ch09/app/frontend/biz/service/home.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (

common "github.com/cloudwego/biz-demo/gomall/app/frontend/hertz_gen/frontend/common"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/common/utils"
)

type HomeService struct {
Expand All @@ -31,8 +30,21 @@ func NewHomeService(Context context.Context, RequestContext *app.RequestContext)
return &HomeService{RequestContext: RequestContext, Context: Context}
}

func (h *HomeService) Run(req *common.Empty) (res map[string]any, err error) {
return utils.H{
"title": "Hot sale",
}, nil
func (h *HomeService) Run(req *common.Empty) (map[string]any, error) {
//defer func() {
// hlog.CtxInfof(h.Context, "req = %+v", req)
// hlog.CtxInfof(h.Context, "resp = %+v", resp)
//}()
var resp = make(map[string]any)
items := []map[string]any{
{"Name": "T-shirt-1", "Price": 100, "Picture": "/static/image/t-shirt-1.jpeg"},
{"Name": "T-shirt-2", "Price": 110, "Picture": "/static/image/t-shirt-1.jpeg"},
{"Name": "T-shirt-3", "Price": 120, "Picture": "/static/image/t-shirt-2.jpeg"},
{"Name": "T-shirt-4", "Price": 130, "Picture": "/static/image/notebook.jpeg"},
{"Name": "T-shirt-5", "Price": 140, "Picture": "/static/image/t-shirt-1.jpeg"},
{"Name": "T-shirt-6", "Price": 150, "Picture": "/static/image/t-shirt.jpeg"},
}
resp["title"] = "Hot Sales"
resp["items"] = items
return resp, nil
}
30 changes: 17 additions & 13 deletions gomall/tutorial/ch09/app/frontend/biz/service/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ import (

auth "github.com/cloudwego/biz-demo/gomall/app/frontend/hertz_gen/frontend/auth"
"github.com/cloudwego/biz-demo/gomall/app/frontend/infra/rpc"
frontendutils "github.com/cloudwego/biz-demo/gomall/app/frontend/utils"
rpcuser "github.com/cloudwego/biz-demo/gomall/rpc_gen/kitex_gen/user"
"github.com/cloudwego/biz-demo/gomall/rpc_gen/kitex_gen/user"
"github.com/cloudwego/hertz/pkg/app"
"github.com/hertz-contrib/sessions"
)
Expand All @@ -34,23 +33,28 @@ func NewLoginService(Context context.Context, RequestContext *app.RequestContext
return &LoginService{RequestContext: RequestContext, Context: Context}
}

func (h *LoginService) Run(req *auth.LoginReq) (resp string, err error) {
res, err := rpc.UserClient.Login(h.Context, &rpcuser.LoginReq{Email: req.Email, Password: req.Password})
func (h *LoginService) Run(req *auth.LoginReq) (redirect string, err error) {
//defer func() {
// hlog.CtxInfof(h.Context, "req = %+v", req)
// hlog.CtxInfof(h.Context, "resp = %+v", resp)
//}()
resp, err := rpc.UserClient.Login(h.Context, &user.LoginReq{
Email: req.Email,
Password: req.Password,
})
if err != nil {
return
return "", err
}

session := sessions.Default(h.RequestContext)
session.Set("user_id", res.UserId)
session.Set("user_id", resp.UserId)
err = session.Save()
frontendutils.MustHandleError(err)
redirect := "/"
if frontendutils.ValidateNext(req.Next) {
redirect = req.Next
}
if err != nil {
return "", err
}

return redirect, nil
redirect = "/"
if req.Next != "" {
redirect = req.Next
}
return
}
9 changes: 8 additions & 1 deletion gomall/tutorial/ch09/app/frontend/biz/service/logout.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,15 @@ func NewLogoutService(Context context.Context, RequestContext *app.RequestContex
}

func (h *LogoutService) Run(req *common.Empty) (resp *common.Empty, err error) {
//defer func() {
// hlog.CtxInfof(h.Context, "req = %+v", req)
// hlog.CtxInfof(h.Context, "resp = %+v", resp)
//}()
session := sessions.Default(h.RequestContext)
session.Clear()
session.Save() //nolint:errcheck
err = session.Save()
if err != nil {
return nil, err
}
return
}
14 changes: 8 additions & 6 deletions gomall/tutorial/ch09/app/frontend/biz/service/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
auth "github.com/cloudwego/biz-demo/gomall/app/frontend/hertz_gen/frontend/auth"
common "github.com/cloudwego/biz-demo/gomall/app/frontend/hertz_gen/frontend/common"
"github.com/cloudwego/biz-demo/gomall/app/frontend/infra/rpc"
rpcuser "github.com/cloudwego/biz-demo/gomall/rpc_gen/kitex_gen/user"
"github.com/cloudwego/biz-demo/gomall/rpc_gen/kitex_gen/user"
"github.com/cloudwego/hertz/pkg/app"
"github.com/hertz-contrib/sessions"
)
Expand All @@ -35,19 +35,21 @@ func NewRegisterService(Context context.Context, RequestContext *app.RequestCont
}

func (h *RegisterService) Run(req *auth.RegisterReq) (resp *common.Empty, err error) {
res, err := rpc.UserClient.Register(h.Context, &rpcuser.RegisterReq{
//defer func() {
// hlog.CtxInfof(h.Context, "req = %+v", req)
// hlog.CtxInfof(h.Context, "resp = %+v", resp)
//}()
userResp, err := rpc.UserClient.Register(h.Context, &user.RegisterReq{
Email: req.Email,
Password: req.Password,
ConfirmPassword: req.Password,
PasswordConfirm: req.PasswordConfirm,
})
if err != nil {
return nil, err
}

session := sessions.Default(h.RequestContext)
session.Set("user_id", res.UserId)
session.Set("user_id", userResp.UserId)
err = session.Save()

if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions gomall/tutorial/ch09/app/frontend/biz/utils/resp.go
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ package utils
import (
"context"

frontendutils "github.com/cloudwego/biz-demo/gomall/app/frontend/utils"
frontendUtils "github.com/cloudwego/biz-demo/gomall/app/frontend/utils"
"github.com/cloudwego/hertz/pkg/app"
)

Expand All @@ -34,6 +34,6 @@ func SendSuccessResponse(ctx context.Context, c *app.RequestContext, code int, d
}

func WarpResponse(ctx context.Context, c *app.RequestContext, content map[string]any) map[string]any {
content["user_id"] = ctx.Value(frontendutils.UserIdKey)
content["user_id"] = frontendUtils.GetUserIdFromCtx(ctx)
return content
}
4 changes: 2 additions & 2 deletions gomall/tutorial/ch09/app/frontend/conf/conf.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package conf

import (
"io/ioutil"
"os"
"path/filepath"
"sync"
Expand Down Expand Up @@ -51,7 +52,6 @@ type Redis struct {

type Hertz struct {
Address string `yaml:"address"`
MetricsPort int `yaml:"metrics_port"`
EnablePprof bool `yaml:"enable_pprof"`
EnableGzip bool `yaml:"enable_gzip"`
EnableAccessLog bool `yaml:"enable_access_log"`
Expand All @@ -72,7 +72,7 @@ func GetConf() *Config {
func initConf() {
prefix := "conf"
confFileRelPath := filepath.Join(prefix, filepath.Join(GetEnv(), "conf.yaml"))
content, err := os.ReadFile(confFileRelPath)
content, err := ioutil.ReadFile(confFileRelPath)
if err != nil {
panic(err)
}
Expand Down
5 changes: 2 additions & 3 deletions gomall/tutorial/ch09/app/frontend/conf/dev/conf.yaml
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
hertz:
address: ":8080"
metrics_port: 8090
enable_pprof: false
enable_pprof: true
enable_gzip: true
enable_access_log: true
log_level: info
log_file_name: "log/hertz.log"
log_max_size: 10
log_max_age: 3
log_max_backups: 50
registry_addr: "localhost:8500"
registry_addr: "127.0.0.1:8500"

mysql:
dsn: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8mb4&parseTime=True&loc=Local"
Expand Down
3 changes: 1 addition & 2 deletions gomall/tutorial/ch09/app/frontend/conf/online/conf.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
hertz:
address: ":8080"
metrics_port: 8090
enable_pprof: false
enable_gzip: true
enable_access_log: true
Expand All @@ -9,7 +8,7 @@ hertz:
log_max_size: 10
log_max_age: 3
log_max_backups: 50
registry_addr: "localhost:8500"
registry_addr: "127.0.0.1:8500"

mysql:
dsn: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8mb4&parseTime=True&loc=Local"
Expand Down
3 changes: 1 addition & 2 deletions gomall/tutorial/ch09/app/frontend/conf/test/conf.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
hertz:
address: ":8080"
metrics_port: 8090
enable_pprof: true
enable_gzip: true
enable_access_log: true
Expand All @@ -9,7 +8,7 @@ hertz:
log_max_size: 10
log_max_age: 3
log_max_backups: 50
registry_addr: "localhost:8500"
registry_addr: "127.0.0.1:8500"

mysql:
dsn: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8mb4&parseTime=True&loc=Local"
Expand Down
Loading
Loading