首页 > 其他分享 >一个练习项目,好玩的bbs-go-echo

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

时间:2024-09-02 14:18:44浏览次数:13  
标签:string err db sessionId echo json go bbs

代码:

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"
    "net/http"
    "strconv"

    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
    "github.com/labstack/echo"
)

var (
    userName  string = "root"
    password  string = "123456"
    ipAddrees string = "127.0.0.1"
    port      int    = 3306
    dbName    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
}

func Index_test(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    return c.String(http.StatusOK, "此站接口使用go.echo实现,<a href='api.html' target='_blank'>接口列表</a>")
}

func User_register(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    username := c.QueryParam("username")
    password := c.QueryParam("password")
    nickname := c.QueryParam("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()
        return c.JSON(http.StatusOK, &Responsex{Code: 0, Msg: "", Data: fmt.Sprintf("%d", insertId)})
    } else if result1.Id > 0 {
        return c.JSON(http.StatusOK, &Responsex{Code: 1, Msg: "用户名已经存在", Data: ""})
    } else {
        return c.JSON(http.StatusOK, &Responsex{Code: 1, Msg: "未知错误", Data: ""})
    }
}

func User_login(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    username := c.QueryParam("username")
    password := c.QueryParam("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 {
        return c.JSON(http.StatusOK, &Responsex{Code: 1, Msg: "用户名或者密码错误", Data: ""})
    } 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 = sessionId
        return c.JSON(http.StatusOK, &Responseuserinfo{Code: 0, Msg: "", Data: result1})
    }
}

func User_logout(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    sessionId := c.QueryParam("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 = ""
    }

    return c.JSON(http.StatusOK, &Responseuserinfo{Code: 0, Msg: "", Data: result1})
}

func User_info(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    sessionId := c.QueryParam("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)
    }

    return c.JSON(http.StatusOK, &Responseuserinfo{Code: 0, Msg: "", Data: result1})
}

func Post_list(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    page, err := strconv.Atoi(c.QueryParam("page"))
    keyword := c.QueryParam("keyword")

    if page <= 0 {
        page = 1
    }

    start := (page - 1) * pagesize

    addSql := " 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 " + addSql
    err = Db.Get(result1, sql1)
    if err != nil {
        log.Fatal(err)
    }

    var result2 []postinfo
    sql2 := "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.Count
    totalpage := 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 = totalpage

    return c.JSON(http.StatusOK, &Responsepostlistpage{Code: 0, Msg: "", Data: result3})
}

func Post_detail(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    id := c.QueryParam("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=" + id
    err := Db.Get(result1, sql1)
    if err != nil {
        log.Fatal(err)
    }

    return c.JSON(http.StatusOK, &Responsepostinfodetail{Code: 0, Msg: "", Data: result1})
}

func Post_add(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    title := c.QueryParam("title")
    content := c.QueryParam("content")
    sessionId := c.QueryParam("sessionId")

    var Db *sqlx.DB = connectMysql()
    defer Db.Close()

    var userinfo1 *userinfo = getloginuserinfo(sessionId)
    if userinfo1.Id <= 0 {
        return c.JSON(http.StatusOK, &Responsex{Code: 1, Msg: "请先登录", Data: ""})
    } 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()
        return c.JSON(http.StatusOK, &Responsex{Code: 0, Msg: "", Data: fmt.Sprintf("%d", insertId)})
    }
}

func Post_edit(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    id := c.QueryParam("id")
    title := c.QueryParam("title")
    content := c.QueryParam("content")
    sessionId := c.QueryParam("sessionId")

    var Db *sqlx.DB = connectMysql()
    defer Db.Close()

    var userinfo1 *userinfo = getloginuserinfo(sessionId)
    if userinfo1.Id <= 0 {
        return c.JSON(http.StatusOK, &Responsex{Code: 1, Msg: "请先登录", Data: ""})
    } 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)
        }
        return c.JSON(http.StatusOK, &Responsex{Code: 0, Msg: "", Data: ""})
    }
}

func Post_delete(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    id := c.QueryParam("id")
    sessionId := c.QueryParam("sessionId")

    var Db *sqlx.DB = connectMysql()
    defer Db.Close()

    var userinfo1 *userinfo = getloginuserinfo(sessionId)
    if userinfo1.Id <= 0 {
        return c.JSON(http.StatusOK, &Responsex{Code: 1, Msg: "请先登录", Data: ""})
    } 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)
        }
        return c.JSON(http.StatusOK, &Responsex{Code: 0, Msg: "", Data: ""})
    }
}

func Reply_list(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    page, err := strconv.Atoi(c.QueryParam("page"))
    contentId := c.QueryParam("contentId")

    if page <= 0 {
        page = 1
    }

    start := (page - 1) * pagesize

    var 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=" + contentId
    err = Db.Get(result1, sql1)
    if err != nil {
        log.Fatal(err)
    }

    var result2 []replyinfo
    sql2 := "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.Count
    totalpage := 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 = totalpage

    return c.JSON(http.StatusOK, &Responsereplylistpage{Code: 0, Msg: "", Data: result3})
}

func Reply_detail(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    id := c.QueryParam("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=" + id
    err := Db.Get(result1, sql1)
    if err != nil {
        log.Fatal(err)
    }

    return c.JSON(http.StatusOK, &Responsereplyinfo{Code: 0, Msg: "", Data: result1})
}

func Reply_add(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    contentId := c.QueryParam("contentId")
    content := c.QueryParam("content")
    sessionId := c.QueryParam("sessionId")

    var Db *sqlx.DB = connectMysql()
    defer Db.Close()

    var userinfo1 *userinfo = getloginuserinfo(sessionId)
    if userinfo1.Id <= 0 {
        return c.JSON(http.StatusOK, &Responsex{Code: 1, Msg: "请先登录", Data: ""})
    } else {
        sql1 := "update content set replyNum=replyNum+1 where id=" + contentId
        result1, 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()
        return c.JSON(http.StatusOK, &Responsex{Code: 0, Msg: "", Data: fmt.Sprintf("%d", insertId)})
    }
}

func Reply_edit(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    id := c.QueryParam("id")
    content := c.QueryParam("content")
    sessionId := c.QueryParam("sessionId")

    var Db *sqlx.DB = connectMysql()
    defer Db.Close()

    var userinfo1 *userinfo = getloginuserinfo(sessionId)
    if userinfo1.Id <= 0 {
        return c.JSON(http.StatusOK, &Responsex{Code: 1, Msg: "请先登录", Data: ""})
    } 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)
        }
        return c.JSON(http.StatusOK, &Responsex{Code: 0, Msg: "", Data: ""})
    }
}

func Reply_delete(c echo.Context) error {
    resp := c.Response()
    resp.Header().Set(echo.HeaderServer, "go-echo")

    id := c.QueryParam("id")
    sessionId := c.QueryParam("sessionId")

    var Db *sqlx.DB = connectMysql()
    defer Db.Close()

    var userinfo1 *userinfo = getloginuserinfo(sessionId)
    if userinfo1.Id <= 0 {
        return c.JSON(http.StatusOK, &Responsex{Code: 1, Msg: "请先登录", Data: ""})
    } else {
        var result0 *replyinfo = new(replyinfo)
        sql0 := "select id,content,replyUserId,replyUserNickename,addTime,contentId from reply where isDel=0 and id=" + id
        err := 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)
        }
        return c.JSON(http.StatusOK, &Responsex{Code: 0, Msg: "", Data: ""})
    }
}

func main() {
    e := echo.New()

    e.GET("/", Index_test)
    e.GET("/user/register", User_register)
    e.GET("/user/login", User_login)
    e.GET("/user/logout", User_logout)
    e.GET("/user/getuserinfo", User_info)
    e.GET("/post/list", Post_list)
    e.GET("/post/detail", Post_detail)
    e.GET("/post/add", Post_add)
    e.GET("/post/edit", Post_edit)
    e.GET("/post/delete", Post_delete)
    e.GET("/reply/list", Reply_list)
    e.GET("/reply/detail", Reply_detail)
    e.GET("/reply/add", Reply_add)
    e.GET("/reply/edit", Reply_edit)
    e.GET("/reply/delete", Reply_delete)

    e.Start(":1095")
}

 

输出:

D:\workspace\studys\study_bbs>D:\software\go\bin\go.exe run D:\workspace\studys\study_bbs\start_web_echo.go

   ____    __
  / __/___/ /  ___
 / _// __/ _ \/ _ \
/___/\__/_//_/\___/ v3.3.10-dev
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
                                    O\
⇨ http server started on [::]:1095

 

标签:string,err,db,sessionId,echo,json,go,bbs
From: https://www.cnblogs.com/xuxiaobo/p/18392612

相关文章

  • 一个练习项目,好玩的bbs-go-beego
    代码:packagemain/**goenv-wGO111MODULE=ongoenv-wGOPROXY=https://goproxy.cngomodinitgosgomodtidygomodvendor*/import("crypto/md5""database/sql""fmt""log""math"......
  • 一个练习项目,好玩的bbs-go-chi
    代码:packagemain/**goenv-wGO111MODULE=ongoenv-wGOPROXY=https://goproxy.cngomodinitgosgomodtidygomodvendor*/import("crypto/md5""database/sql""encoding/json""fmt""......
  • 一个练习项目,好玩的bbs-perl-mojolicious
    代码:#!D:/software/Strawberry/perl/bin/perl.exeBEGIN{push(@INC,'D:/workspace/studys/study_bbs');}useMojolicious::Lite-signatures;useutf8;useNet::MySQL;useEncode;usePOSIX;useJSONqw/encode_jsondecode_json/;useDigest;o......
  • 一个练习项目,好玩的bbs-perl-dancer
    代码:#!D:/software/Strawberry/perl/bin/perl.exeBEGIN{push(@INC,'D:/workspace/studys/study_bbs');}useutf8;useDancer;useDancer::Serializer::JSON;useNet::MySQL;useEncode;usePOSIX;useJSONqw/encode_jsondecode_json/;useDi......
  • 一个练习项目,好玩的bbs-python-cherrypy
    代码:importcherrypyimportMySQLdbimportjsonimporthashlibimportrandomimportmathimportosfromdatetimeimportdatetimeclassDateEncoder(json.JSONEncoder):defdefault(self,obj):ifisinstance(obj,datetime):returnobj......
  • 一个练习项目,好玩的bbs-python-tornado
    代码:importos.pathimporttornado.httpserverimporttornado.webimporttornado.optionsimporttornado.ioloopfromtornado.optionsimportdefine,optionsimportMySQLdbimportjsonimporthashlibimportrandomimportmathimportosfromdatetimeimportda......
  • 一个练习项目,好玩的bbs-python-flask
    代码:fromflaskimportFlask,make_response,requestimportos.pathimportMySQLdbimportjsonimporthashlibimportrandomimportmathimportosfromdatetimeimportdatetimeapp=Flask(__name__)classDateEncoder(json.JSONEncoder):defdefault(se......
  • 一个练习项目,好玩的bbs-python-fastapi
    代码:fromfastapiimportFastAPI,Response,Cookie,Dependsfromfastapi.responsesimportJSONResponsefromfastapi.responsesimportHTMLResponseimportos.pathimportMySQLdbimportjsonimporthashlibimportrandomimportmathimportosfromdatetimeim......
  • 一个练习项目,好玩的bbs-python-bottle
    代码:frombottleimportroute,run,templatefrombottleimportBottle,request,responseimportos.pathimportMySQLdbimportjsonimporthashlibimportrandomimportmathimportosfromdatetimeimportdatetimeclassDateEncoder(json.JSONEncoder):......
  • 一个练习项目,好玩的bbs-python-pyramid
    代码:fromwsgiref.simple_serverimportmake_serverfrompyramid.configimportConfiguratorfrompyramid.viewimportview_configfrompyramid.responseimportResponseimportos.pathimportMySQLdbimportjsonimporthashlibimportrandomimportmathimport......