上个webapi,来源一个看起来不够优雅,参考了一篇文章:
https://blog.csdn.net/qq_39312146/article/details/129801689
进行了简单的优化,无非是封装了方法,但是文章里的程序是编译不了的,排除了打字错误,我改了几个地方,问题的来自他的引用“hongjijun.com/xxxxx”,修改为自己的本地的路径就好了
这个是我的程序的的路径
对应的代码:
- main.go
package main
import (
"test/application"
)
func main() {
application.Run()
}
够简洁了吧
- user.go
package v1
import (
response "test/common/response"
"github.com/gin-gonic/gin"
)
func Login(ctx *gin.Context) {
username := ctx.PostForm("username")
password := ctx.PostForm("password")
//这里判断用户名密码的正确性
if username != "" && password != "" {
response.SuccessResultWithEmptyData(ctx)
}
}
引用的部分,定义response 到自己的路径“test/common/response”
- response.go
package response
import (
"net/http"
"github.com/gin-gonic/gin"
)
type Result struct {
Success bool
Code int
Msg string
Data interface{}
}
func response(success bool, code int, msg string, data interface{}, ctx *gin.Context) {
r := Result{success, code, msg, data}
ctx.JSON(http.StatusOK, r)
}
func successResponse(data interface{}, ctx *gin.Context) {
response(true, 0, "请求成功", data, ctx)
}
func failResponse(code int, msg string, ctx *gin.Context) {
response(false, code, msg, nil, ctx)
}
func SuccessResultWithEmptyData(ctx *gin.Context) {
successResponse(nil, ctx)
}
func SuccessResult(data interface{}, ctx *gin.Context) {
successResponse(data, ctx)
}
func FailResultWithDefaultMsg(code int, ctx *gin.Context) {
failResponse(code, "请求失败", ctx)
}
func FailResult(code int, msg string, ctx *gin.Context) {
failResponse(code, msg, ctx)
}
这里主要是定义了一个返回的结构体和返回的方法
- run.go
package application
import (
v1 "test/api/v1"
"github.com/gin-gonic/gin"
)
func Run() {
router := gin.New()
router.Use(gin.Logger(), gin.Recovery())
router.POST("/login", v1.Login)
router.Run(":8080")
}
这里主要定义了路由, v1指向自己的目录“test/api/v1”
运行,postman-》
但是现在主流都是post参数是json,必须改下,而且现在的程序也没有提交参数不对的返回,搜了下,修改了user.go
package v1
import (
"encoding/json"
response "test/common/response"
"github.com/gin-gonic/gin"
)
func Login(ctx *gin.Context) {
data, _ := ctx.GetRawData()
var body map[string]string
_ = json.Unmarshal(data, &body)
//获取json中的key,注意使用["key"]获取
username := body["username"]
password := body["password"]
//这里判断用户名密码的正确性
if username != "" && password != "" {
response.SuccessResultWithEmptyData(ctx)
} else {
response.FailResult(-1, "失败哦", ctx)
}
}
好了,下面再学学其他的吧。3天已经大概可以写程序了吧。