This commit is contained in:
laodaming 2023-07-26 11:02:30 +08:00
parent c378c6d8da
commit c7536d0fdb
12 changed files with 349 additions and 1 deletions

View File

@ -1,6 +1,6 @@
#! /bin/bash
name=${1%%\\*}
options=("backend" "product-template" "product-model")
options=("backend" "product-template" "product-template-tag" "product-model")
for option in "${options[@]}"; do
if [ "$name" = "$option" ]; then
echo $name

View File

@ -8,6 +8,7 @@ import (
type FsProductTemplateTags struct {
Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // ID
Title *string `gorm:"default:'';" json:"title"` // 标题
CoverImg *string `gorm:"default:'';" json:"cover_img"` // 封面图
Status *int64 `gorm:"default:0;" json:"status"` // 状态 1可用
CreateAt *int64 `gorm:"default:0;" json:"create_at"` // 创建时间
}

View File

@ -23,3 +23,12 @@ func (pt *FsProductTemplateTagsModel) FindOne(ctx context.Context, id int64, fie
err = db.Take(&resp).Error
return resp, err
}
func (pt *FsProductTemplateTagsModel) GetList(ctx context.Context, page, limit int, orderBy string) (resp []FsProductTemplateTags, err error) {
db := pt.db.WithContext(ctx).Model(&FsProductTemplateTags{}).Where("`status` = ?", 1)
if orderBy != "" {
db = db.Order(orderBy)
}
offset := (page - 1) * limit
err = db.Offset(offset).Limit(limit).Find(&resp).Error
return resp, err
}

View File

@ -0,0 +1,8 @@
Name: product-template-tag
Host: 0.0.0.0
Port: 9916
SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest
Auth:
AccessSecret: fusen2023
AccessExpire: 2592000
RefreshAfter: 1592000

View File

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

View File

@ -0,0 +1,35 @@
package handler
import (
"net/http"
"reflect"
"fusenapi/utils/basic"
"fusenapi/server/product-template-tag/internal/logic"
"fusenapi/server/product-template-tag/internal/svc"
"fusenapi/server/product-template-tag/internal/types"
)
func GetProductTemplateTagsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.GetProductTemplateTagsReq
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
if err != nil {
return
}
// 创建一个业务逻辑层实例
l := logic.NewGetProductTemplateTagsLogic(r.Context(), svcCtx)
rl := reflect.ValueOf(l)
basic.BeforeLogic(w, r, rl)
resp := l.GetProductTemplateTags(&req, userinfo)
if !basic.AfterLogic(w, r, rl, resp) {
basic.NormalAfterLogic(w, r, resp)
}
}
}

View File

@ -0,0 +1,22 @@
// Code generated by goctl. DO NOT EDIT.
package handler
import (
"net/http"
"fusenapi/server/product-template-tag/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodGet,
Path: "/api/product-template/get_product_template_tags",
Handler: GetProductTemplateTagsHandler(serverCtx),
},
},
)
}

View File

@ -0,0 +1,55 @@
package logic
import (
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"context"
"fusenapi/server/product-template-tag/internal/svc"
"fusenapi/server/product-template-tag/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetProductTemplateTagsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetProductTemplateTagsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetProductTemplateTagsLogic {
return &GetProductTemplateTagsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 处理进入前逻辑w,r
// func (l *GetProductTemplateTagsLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *GetProductTemplateTagsLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }
func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProductTemplateTagsReq, userinfo *auth.UserInfo) (resp *basic.Response) {
if req.Limit <= 0 || req.Limit > 100 {
req.Limit = 4
}
productTemplateTags, err := l.svcCtx.AllModels.FsProductTemplateTags.GetList(l.ctx, 1, req.Limit, "`id` DESC")
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template tags")
}
list := make([]types.GetProductTemplateTagsRsp, 0, len(productTemplateTags))
for _, v := range productTemplateTags {
list = append(list, types.GetProductTemplateTagsRsp{
Tag: *v.Title,
Cover: *v.CoverImg,
})
}
return resp.SetStatusWithMessage(basic.CodeOK, "success", list)
}

View File

@ -0,0 +1,61 @@
package svc
import (
"errors"
"fmt"
"fusenapi/server/product-template-tag/internal/config"
"net/http"
"fusenapi/initalize"
"fusenapi/model/gmodel"
"github.com/golang-jwt/jwt"
"gorm.io/gorm"
)
type ServiceContext struct {
Config config.Config
MysqlConn *gorm.DB
AllModels *gmodel.AllModelsGen
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
MysqlConn: initalize.InitMysql(c.SourceMysql),
AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)),
}
}
func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
AuthKey := r.Header.Get("Authorization")
if AuthKey == "" {
return nil, nil
}
AuthKey = AuthKey[7:]
if len(AuthKey) <= 50 {
return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey)))
}
token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) {
// 检查签名方法是否为 HS256
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// 返回用于验证签名的密钥
return []byte(svcCtx.Config.Auth.AccessSecret), nil
})
if err != nil {
return nil, errors.New(fmt.Sprint("Error parsing token:", err))
}
// 验证成功返回
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New(fmt.Sprint("Invalid token", err))
}

View File

@ -0,0 +1,84 @@
// Code generated by goctl. DO NOT EDIT.
package types
import (
"fusenapi/utils/basic"
)
type GetProductTemplateTagsReq struct {
Limit int `form:"limit"`
}
type GetProductTemplateTagsRsp struct {
Tag string `json:"tag"`
Cover string `json:"cover"`
}
type Request struct {
}
type Response struct {
Code int `json:"code"`
Message string `json:"msg"`
Data interface{} `json:"data"`
}
type Auth struct {
AccessSecret string `json:"accessSecret"`
AccessExpire int64 `json:"accessExpire"`
RefreshAfter int64 `json:"refreshAfter"`
}
type File struct {
Filename string `fsfile:"filename"`
Header map[string][]string `fsfile:"header"`
Size int64 `fsfile:"size"`
Data []byte `fsfile:"data"`
}
type Meta struct {
TotalCount int64 `json:"totalCount"`
PageCount int64 `json:"pageCount"`
CurrentPage int `json:"currentPage"`
PerPage int `json:"perPage"`
}
// 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,36 @@
package main
import (
"flag"
"fmt"
"net/http"
"time"
"fusenapi/utils/auth"
"fusenapi/server/product-template-tag/internal/config"
"fusenapi/server/product-template-tag/internal/handler"
"fusenapi/server/product-template-tag/internal/svc"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
var configFile = flag.String("f", "etc/product-template-tag.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
c.Timeout = int64(time.Second * 15)
server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) {
}))
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,25 @@
syntax = "v1"
info (
title: "产品模板标签服务"// TODO: add title
desc: // TODO: add description
author: ""
email: ""
)
import "basic.api"
service product-template-tag {
//获取产品模板标签列表
@handler GetProductTemplateTagsHandler
get /api/product-template/get_product_template_tags(GetProductTemplateTagsReq) returns (response);
}
//获取产品模板标签列表
type GetProductTemplateTagsReq {
Limit int `form:"limit"`
}
type GetProductTemplateTagsRsp {
Tag string `json:"tag"`
Cover string `json:"cover"`
}