介绍:分别测试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
文章来源:https://www.toymoban.com/news/detail-823596.html
3.2 post
这里面包括了测试redis
4.完整代码
项目地址文章来源地址https://www.toymoban.com/news/detail-823596.html
到了这里,关于go api(get post传参,数据库,redis) 测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!