后端代码一

代码图片:

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"net/http"
	"shop/contronller"
	"shop/tool"
	"strings"
)

func main() {

	cfg, err := tool.ParseConfig("./config/app.json")
	tool.GenConfig()
	if err != nil {
		panic(err.Error())
	}
	_, err = tool.OrmEngine(cfg)
	if err != nil {

		return
	}

	tool.InitRedisStore()
	app := gin.Default()

	registerRouter(app)
	app.Use(Cors())
	//设置全局跨域访问

	app.Run(cfg.AppHost + ":" + cfg.AppPort)
}

//路由设置
func registerRouter(router *gin.Engine) {
	new(contronller.HelloController).Router(router)
	new(contronller.MemberController).Router(router)

}

//跨域访问 :cross origin resource share
func Cors() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method
		origin := context.Request.Header.Get("Origin")
		var headerKeys []string
		for k, _ := range context.Request.Header {
			headerKeys = append(headerKeys, k)
		}
		headerStr := strings.Join(headerKeys, ",")
		if headerStr != "" {
			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}

		if origin != "" {
			context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
			context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
			context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
			context.Header("Access-Control-Max-Age", "172800")
			context.Header("Access-Control-Allow-Credentials", "false")
			context.Set("content-type", "application/json")  设置返回格式是json
		}

		if method == "OPTIONS" {
			context.JSON(http.StatusOK, "Options Request!")
		}
		//处理请求
		context.Next()
	}
}

package service

import (
	"shop/dao"
	"shop/model"
	"shop/param"
	"shop/tool"
)

type MemberService struct {
}

//用户名+密码登录
func (ms *MemberService) Login(loginparam param.UserLogin) *model.Member {
	//获取到用户名+密码
	//验证用户名+密码是否正确
	md := dao.MemberDao{tool.DbEngine}

	is := md.QueryUserAndPassword(loginparam.UserName, loginparam.Password)
	if is.Id != 0 {
		return is
	}
	return nil
}

//保存文件
func (ms *MemberService) UploadAvatar(useId int64, fileName string) string {
	memberdao := dao.MemberDao{tool.DbEngine}
	result := memberdao.UpdataMemberAvatar(useId, fileName)
	if result == 0 {
		return ""
	}
	return fileName
}

package dao

import (
	"fmt"
	"shop/model"
	"shop/tool"
)

type MemberDao struct {
	*tool.Orm
}

func (md *MemberDao) UpdataMemberAvatar(useId int64, fileName string) int64 {
	member := model.Member{Avatar: fileName}

	result, err := md.Where("id = ?", useId).Update(&member)
	if err != nil {
		fmt.Println(err.Error())
		return 0
	}
	return result
}

//通过用户名和密码查询
func (md *MemberDao) QueryUserAndPassword(username string, password string) *model.Member {
	var member model.Member
	//password = tool.EncodeSha256(password)
	_, err := md.Where("user_name =? and password = ? ", username, password).Get(&member)
	if err != nil {
		fmt.Println(err)

	}
	return &member
}

package contronller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"shop/model"
	"shop/param"
	"shop/service"
	"shop/tool"
	"strconv"
	"time"
)

type MemberController struct {
}

//完成用户名+密码的登录
func (mc *MemberController) Router(engine *gin.Engine) {
	engine.POST("api/login", mc.userLogin)
	engine.POST("api/upload/wz", mc.uploadtp)
}

//用户名+密码登录方法
func (mc *MemberController) userLogin(context *gin.Context) {
	var userLogin param.UserLogin
	err := tool.Decode(context.Request.Body, &userLogin)
	if err != nil {
		tool.Failed(context, "参数解析失败")
		return
	}
	//完成登录(用户名+密码)
	ms := service.MemberService{}
	member := ms.Login(userLogin)
	if member != nil {
		sess, _ := json.Marshal(member)
		err := tool.SetSess(context, "user"+string(member.Id), sess)
		if err != nil {
			tool.Failed(context, "登录失败")
		}
		tool.Success(context, member)
		return
	}
	tool.Failed(context, "登录失败")
}

//文件上传
func (mc *MemberController) uploadtp(context *gin.Context) {
	//解析上传的参数
	userId := context.PostForm("user_id")
	fmt.Println(userId)
	file, err := context.FormFile("avatar")
	if err != nil {
		tool.Failed(context, "参数解析失败")
		return
	}
	//判断用户是否登录
	sess := tool.GetSess(context, "user_"+userId)
	if sess == nil {
		tool.Failed(context, "参数不合法")
		return
	}
	var member model.Member
	json.Unmarshal(sess.([]byte), &member)
	//将文件保存
	fileName := "./uploadfile/" + strconv.FormatInt(time.Now().Unix(), 10) + file.Filename
	err = context.SaveUploadedFile(file, fileName)
	if err != nil {
		tool.Failed(context, "保存文件失败")
	}
	//将文件保存到数据库
	memberService := service.MemberService{}
	path := memberService.UploadAvatar(member.Id, fileName[1:])
	if path != "" {
		tool.Success(context, "http://localhost:8090"+path)
		return
	}
}

结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值