91 lines
2.0 KiB
Go
91 lines
2.0 KiB
Go
package user
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
type Userloginstruct struct {
|
|
Email string `json:"email"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
type Loginresponse struct {
|
|
Success string `json:"success"`
|
|
Message string `json:"message"`
|
|
Token string `json:"token"`
|
|
}
|
|
|
|
func Userlogin(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:5173")
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
|
|
if r.Method == "OPTIONS" {
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
|
|
body, error := io.ReadAll(r.Body)
|
|
if error != nil {
|
|
fmt.Println("数据读取失败")
|
|
return
|
|
}
|
|
fmt.Println(string(body))
|
|
var userinfo Userloginstruct
|
|
error = json.Unmarshal(body, &userinfo)
|
|
if error != nil {
|
|
fmt.Println("数据解析失败")
|
|
return
|
|
}
|
|
|
|
mongocli := options.Client().ApplyURI("mongodb://localhost:27017")
|
|
|
|
mongoclient, error := mongo.Connect(context.TODO(), mongocli)
|
|
if error != nil {
|
|
fmt.Println("数据库连接失败")
|
|
}
|
|
|
|
finduser := mongoclient.Database("user").Collection("userlist")
|
|
|
|
filter := bson.M{"email": userinfo.Email, "password": userinfo.Password}
|
|
|
|
type theuser struct {
|
|
Email string `json:"email"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
var oneuser theuser
|
|
|
|
error = finduser.FindOne(context.Background(), filter).Decode(&oneuser)
|
|
if error != nil {
|
|
fmt.Println("未找到该用户")
|
|
loginres := Loginresponse{
|
|
Success: "no",
|
|
Message: "登录失败",
|
|
Token: "0",
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(loginres)
|
|
return
|
|
} else {
|
|
loginres := Loginresponse{
|
|
Success: "yes",
|
|
Message: "登录成功",
|
|
Token: "1",
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(loginres)
|
|
return
|
|
}
|
|
|
|
}
|