Commit 2e8eb26f authored by 李宇怀's avatar 李宇怀
Browse files

添加了测试模板

parent e5722257
package route package route
import ( import (
"github.com/gin-gonic/gin"
"go-svc-tpl/api/dto" "go-svc-tpl/api/dto"
"net/http" "net/http"
"github.com/gin-gonic/gin"
) )
func Ping(c *gin.Context) { func Ping(c *gin.Context) {
...@@ -16,5 +17,20 @@ func Ping(c *gin.Context) { ...@@ -16,5 +17,20 @@ func Ping(c *gin.Context) {
func SetupRouter(r *gin.RouterGroup) { func SetupRouter(r *gin.RouterGroup) {
r.GET("/ping", Ping) r.GET("/ping", Ping)
setupFooController(r) r.POST("/register", Register)
r.POST("/login", Login)
setupUserController(r)
}
func Register(ctx *gin.Context) {
// 注册
// ctx.JSON(http.StatusOK, dto.Resp{
// Code: http.StatusOK,
// Msg: "success",
// Data: "register success",)
}
func Login(ctx *gin.Context) {
// 登录
} }
...@@ -50,6 +50,7 @@ require ( ...@@ -50,6 +50,7 @@ require (
github.com/spf13/cast v1.5.1 // indirect github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.5.1 // indirect
github.com/subosito/gotenv v1.4.2 // indirect github.com/subosito/gotenv v1.4.2 // indirect
github.com/swaggo/swag v1.16.1 // indirect github.com/swaggo/swag v1.16.1 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
......
package main
import (
"fmt"
"io"
"net/http"
"testing"
"time"
)
func TestMyController(t *testing.T) {
// 创建一个新的HTTP服务器,用于处理请求
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
server := &http.Server{Addr: ":8080", Handler: mux}
// 启动HTTP服务器
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
t.Errorf("Error starting server: %v", err)
}
}()
// 等待服务器启动
time.Sleep(1 * time.Second)
// 创建一个HTTP客户端
client := &http.Client{
Timeout: 5 * time.Second,
}
// 发送一个GET请求到服务器
resp, err := client.Get("http://localhost:8080")
if err != nil {
t.Errorf("Error sending request: %v", err)
return
}
defer resp.Body.Close()
// 发送一个POST请求到服务器
resp, err = client.Post("http://localhost:8080", "application/json", nil)
if err != nil {
t.Errorf("Error sending request: %v", err)
return
}
defer resp.Body.Close()
// 检查响应是否成功
if resp.StatusCode != http.StatusOK {
t.Errorf("Unexpected status code: %d", resp.StatusCode)
return
}
// 读取响应内容
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("Error reading response body: %v", err)
return
}
// 检查响应内容是否正确
expected := "Hello, World!"
if string(body) != expected {
t.Errorf("Unexpected response body: %s", string(body))
return
}
// 关闭HTTP服务器
server.Close()
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment