go api(get post传参,数据库,redis) 测试

介绍:分别测试get请求,post请求,请求链接数据库,以及redis操作。
1.api代码

package main

import (
	_ "database/sql"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"go-test/com.zs/database"
	"go-test/com.zs/models"
	"go-test/com.zs/repositories"
	"go-test/com.zs/services"
	"go-test/com.zs/utils"
	"log"
	"net/http"
	"strconv"
)

func main() {

	router := gin.Default()

	//reDB, _ := config.ConnRedis()

	log.Println("coming main method ...")
	db, err := database.NewMySQLDB()
	if err != nil {
		log.Fatal(err)
	}

	userRepository := &repositories.UserRepository{
		DB: db,
	}
	userService := &services.UserService{
		UserRepository: userRepository,
	}

	http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodGet:
			users, err := userService.GetUsers()
			if err != nil {
				utils.ErrorHandler(w, err)
				return
			}
			utils.RespondJSON(w, users, http.StatusOK)

		case http.MethodPost:
			var user models.User
			err := json.NewDecoder(r.Body).Decode(&user)
			if err != nil {
				utils.ErrorHandler(w, err)
				return
			}
			err = userService.CreateUser(&user)
			if err != nil {
				utils.ErrorHandler(w, err)
				return
			}
			utils.RespondJSON(w, user, http.StatusCreated)

		default:
			w.WriteHeader(http.StatusMethodNotAllowed)
			response := models.ErrorResponse{
				Message: "Method not allowed",
			}
			json.NewEncoder(w).Encode(response)
		}
	})

	// http.HandleFunc get 请求拼接参数查询
	//http.HandleFunc("/getUserById", func(w http.ResponseWriter, r *http.Request) {
	//	switch r.Method {
	//	case http.MethodGet:
	//		n, err := strconv.Atoi(r.URL.Query().Get("id"))
	//		user, err := userService.GetUserByID(uint(n))
	//		if err != nil {
	//			utils.ErrorHandler(w, err)
	//			return
	//		}
	//		utils.RespondJSON(w, user, http.StatusOK)
	//
	//	}
	//})

	// router := gin.Default() get请求拼接参数查询
	router.GET("/getUserById", func(c *gin.Context) {
		uid := c.Query("id")
		num, _ := strconv.Atoi(uid)
		user, err := userService.GetUserByID(uint(num))
		if err != nil {
			return
		}
		// 返回字符串
		//c.String(http.StatusOK, "姓名:%s,年龄:%s", user.Name, strconv.Itoa(user.Age))

		// 返回json数据
		c.JSON(http.StatusOK, user)
	})

	// router := gin.Default() post请求拼接参数查询
	router.POST("/postUserById", func(c *gin.Context) {
		//uid := c.PostForm("id") //post请求中 form表单形式
		//num, _ := strconv.Atoi(uid)
		//user, err := userService.GetUserByID(uint(num))
		//if err != nil {
		//	return
		//}
		 返回字符串
		c.String(http.StatusOK, "姓名:%s,年龄:%s", user.Name, strconv.Itoa(user.Age))
		 返回json数据
		//c.JSON(http.StatusOK, user)

		//接收json数据处理方式
		if err := c.ShouldBindJSON(&models.UserJsonReq); err != nil {
			c.JSON(400, gin.H{"error": "无效的JSON格式或参数错误"})
			return
		}

		tId := uint(models.UserJsonReq.ID)
		tName := models.UserJsonReq.Name
		tAge := models.UserJsonReq.Age

		log.Printf("name:%s,age:%s", tName, strconv.Itoa(tAge))

		user, err := userService.GetUserByID(tId)

		if err != nil {
			return
		}

		// 测试往redis中添加string 数据
		//res1, err := reDB.Set(config.GetCtx(), "name", user.Name, time.Minute).Result()
		//if err != nil {
		//	fmt.Println(err)
		//}
		//fmt.Printf("插入成功:%s\n", res1)

		//测试往redis中批量添加string 数据
		//res2, err := reDB.MSet(config.GetCtx(), "user_id", user.ID, "age", user.Age).Result()
		//if err != nil {
		//	fmt.Println(err)
		//}
		//fmt.Printf("插入多行成功:%s\n", res2)

		// 测试从redis中取出数据
		//fmt.Printf("取出数据userId:%s\n", reDB.Get(config.GetCtx(), strconv.Itoa(int(user.ID))))
		//fmt.Printf("取出数据userAge:%s\n", reDB.Get(config.GetCtx(), strconv.Itoa(user.Age)))

		// 删除user_id=1 数据
		//n, err := reDB.Del(config.GetCtx(), "user_id", strconv.Itoa(int(user.ID))).Result()
		//if err != nil {
		//	fmt.Println(err)
		//}
		//fmt.Printf("删除了%d\n", n)

		// 以上只是对redis中string 操作,其它list,hash,set查看具体官方文档
		// 附几篇不错的博客:https://blog.csdn.net/qq_21275565/article/details/129904644,
		//https://blog.csdn.net/weixin_43495948/article/details/127893883?ops_request_misc=&request_id=&biz_id=102&utm_term=go%20%E9%9B%86%E5%90%88redis%20%E6%B5%8B%E8%AF%95&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-6-127893883.142^v99^pc_search_result_base4&spm=1018.2226.3001.4187

		c.JSON(http.StatusOK, user)
	})

	log.Println("Server is running on port 8000")
	// 和http.HandleFunc使用
	//log.Fatal(http.ListenAndServe(":8000", nil))

	// 和router := gin.Default()使用
	log.Fatal(router.Run(":8000"))
}

2.相关sql

CREATE TABLE `users` (
                         `id` int(11) NOT NULL AUTO_INCREMENT,
                         `name` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
                         `age` int(12) DEFAULT '18',
                         PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;



INSERT INTO `user_demo`.`users` (`id`, `name`, `age`) VALUES (1, 'aa', 12);
INSERT INTO `user_demo`.`users` (`id`, `name`, `age`) VALUES (2, 'bb', 22);

3.测试
3.1 get
go api(get post传参,数据库,redis) 测试_第1张图片

3.2 post
这里面包括了测试redis
go api(get post传参,数据库,redis) 测试_第2张图片
go api(get post传参,数据库,redis) 测试_第3张图片4.完整代码
项目地址

你可能感兴趣的:(数据库,golang,redis)