把server归到统一文件夹

This commit is contained in:
eson
2023-06-08 10:51:56 +08:00
parent dc73ff1679
commit 859c101c51
36 changed files with 179 additions and 67 deletions

View File

@@ -0,0 +1,9 @@
Name: home-user-auth
Host: 0.0.0.0
Port: 8888
SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest
Auth:
AccessSecret: fusen2023
AccessExpire: 60
RefreshAfter: 60

View File

@@ -0,0 +1,31 @@
package main
import (
"flag"
"fmt"
"fusenapi/server/home-user-auth/internal/config"
"fusenapi/server/home-user-auth/internal/handler"
"fusenapi/server/home-user-auth/internal/svc"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
var configFile = flag.String("f", "etc/home-user-auth.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
server := rest.MustNewServer(c.RestConf)
defer server.Stop()
ctx := svc.NewServiceContext(c)
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
}

View File

@@ -0,0 +1,7 @@
package main
import "testing"
func TestMain(t *testing.T) {
main()
}

View File

@@ -0,0 +1,13 @@
package config
import (
"fusenapi/server/home-user-auth/internal/types"
"github.com/zeromicro/go-zero/rest"
)
type Config struct {
rest.RestConf
SourceMysql string
Auth types.Auth
}

View File

@@ -0,0 +1,37 @@
package handler
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/server/home-user-auth/internal/logic"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
)
func GetTypeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.Request
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &types.Response{
Code: 510,
Message: "parameter error",
})
logx.Info(err)
return
}
l := logic.NewGetTypeLogic(r.Context(), svcCtx)
resp := l.GetType(&req)
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,53 @@
// Code generated by goctl. DO NOT EDIT.
package handler
import (
"net/http"
"fusenapi/server/home-user-auth/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodPost,
Path: "/user/login",
Handler: UserLoginHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/user/fonts",
Handler: UserFontsHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/user/get-type",
Handler: GetTypeHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/user/basic-info",
Handler: UserSaveBasicInfoHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/user/status-config",
Handler: UserStatusConfigHandler(serverCtx),
},
},
)
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodGet,
Path: "/user/basic-info",
Handler: UserBasicInfoHandler(serverCtx),
},
},
rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
)
}

View File

@@ -0,0 +1,37 @@
package handler
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/server/home-user-auth/internal/logic"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
)
func UserBasicInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.Request
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &types.Response{
Code: 510,
Message: "parameter error",
})
logx.Info(err)
return
}
l := logic.NewUserBasicInfoLogic(r.Context(), svcCtx)
resp := l.UserBasicInfo(&req)
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,37 @@
package handler
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/server/home-user-auth/internal/logic"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
)
func UserFontsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.Request
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &types.Response{
Code: 510,
Message: "parameter error",
})
logx.Info(err)
return
}
l := logic.NewUserFontsLogic(r.Context(), svcCtx)
resp := l.UserFonts(&req)
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,42 @@
package handler
import (
"errors"
"fmt"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/server/home-user-auth/internal/logic"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
"fusenapi/utils/basic"
)
func UserLoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.RequestUserLogin
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &types.Response{
Code: 510,
Message: "parameter error",
})
logx.Info(err)
return
}
l := logic.NewUserLoginLogic(r.Context(), svcCtx)
resp, token := l.UserLogin(&req)
if resp.Code == basic.CodeOK.Code {
w.Header().Add("Authorization", fmt.Sprintf("Bearer %s", token))
}
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,37 @@
package handler
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/server/home-user-auth/internal/logic"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
)
func UserSaveBasicInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.RequestBasicInfoForm
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &types.Response{
Code: 510,
Message: "parameter error",
})
logx.Info(err)
return
}
l := logic.NewUserSaveBasicInfoLogic(r.Context(), svcCtx)
resp := l.UserSaveBasicInfo(&req)
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,37 @@
package handler
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/server/home-user-auth/internal/logic"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
)
func UserStatusConfigHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.RequestBasicInfoForm
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &types.Response{
Code: 510,
Message: "parameter error",
})
logx.Info(err)
return
}
l := logic.NewUserStatusConfigLogic(r.Context(), svcCtx)
resp := l.UserStatusConfig(&req)
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,35 @@
package logic
import (
"context"
"fusenapi/model"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
"fusenapi/utils/basic"
"github.com/zeromicro/go-zero/core/logx"
)
type GetTypeLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetTypeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTypeLogic {
return &GetTypeLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetTypeLogic) GetType(req *types.Request) (resp *types.Response) {
data, err := model.NewFsCanteenTypeModel(l.svcCtx.MysqlConn).FindGetType(l.ctx)
if err != nil {
logx.Error(err)
return
}
return resp.SetStatus(basic.CodeOK, "success", data)
}

View File

@@ -0,0 +1,39 @@
package logic
import (
"context"
"fusenapi/model"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"github.com/zeromicro/go-zero/core/logx"
)
type UserBasicInfoLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUserBasicInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserBasicInfoLogic {
return &UserBasicInfoLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UserBasicInfoLogic) UserBasicInfo(req *types.Request) (resp *types.Response) {
loginInfo := auth.GetUserInfoFormCtx(l.ctx)
if loginInfo.UserId == 0 {
return resp.SetStatus(basic.CodeOK, "parse login info err ")
}
fsUserModel, err := model.NewFsUserModel(l.svcCtx.MysqlConn).FindOne(l.ctx, loginInfo.UserId)
if err != nil {
logx.Error(err)
return resp.Set(510, err.Error())
}
return resp.SetStatus(basic.CodeOK, fsUserModel)
}

View File

@@ -0,0 +1,36 @@
package logic
import (
"context"
"fusenapi/model"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
"fusenapi/utils/basic"
"github.com/zeromicro/go-zero/core/logx"
)
type UserFontsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUserFontsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserFontsLogic {
return &UserFontsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UserFontsLogic) UserFonts(req *types.Request) (resp *types.Response) {
data, err := model.NewFsFontModel(l.svcCtx.MysqlConn).FindAllOrderSortByDesc(l.ctx)
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeOK, data)
}
return resp.SetStatus(basic.CodeOK)
}

View File

@@ -0,0 +1,72 @@
package logic
import (
"context"
"time"
"fusenapi/model"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
"fusenapi/utils/basic"
"github.com/golang-jwt/jwt"
"github.com/zeromicro/go-zero/core/logx"
)
type UserLoginLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
return &UserLoginLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UserLoginLogic) genJwtToken(accessSecret string, accessExpire, nowSec, userid int64) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = nowSec + accessExpire
claims["iat"] = nowSec
claims["userid"] = userid
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(accessSecret))
}
func (l *UserLoginLogic) UserLogin(req *types.RequestUserLogin) (resp *types.Response, jwtToken string) {
m := model.NewFsUserModel(l.svcCtx.MysqlConn)
userModel, err := m.FindOneByEmail(l.ctx, req.Name)
if err == model.ErrNotFound {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, err.Error()), jwtToken
}
if userModel.PasswordHash != req.Password {
logx.Info("密码错误")
return resp.SetStatusWithMessage(basic.CodeUnAuth, "密码错误"), jwtToken
}
// jwt 生成
nowSec := time.Now().Unix()
jwtToken, err = l.genJwtToken(l.svcCtx.Config.Auth.AccessSecret, l.svcCtx.Config.Auth.AccessExpire, nowSec, userModel.Id)
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeUnAuth), jwtToken
}
err = m.UpdateVerificationToken(l.ctx, userModel.Id, jwtToken)
if err != nil {
return resp.SetStatus(basic.CodeUnAuth), jwtToken
}
data := &types.DataUserLogin{
Token: jwtToken,
}
return resp.SetStatus(basic.CodeOK, data), jwtToken
}

View File

@@ -0,0 +1,45 @@
package logic
import (
"context"
"fusenapi/utils/auth"
"fusenapi/model"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
"fusenapi/utils/basic"
"github.com/zeromicro/go-zero/core/logx"
)
type UserSaveBasicInfoLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUserSaveBasicInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserSaveBasicInfoLogic {
return &UserSaveBasicInfoLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UserSaveBasicInfoLogic) UserSaveBasicInfo(req *types.RequestBasicInfoForm) (resp *types.Response) {
loginInfo := auth.GetUserInfoFormCtx(l.ctx)
if loginInfo.UserId == 0 {
return resp.SetStatus(basic.CodeOK, "parse login info err ")
}
fsUserModel, err := model.NewFsUserModel(l.svcCtx.MysqlConn).FindOne(l.ctx, loginInfo.UserId)
if err != nil {
if err == model.ErrNotFound {
return resp
}
logx.Error(err)
return resp
}
return resp.SetStatus(basic.CodeOK, fsUserModel)
}

View File

@@ -0,0 +1,92 @@
package logic
import (
"context"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
"fusenapi/utils/basic"
"github.com/zeromicro/go-zero/core/logx"
)
type UserStatusConfigLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUserStatusConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserStatusConfigLogic {
return &UserStatusConfigLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UserStatusConfigLogic) UserStatusConfig(req *types.RequestBasicInfoForm) (resp *types.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
return resp.SetStatus(basic.CodeOK)
}
// [
// //返回订单每个状态值
// //搜索下拉列表
// 'search_list' => [
// ['key' => -1, "name" => 'All'],
// ['key' => 1, "name" => 'Order Has Been Placed'],
// ['key' => 2, "name" => 'In Production'],
// ['key' => 3, "name" => 'Shipped'],
// ['key' => 4, "name" => 'Inventory'],
// ['key' => 8, "name" => 'Ready for Shipment'],
// ['key' => 5, "name" => 'Completed'],
// // ['key' => 6, "name" => 'Refund Under Review'],
// ['key' => 7, "name" => 'Transaction Closed'],
// ],
// //直邮单状态
// 'order_status' => [
// ['key' => 1, "name" => 'Order Has Been Placed', 'button' => ['download_invoice', 'cancel', 'again', 'toPay']],
// ['key' => 2, "name" => 'In Production', 'button' => ['download_invoice', 'again', 'toPay']],
// ['key' => 3, "name" => 'Shipped', 'button' => ['download_invoice', 'again', 'view_logistics']],
// ['key' => 5, "name" => 'Completed', 'button' => ['download_invoice', 'again', 'view_logistics', 'delete']],
// // ['key' => 6, "name" => 'Refund Under Review', 'button' => ['again', 'delete']],
// ['key' => 7, "name" => 'Transaction Closed', 'button' => ['again', 'delete']],
// ],
// //云仓单状态
// 'Inventory_status' => [
// ['key' => 1, "name" => 'Order Has Been Placed', 'button' => ['download_invoice', 'cancel', 'again', 'toPay']],
// ['key' => 2, "name" => 'In Production', 'button' => ['download_invoice', 'again', 'toPay']],
// ['key' => 4, "name" => 'Inventory', 'button' => ['download_invoice', 'again', 'go_cloud', 'toPay']],
// ['key' => 8, "name" => 'Ready for Shipment', 'button' => ['download_invoice', 'again', 'go_cloud', 'delete']],
// // ['key' => 6, "name" => 'Refund Under Review', 'button' => ['again', 'delete']],
// ['key' => 7, "name" => 'Transaction Closed', 'button' => ['again', 'delete']],
// ],
// //订单物流状态
// 'order_logistics_status' => Order::$statusFontLogisticOrder,
// //订单物流状态
// 'Inventory_logistics_status' => Order::$statusFontLogisticInventory,
// //返回订单时间筛选项
// 'time' => [
// ['key' => 0, 'name' => 'All'],
// ['key' => 1, 'name' => 'within a month'],
// ['key' => 2, 'name' => 'within a quarter'],
// ['key' => 3, 'name' => 'Within half a year'],
// ['key' => 4, 'name' => 'Within a year'],
// ],
// //退款原因说明项
// 'refund_reason' => [
// ['key' => 1, 'name' => 'I don\'t want it anymore'],
// ['key' => 2, 'name' => 'no reason'],
// ['key' => 3, 'name' => 'other'],
// ],
// //物流状态筛选项
// 'logistics_status' => [
// ['key' => -1, "name" => 'All'],
// ['key' => 1, "name" => 'Draw', 'button' => []],
// ['key' => 2, "name" => 'Shipping', 'button' => []],
// // ['key' => Deliver::STATUS_PORT, "name" => 'To the port', 'button' => []],
// ['key' => 3, "name" => 'UPS pick up', 'button' => ['check_detail']],
// ['key' => 4, "name" => 'Arrival', 'button' => []],
// ]
// ];

View File

@@ -0,0 +1,20 @@
package svc
import (
"fusenapi/server/home-user-auth/internal/config"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type ServiceContext struct {
Config config.Config
MysqlConn sqlx.SqlConn
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
MysqlConn: sqlx.NewMysql(c.SourceMysql),
}
}

View File

@@ -0,0 +1,152 @@
// Code generated by goctl. DO NOT EDIT.
package types
import (
"fusenapi/utils/basic"
)
type Request struct {
}
type RequestBasicInfoForm struct {
FirstName string `form:"first_name,optional" db:"first_name"` // FirstName
LastName string `form:"last_name,optional" db:"last_name"` // LastName
Company string `form:"company,optional" db:"company"` // 公司名称
Mobile string `form:"mobile,optional" db:"mobile"` // 手机号码
Email string `form:"email" db:"email"` // 邮箱
Status int64 `form:"status,optional" db:"status"` // 1正常 0不正常
IsOrderStatusEmail int64 `form:"is_order_status_email,optional" db:"is_order_status_email"` // 订单状态改变时是否接收邮件
IsEmailAdvertisement int64 `form:"is_email_advertisement,optional" db:"is_email_advertisement"` // 是否接收邮件广告
IsOrderStatusPhone int64 `form:"is_order_status_phone,optional" db:"is_order_status_phone"` // 订单状态改变是是否接收电话
IsPhoneAdvertisement int64 `form:"is_phone_advertisement,optional" db:"is_phone_advertisement"` // 是否接收短信广告
IsOpenRender int64 `form:"is_open_render,optional" db:"is_open_render"` // 是否打开个性化渲染1开启0关闭
IsLowRendering int64 `form:"is_low_rendering,optional" db:"is_low_rendering"` // 是否开启低渲染模型渲染
IsRemoveBg int64 `form:"is_remove_bg,optional" db:"is_remove_bg"` // 用户上传logo是否去除背景
NewPassword string `form:"new_password,optional" db:"new_password"` // new_password 如果存在新密码
}
type RequestUserLogin struct {
Name string `form:"name"`
Password string `form:"pwd"`
}
type DataUserLogin struct {
Token string `json:"token"` // 充值密码token
JwtToken string `json:"jwt_token"` // jwt 的Token
}
type DataUserBasicInfo struct {
Id int64 `db:"id"` // ID
FaceId int64 `db:"face_id"` // facebook的userid
Sub int64 `db:"sub"` // google的sub
FirstName string `db:"first_name"` // FirstName
LastName string `db:"last_name"` // LastName
Username string `db:"username"` // 用户名
Company string `db:"company"` // 公司名称
Mobile string `db:"mobile"` // 手机号码
AuthKey string `db:"auth_key"`
PasswordHash string `db:"password_hash"`
VerificationToken string `db:"verification_token"`
PasswordResetToken string `db:"password_reset_token"`
Email string `db:"email"` // 邮箱
Type int64 `db:"type"` // 1普通餐厅 2连锁餐厅
Status int64 `db:"status"` // 1正常 0不正常
IsDel int64 `db:"is_del"` // 是否删除 1删除
CreatedAt int64 `db:"created_at"` // 添加时间
UpdatedAt int64 `db:"updated_at"` // 更新时间
IsOrderStatusEmail int64 `db:"is_order_status_email"` // 订单状态改变时是否接收邮件
IsEmailAdvertisement int64 `db:"is_email_advertisement"` // 是否接收邮件广告
IsOrderStatusPhone int64 `db:"is_order_status_phone"` // 订单状态改变是是否接收电话
IsPhoneAdvertisement int64 `db:"is_phone_advertisement"` // 是否接收短信广告
IsOpenRender int64 `db:"is_open_render"` // 是否打开个性化渲染1开启0关闭
IsThousandFace int64 `db:"is_thousand_face"` // 是否已经存在千人千面1存在0不存在
IsLowRendering int64 `db:"is_low_rendering"` // 是否开启低渲染模型渲染
IsRemoveBg int64 `db:"is_remove_bg"` // 用户上传logo是否去除背景
}
type DataGetType struct {
Id int64 `db:"id" json:"key"` // ID
Name string `db:"name" json:"name"` // 餐厅名字
}
type KeyName struct {
Key string `json:"key"`
Name string `json:"name"`
}
type KeyNameButton struct {
Key string `json:"key"`
Name string `json:"name"`
Button []string `json:"button"`
}
type DataStatusConfig struct {
SearchList []KeyName `json:"search_list"` //搜索下拉列表
OrderStatus []KeyNameButton `json:"order_status"` //直邮单状态
InventoryStatus []KeyNameButton `json:"Inventory_status"` //云仓单状态
OrderLogisticsStatus []KeyName `json:"order_logistics_status"` //订单物流状态
InventoryLogisticsStatus []KeyName `json:"Inventory_logistics_status"` //订单物流状态
Time []KeyName `json:"time"` //返回订单时间筛选项
RefundReason []KeyName `json:"refund_reason"` //退款原因说明项
LogisticsStatus []KeyName `json:"logistics_status"` //物流状态筛选项
}
type Response struct {
Code int `json:"code"`
Message string `json:"msg"`
Data interface{} `json:"data"`
}
type ResponseJwt struct {
Code int `json:"code"`
Message string `json:"msg"`
Data interface{} `json:"data"`
AccessSecret string `json:"accessSecret"`
AccessExpire int64 `json:"accessExpire"`
}
type Auth struct {
AccessSecret string `json:"accessSecret"`
AccessExpire int64 `json:"accessExpire"`
RefreshAfter int64 `json:"refreshAfter"`
}
// Set 设置Response的Code和Message值
func (resp *Response) Set(Code int, Message string) *Response {
return &Response{
Code: Code,
Message: Message,
}
}
// Set 设置整个Response
func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response {
return &Response{
Code: Code,
Message: Message,
Data: Data,
}
}
// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数
func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response {
newResp := &Response{
Code: sr.Code,
}
if len(data) == 1 {
newResp.Data = data[0]
}
return newResp
}
// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数
func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response {
newResp := &Response{
Code: sr.Code,
Message: msg,
}
if len(data) == 1 {
newResp.Data = data[0]
}
return newResp
}

View File

@@ -0,0 +1,8 @@
Name: product
Host: 0.0.0.0
Port: 8889
DataSource: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest
Auth:
AccessSecret: fusen2023
AccessExpire: 60
RefreshAfter: 60

View File

@@ -0,0 +1,12 @@
package config
import (
"fusenapi/product/internal/types"
"github.com/zeromicro/go-zero/rest"
)
type Config struct {
rest.RestConf
DataSource string
Auth types.Auth
}

View File

@@ -0,0 +1,37 @@
package handler
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/product/internal/logic"
"fusenapi/product/internal/svc"
"fusenapi/product/internal/types"
)
func GetProductListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.GetProductListReq
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &types.Response{
Code: 510,
Message: err.Error(),
})
logx.Info(err)
return
}
l := logic.NewGetProductListLogic(r.Context(), svcCtx)
resp := l.GetProductList(&req)
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,26 @@
package handler
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/product/internal/logic"
"fusenapi/product/internal/svc"
)
func GetSizeByProductHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := logic.NewGetSizeByProductLogic(r.Context(), svcCtx)
resp := l.GetSizeByProduct()
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,37 @@
package handler
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/product/internal/logic"
"fusenapi/product/internal/svc"
"fusenapi/product/internal/types"
)
func GetSuccessRecommandHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.GetSuccessRecommandReq
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &types.Response{
Code: 510,
Message: err.Error(),
})
logx.Info(err)
return
}
l := logic.NewGetSuccessRecommandLogic(r.Context(), svcCtx)
resp := l.GetSuccessRecommand(&req)
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,38 @@
// Code generated by goctl. DO NOT EDIT.
package handler
import (
"net/http"
"fusenapi/product/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodGet,
Path: "/product/list",
Handler: GetProductListHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/product/success-recommand",
Handler: GetSuccessRecommandHandler(serverCtx),
},
},
rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
)
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodGet,
Path: "/product/get-size-by-product",
Handler: GetSizeByProductHandler(serverCtx),
},
},
)
}

View File

@@ -0,0 +1,174 @@
package logic
import (
"context"
"encoding/json"
"errors"
"fmt"
"fusenapi/constants"
"fusenapi/model"
"fusenapi/product/internal/svc"
"fusenapi/product/internal/types"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/format"
"fusenapi/utils/image"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"sort"
"strings"
)
type GetProductListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetProductListLogic {
return &GetProductListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 获取产品列表
func (l *GetProductListLogic) GetProductList(req *types.GetProductListReq) (resp *types.Response) {
resp = &types.Response{}
loginInfo := auth.GetUserInfoFormCtx(l.ctx)
if loginInfo.UserId == 0 {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "get login user info err")
}
//如果是demo
if req.IsDemo == 1 {
var demo types.GetProductListRsp
if err := json.Unmarshal([]byte(constants.PRODUCT_LIST_DEMO), &demo); err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "demo data format err")
}
return resp.SetStatusWithMessage(basic.CodeOK, "success", demo)
}
if req.Page <= 0 {
req.Page = 1
}
//获取合适尺寸
if req.Size > 0 {
req.Size = image.GetCurrentSize(req.Size)
}
//查询用户信息
userModel := model.NewFsUserModel(l.svcCtx.MysqlConn)
userInfo, err := userModel.FindOne(l.ctx, loginInfo.UserId)
if err != nil && !errors.Is(err, sqlc.ErrNotFound) {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "get user info err")
}
if userInfo == nil {
return resp.SetStatusWithMessage(basic.CodeUnAuth, "user not exists")
}
//查询符合的产品列表
productModel := model.NewFsProductModel(l.svcCtx.MysqlConn)
productList, err := productModel.GetProductListByConditions(l.ctx, []string{fmt.Sprintf("%d", req.Cid)}, "sort-desc")
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product list")
}
productLen := len(productList)
if productLen == 0 {
return resp.SetStatusWithMessage(basic.CodeOK, "success")
}
//提取产品ids
productIds := make([]string, 0, productLen)
for _, v := range productList {
productIds = append(productIds, fmt.Sprintf("%d", v.Id))
}
productPriceModel := model.NewFsProductPriceModel(l.svcCtx.MysqlConn)
productPriceList, err := productPriceModel.GetPriceListByProductIds(l.ctx, productIds)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product min price list")
}
//存储产品最小价格
mapProductMinPrice := make(map[int64]int64)
for _, v := range productPriceList {
priceStrSlic := strings.Split(v.Price, ",")
priceSlice, err := format.StrSlicToIntSlice(priceStrSlic)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, err.Error())
}
if len(priceSlice) == 0 {
continue
}
sort.Ints(priceSlice)
mapProductMinPrice[v.ProductId] = int64(priceSlice[0])
}
//获取模板
productTemplateModel := model.NewFsProductTemplateV2Model(l.svcCtx.MysqlConn)
productTemplatesV2, err := productTemplateModel.FindAllByCondition(l.ctx, productIds)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "get product template_v2 err")
}
mapProductTemplate := make(map[int64]struct{})
for _, v := range productTemplatesV2 {
mapProductTemplate[v.ProductId] = struct{}{}
}
//获取分类
tagsModel := model.NewFsTagsModel(l.svcCtx.MysqlConn)
tagInfo, err := tagsModel.FindOne(l.ctx, req.Cid)
if err != nil && !errors.Is(err, sqlc.ErrNotFound) {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "get tag err")
}
if tagInfo == nil {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "tag is not exists")
}
//获取产品尺寸数量
productSizeModel := model.NewFsProductSizeModel(l.svcCtx.MysqlConn)
productSizeCount, err := productSizeModel.CountByStatus(l.ctx, 1)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "get product size count err")
}
//拼接返回
itemList := make([]types.Items, 0, productLen)
for _, v := range productList {
minPrice, ok := mapProductMinPrice[v.Id]
_, tmpOk := mapProductTemplate[v.Id]
//无最小价格则不显示 || 没有模板也不显示
if !ok || !tmpOk {
continue
}
item := types.Items{
Id: v.Id,
Sn: v.Sn,
Title: v.Title,
Intro: v.Intro.String,
IsEnv: v.IsProtection,
IsMicro: v.IsMicrowave,
SizeNum: uint32(productSizeCount),
MiniPrice: format.CentoDollar(minPrice),
}
//千人千面处理
thousandFaceImageFormatReq := image.ThousandFaceImageFormatReq{
Size: int(req.Size),
IsThousandFace: int(userInfo.IsThousandFace),
Cover: v.Cover,
CoverImg: v.CoverImg,
CoverDefault: v.CoverImg,
ProductId: v.Id,
UserInfo: *userInfo,
}
image.ThousandFaceImageFormat(&thousandFaceImageFormatReq)
item.Cover = thousandFaceImageFormatReq.Cover
item.CoverImg = thousandFaceImageFormatReq.CoverImg
item.CoverDefault = thousandFaceImageFormatReq.CoverDefault
itemList = append(itemList, item)
}
return resp.SetStatusWithMessage(basic.CodeOK, "success", types.GetProductListRsp{
Ob: types.Ob{
Items: itemList,
}, TypeName: tagInfo.Title, Description: tagInfo.Description,
})
}

View File

@@ -0,0 +1,193 @@
package logic
import (
"context"
"errors"
"fmt"
"fusenapi/constants"
"fusenapi/model"
"fusenapi/utils/basic"
"fusenapi/utils/format"
"strings"
"fusenapi/product/internal/svc"
"fusenapi/product/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetSizeByProductLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetSizeByProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSizeByProductLogic {
return &GetSizeByProductLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 获取分类下的产品以及尺寸
func (l *GetSizeByProductLogic) GetSizeByProduct() (resp *types.Response) {
//获取所有网站目录
tagsModel := model.NewFsTagsModel(l.svcCtx.MysqlConn)
tagsList, err := tagsModel.ListAllByLevelStatus(l.ctx, constants.TYPE_WEBSITE, 1)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get website tags")
}
if len(tagsList) == 0 {
return resp.SetStatusWithMessage(basic.CodeOK, "tag list is null")
}
tagIds := make([]string, 0, len(tagsList))
for _, v := range tagsList {
tagIds = append(tagIds, fmt.Sprintf("%d", v.Id))
}
//获取这些类型的产品
productModel := model.NewFsProductModel(l.svcCtx.MysqlConn)
productList, err := productModel.GetProductListByConditions(l.ctx, tagIds, "sort-desc")
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get tag product list")
}
productIds := make([]string, 0, len(productList))
for _, v := range productList {
productIds = append(productIds, fmt.Sprintf("%d", v.Id))
}
productSizeModel := model.NewFsProductSizeModel(l.svcCtx.MysqlConn)
productSizeList, err := productSizeModel.FindAllByProductIds(l.ctx, productIds, 2)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product size list")
}
sizeIds := make([]string, 0, len(productSizeList))
for _, v := range productSizeList {
sizeIds = append(sizeIds, fmt.Sprintf("%d", v.Id))
}
//获取价格列表
productPriceModel := model.NewFsProductPriceModel(l.svcCtx.MysqlConn)
productPriceList, err := productPriceModel.GetPriceListBySizeIds(l.ctx, sizeIds)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product proce list")
}
mapProductPrice := make(map[int64]model.FsProductPrice)
for _, v := range productPriceList {
mapProductPrice[v.SizeId] = v
}
//组装返回
list := make([]types.GetSizeByProductRsp, 0, len(tagsList))
for _, tag := range tagsList {
//获取第一层子类
firstChildrenList, err := l.GetFirstChildrenList(tag, productList, productSizeList, mapProductPrice)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get first level children list")
}
data := types.GetSizeByProductRsp{
Id: tag.Id,
Name: tag.Title,
Children: firstChildrenList,
}
list = append(list, data)
}
return resp.SetStatusWithMessage(basic.CodeOK, "success", list)
}
// 第一层子层
func (l *GetSizeByProductLogic) GetFirstChildrenList(tag model.FsTags, productList []model.FsProduct, productSizeList []model.FsProductSize, mapProductPrice map[int64]model.FsProductPrice) (childrenList []types.Children, err error) {
childrenList = make([]types.Children, 0, len(productList))
for _, product := range productList {
if product.Type != tag.Id {
continue
}
childrenObjList, err := l.GetSecondChildrenList(tag, product, productSizeList, mapProductPrice)
if err != nil {
return nil, err
}
//获取第二层子类
data := types.Children{
Id: product.Id,
Name: product.Title,
Cycle: int(product.DeliveryDays + product.ProduceDays),
ChildrenList: childrenObjList,
}
childrenList = append(childrenList, data)
}
return
}
// 第2层子层
func (l *GetSizeByProductLogic) GetSecondChildrenList(tag model.FsTags, product model.FsProduct, productSizeList []model.FsProductSize, mapProductPrice map[int64]model.FsProductPrice) (childrenObjList []types.ChildrenObj, err error) {
childrenObjList = make([]types.ChildrenObj, 0, len(productSizeList))
for _, productSize := range productSizeList {
if product.Id != productSize.ProductId {
continue
}
priceList := make([]types.PriceObj, 0, len(productSizeList))
price, ok := mapProductPrice[productSize.Id]
//无对应尺寸价格
if !ok {
childrenObjList = append(childrenObjList, types.ChildrenObj{
Id: productSize.Id,
Name: productSize.Capacity,
PriceList: []types.PriceObj{
{Num: 1, Price: 0},
{Num: 1, Price: 0},
{Num: 1, Price: 0},
},
})
continue
}
price.StepNum = strings.Trim(price.StepNum, " ")
price.StepPrice = strings.Trim(price.StepPrice, " ")
if price.StepNum == "" || price.StepPrice == "" {
continue
}
//阶梯数量切片
stepNum, err := format.StrSlicToIntSlice(strings.Split(price.StepNum, ","))
if err != nil {
return nil, err
}
//阶梯价格切片
stepPrice, err := format.StrSlicToIntSlice(strings.Split(price.StepPrice, ","))
if err != nil {
return nil, err
}
if len(stepNum) > len(stepPrice) {
return nil, errors.New(fmt.Sprintf("stepNum count not eq stepPrice count: product size id :%d ,product price id :%d", productSize.Id, price.Id))
}
for i := 0; i < 3; i++ {
// 最小购买数量小于 最大阶梯数量+5
if int(price.MinBuyNum) < (stepNum[len(stepNum)-1] + 5) {
priceList = append(priceList, types.PriceObj{
Num: int(price.MinBuyNum * price.EachBoxNum),
Price: l.GetPrice(int(price.MinBuyNum), stepNum, stepPrice),
})
}
price.MinBuyNum++
}
//如果不够三个则追加伪数据
for len(priceList) < 3 {
priceList = append(priceList, types.PriceObj{Num: 1, Price: 0})
}
data := types.ChildrenObj{
Id: productSize.Id,
Name: productSize.Capacity,
PriceList: priceList,
}
childrenObjList = append(childrenObjList, data)
}
return
}
func (l *GetSizeByProductLogic) GetPrice(minBuyNum int, stepNum []int, stepPrice []int) float64 {
for k, v := range stepNum {
if minBuyNum <= v {
return float64(stepPrice[k]) / float64(100)
}
}
return float64(stepPrice[len(stepPrice)-1]) / float64(100)
}

View File

@@ -0,0 +1,89 @@
package logic
import (
"context"
"errors"
"fusenapi/model"
"fusenapi/product/internal/svc"
"fusenapi/product/internal/types"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/image"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type GetSuccessRecommandLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetSuccessRecommandLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSuccessRecommandLogic {
return &GetSuccessRecommandLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 获取推荐的产品列表
func (l *GetSuccessRecommandLogic) GetSuccessRecommand(req *types.GetSuccessRecommandReq) (resp *types.Response) {
resp = &types.Response{}
loginInfo := auth.GetUserInfoFormCtx(l.ctx)
if loginInfo.UserId == 0 {
return resp.SetStatusWithMessage(basic.CodeUnAuth, "get login user info err")
}
//获取用户信息
userModel := model.NewFsUserModel(l.svcCtx.MysqlConn)
userInfo, err := userModel.FindOne(l.ctx, loginInfo.UserId)
if err != nil && errors.Is(err, sqlx.ErrNotFound) {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get user info")
}
if userInfo == nil {
return resp.SetStatusWithMessage(basic.CodeUnAuth, "failed to get user info")
}
if req.Num == 0 || req.Num > 500 {
req.Num = 8
}
if req.Size > 0 {
req.Size = image.GetCurrentSize(req.Size)
}
//随机取8个产品
productModel := model.NewFsProductModel(l.svcCtx.MysqlConn)
productList, err := productModel.GetRandomProductList(l.ctx, int(req.Num))
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product list")
}
//没有推荐产品就返回
if len(productList) == 0 {
return resp.SetStatusWithMessage(basic.CodeOK, "success")
}
list := make([]types.GetSuccessRecommandRsp, 0, len(productList))
for _, v := range productList {
data := types.GetSuccessRecommandRsp{
Title: v.Title,
Sn: v.Sn,
Id: v.Id,
SkuId: 0, //???????
}
//千人千面处理
thousandFaceImageFormatReq := image.ThousandFaceImageFormatReq{
Size: int(req.Size),
IsThousandFace: int(userInfo.IsThousandFace),
Cover: v.Cover,
CoverImg: v.CoverImg,
CoverDefault: v.CoverImg,
ProductId: v.Id,
UserInfo: *userInfo,
}
image.ThousandFaceImageFormat(&thousandFaceImageFormatReq)
data.Cover = thousandFaceImageFormatReq.Cover
data.CoverImg = thousandFaceImageFormatReq.CoverImg
data.CoverDefault = thousandFaceImageFormatReq.CoverDefault
list = append(list, data)
}
return resp.SetStatusWithMessage(basic.CodeOK, "success", list)
}

View File

@@ -0,0 +1,18 @@
package svc
import (
"fusenapi/product/internal/config"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type ServiceContext struct {
Config config.Config
MysqlConn sqlx.SqlConn
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
MysqlConn: sqlx.NewMysql(c.DataSource),
}
}

View File

@@ -0,0 +1,157 @@
// Code generated by goctl. DO NOT EDIT.
package types
import (
"fusenapi/utils/basic"
)
type GetProductListReq struct {
Cid int64 `form:"cid"`
Size uint32 `form:"size"`
Page uint32 `form:"page"`
IsDemo uint32 `form:"is_demo" , options=0|1"`
}
type GetProductListRsp struct {
Ob Ob `json:"ob"`
TypeName string `json:"typeName"`
Description string `json:"description"`
}
type Ob struct {
Items []Items `json:"items"`
Links Links `json:"_links"`
Meta Meta `json:"_meta"`
}
type Meta struct {
TotalCount int32 `json:"totalCount"`
PageCount int32 `json:"pageCount"`
CurrentPage int32 `json:"currentPage"`
PerPage int32 `json:"perPage"`
}
type Links struct {
Self HrefUrl `json:"self"`
First HrefUrl `json:"first"`
Last HrefUrl `json:"last"`
Next HrefUrl `json:"next"`
}
type HrefUrl struct {
Href string `json:"href"`
}
type Items struct {
Id int64 `json:"id"`
Sn string `json:"sn"`
Title string `json:"title"`
Cover string `json:"cover"`
Intro string `json:"intro"`
CoverImg string `json:"cover_img"`
IsEnv int64 `json:"isEnv"`
IsMicro int64 `json:"isMicro"`
SizeNum uint32 `json:"sizeNum"`
MiniPrice float64 `json:"miniPrice"`
CoverDefault string `json:"coverDefault"`
}
type GetSuccessRecommandReq struct {
Num uint32 `form:"num"`
Size uint32 `form:"size"`
Sn string `form:"sn"`
}
type GetSuccessRecommandRsp struct {
Title string `json:"title"`
Cover string `json:"cover"`
CoverImg string `json:"coverImg"`
Sn string `json:"sn"`
Id int64 `json:"id"`
SkuId int64 `json:"skuId"`
CoverDefault string `json:"coverDefault"`
}
type GetSizeByProductRsp struct {
Id int64 `json:"id"`
Name string `json:"name"`
Children []Children `json:"children"`
}
type Children struct {
Id int64 `json:"id"`
Name string `json:"name"`
Cycle int `json:"cycle"`
ChildrenList []ChildrenObj `json:"children"`
}
type ChildrenObj struct {
Id int64 `json:"id"`
Name string `json:"name"`
PriceList []PriceObj `json:"price_list"`
}
type PriceObj struct {
Num int `json:"num"`
Price float64 `json:"price"`
}
type Response struct {
Code int `json:"code"`
Message string `json:"msg"`
Data interface{} `json:"data"`
}
type ResponseJwt struct {
Code int `json:"code"`
Message string `json:"msg"`
Data interface{} `json:"data"`
AccessSecret string `json:"accessSecret"`
AccessExpire int64 `json:"accessExpire"`
}
type Auth struct {
AccessSecret string `json:"accessSecret"`
AccessExpire int64 `json:"accessExpire"`
RefreshAfter int64 `json:"refreshAfter"`
}
// Set 设置Response的Code和Message值
func (resp *Response) Set(Code int, Message string) *Response {
return &Response{
Code: Code,
Message: Message,
}
}
// Set 设置整个Response
func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response {
return &Response{
Code: Code,
Message: Message,
Data: Data,
}
}
// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数
func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response {
newResp := &Response{
Code: sr.Code,
}
if len(data) == 1 {
newResp.Data = data[0]
}
return newResp
}
// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数
func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response {
newResp := &Response{
Code: sr.Code,
Message: msg,
}
if len(data) == 1 {
newResp.Data = data[0]
}
return newResp
}

30
server/product/product.go Normal file
View File

@@ -0,0 +1,30 @@
package main
import (
"flag"
"fmt"
"fusenapi/product/internal/config"
"fusenapi/product/internal/handler"
"fusenapi/product/internal/svc"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
var configFile = flag.String("f", "etc/product.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
server := rest.MustNewServer(c.RestConf)
defer server.Stop()
ctx := svc.NewServiceContext(c)
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
}

View File

@@ -0,0 +1,7 @@
package main
import "testing"
func TestMain(t *testing.T) {
main()
}