OJ项目环境搭建
OJ项目环境搭建
数据库
建库:
problem,user,submit,category
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 50740
Source Host : localhost:3306
Source Schema : gin_gorm_oj
Target Server Type : MySQL
Target Server Version : 50740
File Encoding : 65001
Date: 14/10/2022 15:57:22
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for category
-- ----------------------------
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`identity` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '分类类别',
`parent_id` int(11) NULL DEFAULT NULL COMMENT '父级ID',
`created_at` datetime(0) NULL DEFAULT NULL,
`updated_at` datetime(0) NULL DEFAULT NULL,
`deleted_at` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of category
-- ----------------------------
-- ----------------------------
-- Table structure for problem
-- ----------------------------
DROP TABLE IF EXISTS `problem`;
CREATE TABLE `problem` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`identity` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`category_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '以逗号分割的单位',
`title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '问题的题目',
`content` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '问题的正文描述',
`max_runtime` int(11) NULL DEFAULT NULL COMMENT '最大的运行时间',
`max_mem` int(11) NULL DEFAULT NULL COMMENT '最大的运行内存',
`created_at` datetime(0) NULL DEFAULT NULL,
`updated_at` datetime(0) NULL DEFAULT NULL,
`deleted_at` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of problem
-- ----------------------------
INSERT INTO `problem` VALUES (1, '00001', '1', '标题1', '内容1', 10, 20, '2022-10-14 15:13:24', '2022-10-14 15:13:27', NULL);
-- ----------------------------
-- Table structure for submit
-- ----------------------------
DROP TABLE IF EXISTS `submit`;
CREATE TABLE `submit` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`identity` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`problem_identity` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '问题的唯一标识',
`user_identity` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户的唯一标识',
`path` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '代码的路径',
`status` tinyint(1) NULL DEFAULT NULL COMMENT '[0-待判断,1-答案正确,2-答案错误,3-运行超时,4-运行超内存]',
`created_at` datetime(0) NULL DEFAULT NULL,
`updated_at` datetime(0) NULL DEFAULT NULL,
`deleted_at` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of submit
-- ----------------------------
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`identity` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户名',
`password` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码',
`phone` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '手机号',
`mail` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱',
`created_at` datetime(0) NULL DEFAULT NULL,
`updated_at` datetime(0) NULL DEFAULT NULL,
`deleted_at` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
SET FOREIGN_KEY_CHECKS = 1;
Go依赖配置
gorm
下载 go get -u gorm.io/gorm
文档 https://learnku.com/docs/gorm/v2
小示例
func TestGormTest(t *testing.T) {
dsn := "root:123456@tcp(127.0.0.1:3306)/gin_gorm_oj?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
data := make([]*models.Problem, 0)
err = db.Find(&data).Error
if err != nil {
t.Fatal(err)
}
for _, v := range data {
fmt.Printf("Problem ===> %v /n", v)
}
}
gin
下载 go get -u -v github.com/gin-gonic/gin
文档 https://learnku.com/docs/gin-gonic/1.7
func Router() *gin.Engine {
r := gin.Default()
// Swagger配置
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
// 做些操作,路由规则
r.GET("/ping", service.Ping)
r.GET("/problem-list", service.GetProblemList)
return r
}
swagger
下载 go get -u github.com/swaggo/swag/cmd/swag
文档 https://github.com/swaggo/gin-swagger
每次新增接口都要使用 swag init,这样才会刷新它增加的内容
下载gin-swagger
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
接口访问:
http://localhost:8080/swagger/index.html
配置操作
- 在router里面要在gin的engine里面配置/swagger/*any的路径,让我们可以处理swagger
// Swagger配置
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
- 在接口服务上要添加注解,让swagger能够扫描到
// GetProblemList
// @Tags 公共方法
// @Summary 问题列表
// @Param page query int false "请输入当前页,默认第一页"
// @Param size query int false "size"
// @Success 200 {string} json "{"code":"200","msg","","data":""}"
// @Router /problem-list [get]
func GetProblemList(c *gin.Context) {
models.GetProblemList()
c.String(http.StatusOK, "Get Problem List")
}
jwt-go
go get github.com/dgrijalva/jwt-go
开箱即用的util
package utils
import (
"fmt"
"github.com/dgrijalva/jwt-go"
)
type UserClaims struct {
Identity string `json:"identity"`
Name string `json:"name"`
jwt.StandardClaims
}
var myKey = []byte("gin-gorm-oj-key")
// GenerateToken 生成token
func GenerateToken(identity, name string) (string, error) {
UserClaim := &UserClaims{
Identity: identity,
Name: name,
StandardClaims: jwt.StandardClaims{
ExpiresAt: 3000, // 设置过期时间
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, UserClaim)
tokenString, err := token.SignedString(myKey)
if err != nil {
return "", err
}
// 获取的token
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZGVudGl0eSI6InVzZXJfMSIsIm5hbWUiOiJHZXQifQ.4inO9HZINmKFYO9qEF2SYYPHk0GuuA-qUdwIhUa8USE
return tokenString, nil
}
// AnalyseToken 解析token
func AnalyseToken(token string) (*UserClaims, error) {
claim := new(UserClaims)
claims, err := jwt.ParseWithClaims(token, claim, func(token *jwt.Token) (interface{}, error) {
return myKey, nil
})
if err != nil {
return nil, err
}
fmt.Println(claims)
if !claims.Valid {
return nil, fmt.Errorf("token is invalid")
}
return claim, nil
}
发送邮件
go get github.com/jordan-wright/email
uuid
go get github.com/satori/go.uuid
go-redis
go get github.com/go-redis/redis/v8
var ctx = context.Background()
var rdb = redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "123456", // no password set
DB: 0, // use default DB
})
func Set(k, v string) error {
err := rdb.Set(ctx, k, v, time.Second*60)
return err.Err()
}
func Get(k string) (string, error) {
v, err := rdb.Get(ctx, k).Result()
return v, err
}
go-ztool
可以用来做加密解密,有uuid和雪花算法