• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

编写关系系统大概操作

武飞扬头像
醉一杯思念
帮助1

编写一个关系系统来管理用户之间的关注关系、好友关系等社交关系,可以通过以下步骤进行实现:

1. 数据库设计:

  • 设计用户表(User):包含用户ID、用户名、密码等字段。
  • 设计关注关系表(Follow):包含关注者ID和被关注者ID两个字段。
  • 设计好友关系表(Friend):包含用户ID和好友ID两个字段。

2. 用户注册功能:

  • 提供注册页面,用户输入用户名和密码。
  • 后端接收到注册请求后,将用户信息插入用户表中。

3. 用户登录功能:

  • 提供登录页面,用户输入用户名和密码。
  • 后端接收到登录请求后,查询用户表中是否存在对应的用户名和密码,如果存在则登录成功。

4. 关注功能:

  • 在用户个人主页或其他用户的个人主页上,提供关注按钮。
  • 用户点击关注按钮后,后端接收到关注请求,将关注者ID和被关注者ID插入关注关系表中。

5. 取消关注功能:

  • 在用户个人主页或其他用户的个人主页上,提供取消关注按钮。
  • 用户点击取消关注按钮后,后端接收到取消关注请求,将关注关系表中对应的记录删除。

6. 好友关系:

  • 实现好友关系可以基于相互关注的方式,即当两个用户互相关注时,认为他们是好友关系。
  • 在关注功能中,当用户A关注用户B后,后端可以检查用户B是否也关注了用户A,若是则建立好友关系。

7. 查询关系功能:

  • 提供查询页面,用户输入某个用户的用户名。
  • 后端接收到查询请求后,根据用户名查询用户ID。
  • 查询关注关系表和好友关系表,可以获取用户的关注列表和好友列表。

以上是一个简单的关系系统的实现思路,可以根据具体需求和业务场景进行进一步的扩展和优化。在实际开发过程中,可以选择使用Go语言的Web框架(如gin、beego等)来实现前后端的交互,同时使用数据库(如MySQL、PostgreSQL等)来存储用户信息和关系数据。通过前后端的交互和数据库的操作来实现用户关系的管理。

以下是一个完整的示例代码,分为前端和后端两部分,分别使用HTML/CSS/JavaScript和Go语言实现。

前端代码(HTML/CSS/JavaScript):

<!DOCTYPE html>
<html>
<head>
    <title>关系系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .container {
            max-width: 400px;
            margin: 0 auto;
            padding: 20px;
        }
        h1 {
            text-align: center;
        }
        label {
            display: block;
            margin-bottom: 10px;
        }
        input[type="text"],
        input[type="password"],
        button {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
        }
        #result {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>关系系统</h1>
        <div id="register">
            <h2>注册</h2>
            <label for="reg-username">用户名</label>
            <input type="text" id="reg-username" required>
            <label for="reg-password">密码</label>
            <input type="password" id="reg-password" required>
            <button onclick="register()">注册</button>
        </div>
        <div id="login">
            <h2>登录</h2>
            <label for="login-username">用户名</label>
            <input type="text" id="login-username" required>
            <label for="login-password">密码</label>
            <input type="password" id="login-password" required>
            <button onclick="login()">登录</button>
        </div>
        <div id="follow" style="display: none;">
            <h2>关注用户</h2>
            <label for="follow-username">用户名</label>
            <input type="text" id="follow-username" required>
            <button onclick="follow()">关注</button>
        </div>
        <div id="unfollow" style="display: none;">
            <h2>取消关注用户</h2>
            <label for="unfollow-username">用户名</label>
            <input type="text" id="unfollow-username" required>
            <button onclick="unfollow()">取消关注</button>
        </div>
        <div id="friends" style="display: none;">
            <h2>我的好友</h2>
            <button onclick="getFriends()">查询好友</button>
            <div id="result"></div>
        </div>
    </div>

    <script>
        var token = "";

        function register() {
            var username = document.getElementById("reg-username").value;
            var password = document.getElementById("reg-password").value;

            fetch("/register", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ username: username, password: password })
            }).then(function(response) {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                alert("注册成功,请登录");
            }).catch(function(error) {
                console.log(error);
                alert("注册失败,请重试");
            });
        }

        function login() {
            var username = document.getElementById("login-username").value;
            var password = document.getElementById("login-password").value;

            fetch("/login", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ username: username, password: password })
            }).then(function(response) {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                return response.json();
            }).then(function(data) {
                token = data.token;
                showFollow();
            }).catch(function(error) {
                console.log(error);
                alert("登录失败,请重试");
            });
        }

        function follow() {
            var username = document.getElementById("follow-username").value;

            fetch("/follow", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer "   token
                },
                body: JSON.stringify({ username: username })
            }).then(function(response) {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                alert("关注成功");
            }).catch(function(error) {
                console.log(error);
                alert("关注失败,请重试");
            });
        }

        function unfollow() {
            var username = document.getElementById("unfollow-username").value;

            fetch("/unfollow", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer "   token
                },
                body: JSON.stringify({ username: username })
            }).then(function(response) {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                alert("取消关注成功");
            }).catch(function(error) {
                console.log(error);
                alert("取消关注失败,请重试");
            });
        }

        function getFriends() {
            fetch("/friends", {
                method: "GET",
                headers: {
                    "Authorization": "Bearer "   token
                }
            }).then(function(response) {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                return response.json();
            }).then(function(data) {
                var resultHtml = "";
                data.friends.forEach(function(friend) {
                    resultHtml  = "<p>"   friend   "</p>";
                });
                document.getElementById("result").innerHTML = resultHtml;
            }).catch(function(error) {
                console.log(error);
                alert("查询好友失败,请重试");
            });
        }

        function showFollow() {
            document.getElementById("login").style.display = "none";
            document.getElementById("register").style.display = "none";
            document.getElementById("follow").style.display = "block";
            document.getElementById("unfollow").style.display = "block";
            document.getElementById("friends").style.display = "block";
        }
    </script>
</body>
</html>

后端代码(Go语言):

package main

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
)

type User struct {
	ID       int    `json:"id"`
	Username string `json:"username"`
	Password string `json:"password"`
}

type Follow struct {
	FollowerID   int `json:"follower_id"`
	FollowingID  int `json:"following_id"`
}

type Friend struct {
	UserID   int `json:"user_id"`
	FriendID int `json:"friend_id"`
}

var db *sql.DB

func main() {
	db, err := sql.Open("mysql", "root:password@tcp(localhost:3306)/social_network")
	if err != nil {
		log.Fatal(err)
	}

	router := gin.Default()
	router.Static("/", "./public")
	router.POST("/register", registerHandler)
	router.POST("/login", loginHandler)
	router.POST("/follow", followHandler)
	router.POST("/unfollow", unfollowHandler)
	router.GET("/friends", getFriendsHandler)

	router.Run(":8080")
}

func registerHandler(c *gin.Context) {
	var user User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	_, err := db.Exec("INSERT INTO users (username, password) VALUES (?, ?)", user.Username, user.Password)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.Status(http.StatusOK)
}

func loginHandler(c *gin.Context) {
	var user User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	err := db.QueryRow("SELECT id FROM users WHERE username=? AND password=?", user.Username, user.Password).Scan(&user.ID)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid username or password"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"token": fmt.Sprintf("user-%d-token", user.ID)})
}

func followHandler(c *gin.Context) {
	var follow Follow
	if err := c.ShouldBindJSON(&follow); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	_, err := db.Exec("INSERT INTO follows (follower_id, following_id) VALUES (?, ?)", follow.FollowerID, follow.FollowingID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.Status(http.StatusOK)
}

func unfollowHandler(c *gin.Context) {
	var follow Follow
	if err := c.ShouldBindJSON(&follow); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	_, err := db.Exec("DELETE FROM follows WHERE follower_id=? AND following_id=?", follow.FollowerID, follow.FollowingID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.Status(http.StatusOK)
}

func getFriendsHandler(c *gin.Context) {
	//

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgijebi
系列文章
更多 icon
同类精品
更多 icon
继续加载