其他分享
首页 > 其他分享> > Golang实战项目-B2C电商平台(2)

Golang实战项目-B2C电商平台(2)

作者:互联网

Golang实战项目-B2C电商平台(2)

实现登录功能

src/user下创建TbUser.go 实体

package user

//对应数据库中用户表
type TbUser struct {
	//属性首字母大写:1. 要转换为json   2. 可能出现跨包访问
	Id int64
	Username string
	Password string
	Phone string
	Email string
	Created string
	Updated string
}

package user

//对应数据库中用户表
type TbUser struct {
	//属性首字母大写:1. 要转换为json   2. 可能出现跨包访问
	Id int64
	Username string
	Password string
	Phone string
	Email string
	Created string
	Updated string
}

//根据用户名和密码查询,如果返回值为nil表示查询失败,否则成功
func SelByUnPwdDao(un, pwd string) *TbUser{
	sql := "select * from tb_user where username=? and password=? or email=? and password=? or phone=? and password=?"
	rows,err:=commons.Dql(sql, un, pwd, un, pwd, un, pwd)
	if err!=nil{
		fmt.Println(err)
		return nil
	}
	if rows.Next(){
		user:=new(TbUser)
		rows.Scan(&user.Id,&user.Username,&user.Password,&user.Phone,&user.Email,&user.Created,&user.Updated)
		commons.CloseConn()
		return user
	}
	return nil
}

func LoginService(un,pwd string) (er commons.EgoResult){
	u:=SelByUnPwdDao(un,pwd)
	if u!=nil{
		er.Status=200
	}else{
		er.Status=400
	}
	return
}
//所有user模块的handler
func UserHandler() {
	http.HandleFunc("/login", loginController)
}

//登录
func loginController(w http.ResponseWriter, r *http.Request) {
	username := r.FormValue("username")
	password := r.FormValue("password")
	er := LoginService(username, password)
	//把结构体转换为json数据
	b, _ := json.Marshal(er)
	//设置响应内容为json
	w.Header().Set("Content-Type", "application/json;charset=utf-8")
	w.Write(b)
}
func main() {
	s := http.Server{Addr: ":80"}
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	http.HandleFunc("/", welcome)
	//用户相关
	user.UserHandler()
	s.ListenAndServe()
}

标签:Status,password,http,string,Golang,json,user,电商,B2C
来源: https://blog.csdn.net/weixin_54147055/article/details/119281601