一个练习项目,好玩的bbs-go-beego

news/2024/11/13 20:36:09/文章来源:https://www.cnblogs.com/xuxiaobo/p/18392616

代码:

package main/**
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn
go mod init gos
go mod tidy
go mod vendor
*/import ("crypto/md5""database/sql""fmt""log""math""strconv""github.com/astaxie/beego"_ "github.com/go-sql-driver/mysql""github.com/jmoiron/sqlx"
)var (userName  string = "root"password  string = "123456"ipAddrees string = "127.0.0.1"port      int    = 3306dbName    string = "my_bbs"charset   string = "utf8mb4"
)type countinfo struct {Count int64 `db:"count" json:"count"`
}type userinfo struct {Id        int    `db:"id" json:"id"`Username  string `db:"username" json:"username"`Nickname  string `db:"nickname" json:"nickname"`AddTime   string `db:"addTime" json:"addTime"`SessionId string `db:"sessionId" json:"sessionId"`
}type postinfo struct {Id            int    `db:"id" json:"id"`Title         string `db:"title" json:"title"`UserId        string `db:"userId" json:"userId"`UserNickename string `db:"userNickename" json:"userNickename"`ReplyNum      int    `db:"replyNum" json:"replyNum"`UpdateTime    string `db:"updateTime" json:"updateTime"`
}type postinfodetail struct {Id            int    `db:"id" json:"id"`Title         string `db:"title" json:"title"`Content       string `db:"content" json:"content"`UserId        int    `db:"userId" json:"userId"`UserNickename string `db:"userNickename" json:"userNickename"`ReplyNum      int    `db:"replyNum" json:"replyNum"`UpdateTime    string `db:"updateTime" json:"updateTime"`
}type replyinfo struct {Id                 int    `db:"id" json:"id"`ContentId          int    `db:"contentId" json:"contentId"`Content            string `db:"content" json:"content"`ReplyUserId        int    `db:"replyUserId" json:"replyUserId"`ReplyUserNickename string `db:"replyUserNickename" json:"replyUserNickename"`AddTime            string `db:"addTime" json:"addTime"`
}type postlistpage struct {Totalpage int        `db:"totalpage" json:"totalpage"`Data      []postinfo `db:"data" json:"data"`
}type replylistpage struct {Totalpage int         `db:"totalpage" json:"totalpage"`Data      []replyinfo `db:"data" json:"data"`
}type Responsex struct {Code int    `json:"code"`Msg  string `json:"msg"`Data string `json:"data"`
}type Responseuserinfo struct {Code int       `json:"code"`Msg  string    `json:"msg"`Data *userinfo `json:"data"`
}type Responsepostlistpage struct {Code int           `json:"code"`Msg  string        `json:"msg"`Data *postlistpage `json:"data"`
}type Responsepostinfodetail struct {Code int             `json:"code"`Msg  string          `json:"msg"`Data *postinfodetail `json:"data"`
}type Responsereplylistpage struct {Code int            `json:"code"`Msg  string         `json:"msg"`Data *replylistpage `json:"data"`
}type Responsereplyinfo struct {Code int        `json:"code"`Msg  string     `json:"msg"`Data *replyinfo `json:"data"`
}var pagesize = 20
var secretKey = "saacac3423@21212"func connectMysql() *sqlx.DB {dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", userName, password, ipAddrees, port, dbName, charset)Db, err := sqlx.Open("mysql", dsn)if err != nil {log.Fatal(err)}return Db
}func calcMD5(message string) string {data := []byte(message)return fmt.Sprintf("%x", md5.Sum(data))
}func getloginuserinfo(sessionId string) *userinfo {var Db *sqlx.DB = connectMysql()defer Db.Close()var result1 *userinfo = new(userinfo)sql1 := "select id,username,nickname,addTime,sessionId from user where sessionId='" + sessionId + "'"err := Db.Get(result1, sql1)if err != nil {log.Fatal(err)}return result1
}type IndexController struct {beego.Controller
}type UserRegisterController struct {beego.Controller
}type UserLoginController struct {beego.Controller
}type UserLogoutController struct {beego.Controller
}type UserInfoController struct {beego.Controller
}type PostlistController struct {beego.Controller
}type PostdetailController struct {beego.Controller
}type PostaddController struct {beego.Controller
}type PosteditController struct {beego.Controller
}type PostdeleteController struct {beego.Controller
}type ReplylistController struct {beego.Controller
}type ReplydetailController struct {beego.Controller
}type ReplyaddController struct {beego.Controller
}type ReplyeditController struct {beego.Controller
}type ReplydeleteController struct {beego.Controller
}func (this *IndexController) Get() {this.Ctx.Output.Header("Server", "go.beego")this.Ctx.WriteString("此站接口使用go.beego实现,<a href='api.html' target='_blank'>接口列表</a>")
}func (this *UserRegisterController) Get() {this.Ctx.Output.Header("Server", "go.beego")username := this.Ctx.Input.Query("username")password := this.Ctx.Input.Query("password")nickname := this.Ctx.Input.Query("nickname")passwordMd5 := calcMD5(password)var Db *sqlx.DB = connectMysql()defer Db.Close()var result1 *userinfo = new(userinfo)sql1 := "select id,username,nickname,addTime,sessionId from user where username='" + username + "'"err := Db.Get(result1, sql1)if err == sql.ErrNoRows {sql2 := "insert into user(username, password, nickname) value('" + username + "', '" + passwordMd5 + "', '" + nickname + "')"result2, err := Db.Exec(sql2)if err != nil {log.Fatal(err)log.Fatal(result2)}insertId, err := result2.LastInsertId()this.Data["json"] = &Responsex{Code: 0, Msg: "", Data: fmt.Sprintf("%d", insertId)}this.ServeJSON()} else if result1.Id > 0 {this.Data["json"] = &Responsex{Code: 1, Msg: "用户名已经存在", Data: ""}this.ServeJSON()} else {this.Data["json"] = &Responsex{Code: 1, Msg: "未知错误", Data: ""}this.ServeJSON()}
}func (this *UserLoginController) Get() {this.Ctx.Output.Header("Server", "go.beego")username := this.Ctx.Input.Query("username")password := this.Ctx.Input.Query("password")passwordMd5 := calcMD5(password)var Db *sqlx.DB = connectMysql()defer Db.Close()var result1 *userinfo = new(userinfo)sql1 := "select id,username,nickname,addTime,sessionId from user where username='" + username + "' and password='" + passwordMd5 + "'"err := Db.Get(result1, sql1)if err == sql.ErrNoRows {this.Data["json"] = &Responsex{Code: 1, Msg: "用户名或者密码错误", Data: ""}this.ServeJSON()} else {sessionId := calcMD5(secretKey + strconv.Itoa(result1.Id) + result1.AddTime)sql2 := "update user set sessionId='" + sessionId + "' where id=" + strconv.Itoa(result1.Id)result2, err := Db.Exec(sql2)if err != nil {log.Fatal(err)log.Fatal(result2)}result1.SessionId = sessionIdthis.Data["json"] = &Responseuserinfo{Code: 0, Msg: "", Data: result1}this.ServeJSON()}
}func (this *UserLogoutController) Get() {this.Ctx.Output.Header("Server", "go.beego")sessionId := this.Ctx.Input.Query("sessionId")var Db *sqlx.DB = connectMysql()defer Db.Close()var result1 *userinfo = new(userinfo)sql1 := "select id,username,nickname,addTime,sessionId from user where sessionId='" + sessionId + "'"err := Db.Get(result1, sql1)if err == sql.ErrNoRows {//
    } else {sql2 := "update user set sessionId='' where sessionId='" + sessionId + "'"result2, err := Db.Exec(sql2)if err != nil {log.Fatal(err)log.Fatal(result2)}result1.SessionId = ""}this.Data["json"] = &Responseuserinfo{Code: 0, Msg: "", Data: result1}this.ServeJSON()
}func (this *UserInfoController) Get() {this.Ctx.Output.Header("Server", "go.beego")sessionId := this.Ctx.Input.Query("sessionId")var Db *sqlx.DB = connectMysql()defer Db.Close()var result1 *userinfo = new(userinfo)sql1 := "select id,username,nickname,addTime,sessionId from user where sessionId='" + sessionId + "'"err := Db.Get(result1, sql1)if err != nil {log.Fatal(err)}this.Data["json"] = &Responseuserinfo{Code: 0, Msg: "", Data: result1}this.ServeJSON()
}func (this *PostlistController) Get() {this.Ctx.Output.Header("Server", "go.beego")page, err := strconv.Atoi(this.Ctx.Input.Query("page"))keyword := this.Ctx.Input.Query("keyword")if page <= 0 {page = 1}start := (page - 1) * pagesizeaddSql := " isDel=0 "if keyword != "" {addSql = " isDel=0 and title like '%" + keyword + "%' "}var Db *sqlx.DB = connectMysql()defer Db.Close()var result1 *countinfo = new(countinfo)sql1 := "select count(1) as count from content where " + addSqlerr = Db.Get(result1, sql1)if err != nil {log.Fatal(err)}var result2 []postinfosql2 := "select id,title,userId,userNickename,replyNum,updateTime from content where " + addSql + " order by updateTime desc limit " + strconv.Itoa(start) + "," + strconv.Itoa(pagesize)err = Db.Select(&result2, sql2)if err != nil {log.Fatal(err)}totalcount := result1.Counttotalpage := int(math.Ceil(float64(totalcount) / float64(pagesize)))var result3 *postlistpage = new(postlistpage)if result2 != nil {result3.Data = result2} else {result3.Data = make([]postinfo, 0)}result3.Totalpage = totalpagethis.Data["json"] = &Responsepostlistpage{Code: 0, Msg: "", Data: result3}this.ServeJSON()
}func (this *PostdetailController) Get() {this.Ctx.Output.Header("Server", "go.beego")id := this.Ctx.Input.Query("id")var Db *sqlx.DB = connectMysql()defer Db.Close()var result1 *postinfodetail = new(postinfodetail)sql1 := "select id,title,content,userId,userNickename,replyNum,updateTime from content where isDel=0 and id=" + iderr := Db.Get(result1, sql1)if err != nil {log.Fatal(err)}this.Data["json"] = &Responsepostinfodetail{Code: 0, Msg: "", Data: result1}this.ServeJSON()
}func (this *PostaddController) Get() {this.Ctx.Output.Header("Server", "go.beego")title := this.Ctx.Input.Query("title")content := this.Ctx.Input.Query("content")sessionId := this.Ctx.Input.Query("sessionId")var Db *sqlx.DB = connectMysql()defer Db.Close()var userinfo1 *userinfo = getloginuserinfo(sessionId)if userinfo1.Id <= 0 {this.Data["json"] = &Responsex{Code: 1, Msg: "请先登录", Data: ""}this.ServeJSON()} else {sql2 := "insert into content(title, content, userId, userNickename) value('" + title + "', '" + content + "', " + strconv.Itoa(userinfo1.Id) + ", '" + userinfo1.Nickname + "')"result2, err := Db.Exec(sql2)if err != nil {log.Fatal(err)log.Fatal(result2)}insertId, err := result2.LastInsertId()this.Data["json"] = &Responsex{Code: 0, Msg: "", Data: fmt.Sprintf("%d", insertId)}this.ServeJSON()}
}func (this *PosteditController) Get() {this.Ctx.Output.Header("Server", "go.beego")id := this.Ctx.Input.Query("id")title := this.Ctx.Input.Query("title")content := this.Ctx.Input.Query("content")sessionId := this.Ctx.Input.Query("sessionId")var Db *sqlx.DB = connectMysql()defer Db.Close()var userinfo1 *userinfo = getloginuserinfo(sessionId)if userinfo1.Id <= 0 {this.Data["json"] = &Responsex{Code: 1, Msg: "请先登录", Data: ""}this.ServeJSON()} else {sql2 := "update content set title='" + title + "',content='" + content + "',userId=" + strconv.Itoa(userinfo1.Id) + ",userNickename='" + userinfo1.Nickname + "' where id=" + id + " and userId=" + strconv.Itoa(userinfo1.Id)result2, err := Db.Exec(sql2)if err != nil {log.Fatal(err)log.Fatal(result2)}this.Data["json"] = &Responsex{Code: 0, Msg: "", Data: ""}this.ServeJSON()}
}func (this *PostdeleteController) Get() {this.Ctx.Output.Header("Server", "go.beego")id := this.Ctx.Input.Query("id")sessionId := this.Ctx.Input.Query("sessionId")var Db *sqlx.DB = connectMysql()defer Db.Close()var userinfo1 *userinfo = getloginuserinfo(sessionId)if userinfo1.Id <= 0 {this.Data["json"] = &Responsex{Code: 1, Msg: "请先登录", Data: ""}this.ServeJSON()} else {sql2 := "update content set isDel=1 where id=" + id + " and userId=" + strconv.Itoa(userinfo1.Id)result2, err := Db.Exec(sql2)if err != nil {log.Fatal(err)log.Fatal(result2)}this.Data["json"] = &Responsex{Code: 0, Msg: "", Data: ""}this.ServeJSON()}
}func (this *ReplylistController) Get() {this.Ctx.Output.Header("Server", "go.beego")page, err := strconv.Atoi(this.Ctx.Input.Query("page"))contentId := this.Ctx.Input.Query("contentId")if page <= 0 {page = 1}start := (page - 1) * pagesizevar Db *sqlx.DB = connectMysql()defer Db.Close()var result1 *countinfo = new(countinfo)sql1 := "select count(1) as count from reply where isDel=0 and contentId=" + contentIderr = Db.Get(result1, sql1)if err != nil {log.Fatal(err)}var result2 []replyinfosql2 := "select id,content,replyUserId,replyUserNickename,addTime,contentId from reply where isDel=0 and contentId=" + contentId + " order by id asc limit " + strconv.Itoa(start) + "," + strconv.Itoa(pagesize)err = Db.Select(&result2, sql2)if err != nil {log.Fatal(err)}totalcount := result1.Counttotalpage := int(math.Ceil(float64(totalcount) / float64(pagesize)))var result3 *replylistpage = new(replylistpage)if result2 != nil {result3.Data = result2} else {result3.Data = make([]replyinfo, 0)}result3.Totalpage = totalpagethis.Data["json"] = &Responsereplylistpage{Code: 0, Msg: "", Data: result3}this.ServeJSON()
}func (this *ReplydetailController) Get() {this.Ctx.Output.Header("Server", "go.beego")id := this.Ctx.Input.Query("id")var Db *sqlx.DB = connectMysql()defer Db.Close()var result1 *replyinfo = new(replyinfo)sql1 := "select id,content,replyUserId,replyUserNickename,addTime,contentId from reply where isDel=0 and id=" + iderr := Db.Get(result1, sql1)if err != nil {log.Fatal(err)}this.Data["json"] = &Responsereplyinfo{Code: 0, Msg: "", Data: result1}this.ServeJSON()
}func (this *ReplyaddController) Get() {this.Ctx.Output.Header("Server", "go.beego")contentId := this.Ctx.Input.Query("contentId")content := this.Ctx.Input.Query("content")sessionId := this.Ctx.Input.Query("sessionId")var Db *sqlx.DB = connectMysql()defer Db.Close()var userinfo1 *userinfo = getloginuserinfo(sessionId)if userinfo1.Id <= 0 {this.Data["json"] = &Responsex{Code: 1, Msg: "请先登录", Data: ""}this.ServeJSON()} else {sql1 := "update content set replyNum=replyNum+1 where id=" + contentIdresult1, err := Db.Exec(sql1)if err != nil {log.Fatal(err)log.Fatal(result1)}sql2 := "insert into reply(contentId, content, replyUserId, replyUserNickename) value(" + contentId + ", '" + content + "', " + strconv.Itoa(userinfo1.Id) + ", '" + userinfo1.Nickname + "')"result2, err := Db.Exec(sql2)if err != nil {log.Fatal(err)log.Fatal(result2)}insertId, err := result2.LastInsertId()this.Data["json"] = &Responsex{Code: 0, Msg: "", Data: fmt.Sprintf("%d", insertId)}this.ServeJSON()}
}func (this *ReplyeditController) Get() {this.Ctx.Output.Header("Server", "go.beego")id := this.Ctx.Input.Query("id")content := this.Ctx.Input.Query("content")sessionId := this.Ctx.Input.Query("sessionId")var Db *sqlx.DB = connectMysql()defer Db.Close()var userinfo1 *userinfo = getloginuserinfo(sessionId)if userinfo1.Id <= 0 {this.Data["json"] = &Responsex{Code: 1, Msg: "请先登录", Data: ""}this.ServeJSON()} else {sql2 := "update reply set content='" + content + "',replyUserId=" + strconv.Itoa(userinfo1.Id) + ",replyUserNickename='" + userinfo1.Nickname + "' where id=" + id + " and replyUserId=" + strconv.Itoa(userinfo1.Id)result2, err := Db.Exec(sql2)if err != nil {log.Fatal(err)log.Fatal(result2)}this.Data["json"] = &Responsex{Code: 0, Msg: "", Data: ""}this.ServeJSON()}
}func (this *ReplydeleteController) Get() {this.Ctx.Output.Header("Server", "go.beego")id := this.Ctx.Input.Query("id")sessionId := this.Ctx.Input.Query("sessionId")var Db *sqlx.DB = connectMysql()defer Db.Close()var userinfo1 *userinfo = getloginuserinfo(sessionId)if userinfo1.Id <= 0 {this.Data["json"] = &Responsex{Code: 1, Msg: "请先登录", Data: ""}this.ServeJSON()} else {var result0 *replyinfo = new(replyinfo)sql0 := "select id,content,replyUserId,replyUserNickename,addTime,contentId from reply where isDel=0 and id=" + iderr := Db.Get(result0, sql0)if err != nil {log.Fatal(err)}sql1 := "update content set replyNum=replyNum-1 where id=" + strconv.Itoa(result0.ContentId)result1, err := Db.Exec(sql1)if err != nil {log.Fatal(err)log.Fatal(result1)}sql2 := "update reply set isDel=1 where id=" + id + " and replyUserId=" + strconv.Itoa(userinfo1.Id)result2, err := Db.Exec(sql2)if err != nil {log.Fatal(err)log.Fatal(result2)}this.Data["json"] = &Responsex{Code: 0, Msg: "", Data: ""}this.ServeJSON()}
}func main() {beego.BConfig.AppName = "beego"beego.BConfig.ServerName = "beego"beego.BConfig.Listen.HTTPAddr = "127.0.0.1"beego.BConfig.Listen.HTTPPort = 1096beego.Router("/", &IndexController{})beego.Router("/user/register", &UserRegisterController{})beego.Router("/user/login", &UserLoginController{})beego.Router("/user/logout", &UserLogoutController{})beego.Router("/user/getuserinfo", &UserInfoController{})beego.Router("/post/list", &PostlistController{})beego.Router("/post/detail", &PostdetailController{})beego.Router("/post/add", &PostaddController{})beego.Router("/post/edit", &PosteditController{})beego.Router("/post/delete", &PostdeleteController{})beego.Router("/reply/list", &ReplylistController{})beego.Router("/reply/detail", &ReplydetailController{})beego.Router("/reply/add", &ReplyaddController{})beego.Router("/reply/edit", &ReplyeditController{})beego.Router("/reply/delete", &ReplydeleteController{})beego.Run()
}

 

输出:

D:\workspace\studys\study_bbs>D:\software\go\bin\go.exe run D:\workspace\studys\study_bbs\start_web_beego.go
2024/09/02 14:14:04.499 [I]  http server Running on http://127.0.0.1:1096

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/791016.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

一个练习项目,好玩的bbs-python-webpy

代码:import web import os.path import MySQLdb import json import hashlib import random import math import os from datetime import datetimeclass DateEncoder(json.JSONEncoder):def default(self, obj):if isinstance(obj, datetime):return obj.strftime("%Y-…

一个练习项目,好玩的bbs-python-flask

代码:from flask import Flask, make_response, request import os.path import MySQLdb import json import hashlib import random import math import os from datetime import datetimeapp = Flask(__name__)class DateEncoder(json.JSONEncoder):def default(self, obj):…

新电脑第一次拉取仓库代码

为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置git config --global user.name xxxxxxxx git config --global user.email xxxxxxxx初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置1 生成 RSA 密钥ssh-keygen -t rsa2 获取 RSA 公…

java~重写hashcode和equals

单字段和多字段重写hashcode 在 Java 中,重写 hashCode 方法的场景通常与对象的哈希值计算有关,特别是在使用哈希表(如 HashMap, HashSet 等)时。下面是你提供的两种 hashCode 实现的具体使用场景分析: 1. 第一种实现 @Override public boolean equals(Object o) {if (thi…

鱼眼相机成像模型和畸变模型

一文详解分析鱼眼相机投影成像模型和畸变模型 - feng..liu - 博客园 (cnblogs.com) 深入洞察OpenCV鱼眼模型之成像投影和畸变表估计系数相互转化 - 知乎 (zhihu.com)

第十二周-云计算运维作业

总结zabbix安装过程(选择课程演示版本)。1. 下载仓库 # wget https://repo.zabbix.com/zabbix/6.0/ubuntu/pool/main/z/zabbix-release/zabbix-release_6.0-4+ubuntu22.04_all.deb # dpkg -i zabbix-release_6.0-4+ubuntu22.04_all.deb # apt update 2. 安装Zabbix server,W…

OpenCV开发笔记(八十):基于特征点匹配实现全景图片拼接

前言一个摄像头视野不大的时候,我们希望进行两个视野合并,这样让正视的视野增大,从而可以看到更广阔的标准视野。拼接的方法分为两条路,第一条路是Sticher类,第二条思路是特征点匹配。  本篇使用特征点匹配,进行两张图来视野合并拼接。 Demo100%的点匹配  换了一幅图…

中国最著名十大风水大师排名

风水大师,又称阴阳先生,因为它们常常在看风水时利用阴阳学说进行解释,于是便有了这样的称谓。风水大师从古至今非常之多,其中也不乏江湖骗子。本期风水大师就来说说中国知名的有真材实料的风水大师吧。 中国最著名十大风水大师排名 Top1裴翁 裴翁(又名裴伟胜),是世界地理名…

从实在智能最新发布的实在Agent 7.0,看RPA Agent的迭代升级

智能体进化发展了一年,现在的RPA Agent迭代到什么程度了? 从实在智能最新发布的实在Agent 7.0,看RPA Agent的迭代升级 抓取豆瓣信息、自己制作PPT,这款AI Agent真的实现了流程全自动化 AI Agent构建到执行全自动化,持续进化RPA Agent再次降低智能体应用门槛 实在智能重磅发…

丝滑解决Chatgpt频繁奔溃、断网掉线问题

这段时间使用Chatgpt的时候频繁出现`something wrong`等断网掉线问题,中间还频繁出现物品转向的人机验证(我那么具有迷惑性吗...),被烦的不行。后面了解到有一个**KeepChatgpt**的插件可以解决这些问题,于是把这个方法介绍给大家,希望大家也都可以丝滑gpt。事件缘由 这段…

周赛413场 个人总结

周赛413场 个人总结第1题 代码 """ 根据a的ascii码值是97 奇数 黑色的规律是: a1是 97 + 1 = 偶数 b2 是 98 + 2 =偶数 c1 是99 +1 = 偶数 d2 是100 + 2 = 偶数 ... 所以,偶数为黑色 === 白色的规律 a2 = 97 +2 = 奇数 b1 = 98 +1 = 奇数 .... 所以,奇数为…

【LaTex、markdown】常用语法写出漂亮的blog

@目录markdown加粗斜体设置标题级别设置目录删除线无序列表有序列表分割线代办引用高亮标记字体颜色代码块图片链接表格公式表达行中公式独行公式LaTex初步文章骨干换行与换页figure(基本是图片)表格公式公式字体颜色左右居中figure引用文献引用markdown 加粗 **加粗样式**格…