Skip to content

BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr

Add the general API response middleware. Optimize the general response data structure.

Jacka809ddef2546
diff --git a/core/api/dockerapi/dockerapi.go b/core/api/dockerapi/dockerapi.go
new file mode 100644
index 00000000..65dbdb7b
--- /dev/null
+++ b/core/api/dockerapi/dockerapi.go
@@ -0,0 +1,17 @@
+// =================================================================================
+// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
+// =================================================================================
+
+package dockerapi
+
+import (
+ "context"
+
+ "billionmail-core/api/dockerapi/v1"
+)
+
+type IDockerapiV1 interface {
+ ListContainer(ctx context.Context, req *v1.ListContainerReq) (res *v1.ListContainerRes, err error)
+ ContainerState(ctx context.Context, req *v1.ContainerStateReq) (res *v1.ContainerStateRes, err error)
+ RestartContainer(ctx context.Context, req *v1.RestartContainerReq) (res *v1.RestartContainerRes, err error)
+}
diff --git a/core/api/dockerapi/v1/dockerapi.go b/core/api/dockerapi/v1/dockerapi.go
new file mode 100644
index 00000000..87e2bff7
--- /dev/null
+++ b/core/api/dockerapi/v1/dockerapi.go
@@ -0,0 +1,113 @@
+package v1
+
+import (
+ "billionmail-core/utility/types/api_v1"
+ "github.com/docker/docker/api/types/container"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+// ContainerStats container status struct
+type ContainerStats struct {
+ CPU float64 `json:"cpu_percent"`
+ Memory float64 `json:"memory_percent"`
+ MemoryMB float64 `json:"memory_mb"`
+ NetIO struct {
+ In float64 `json:"in"`
+ Out float64 `json:"out"`
+ } `json:"net_io"`
+ BlockIO struct {
+ In float64 `json:"in"`
+ Out float64 `json:"out"`
+ } `json:"block_io"`
+}
+
+// DockerStatsJSON container statistics JSON struct
+type DockerStatsJSON struct {
+ CPUStats struct {
+ CPUUsage struct {
+ TotalUsage uint64 `json:"total_usage"`
+ PercpuUsage []uint64 `json:"percpu_usage"`
+ UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
+ UsageInUsermode uint64 `json:"usage_in_usermode"`
+ } `json:"cpu_usage"`
+ SystemUsage uint64 `json:"system_usage"`
+ OnlineCPUs uint32 `json:"online_cpus"`
+ ThrottlingData struct {
+ Periods uint64 `json:"periods"`
+ ThrottledPeriods uint64 `json:"throttled_periods"`
+ ThrottledTime uint64 `json:"throttled_time"`
+ } `json:"throttling_data"`
+ } `json:"cpu_stats"`
+ PreCPUStats struct {
+ CPUUsage struct {
+ TotalUsage uint64 `json:"total_usage"`
+ PercpuUsage []uint64 `json:"percpu_usage"`
+ UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
+ UsageInUsermode uint64 `json:"usage_in_usermode"`
+ } `json:"cpu_usage"`
+ SystemUsage uint64 `json:"system_usage"`
+ OnlineCPUs uint32 `json:"online_cpus"`
+ ThrottlingData struct {
+ Periods uint64 `json:"periods"`
+ ThrottledPeriods uint64 `json:"throttled_periods"`
+ ThrottledTime uint64 `json:"throttled_time"`
+ } `json:"throttling_data"`
+ } `json:"precpu_stats"`
+ MemoryStats struct {
+ Usage uint64 `json:"usage"`
+ MaxUsage uint64 `json:"max_usage"`
+ Limit uint64 `json:"limit"`
+ } `json:"memory_stats"`
+ Networks map[string]struct {
+ RxBytes uint64 `json:"rx_bytes"`
+ RxPackets uint64 `json:"rx_packets"`
+ RxErrors uint64 `json:"rx_errors"`
+ RxDropped uint64 `json:"rx_dropped"`
+ TxBytes uint64 `json:"tx_bytes"`
+ TxPackets uint64 `json:"tx_packets"`
+ TxErrors uint64 `json:"tx_errors"`
+ TxDropped uint64 `json:"tx_dropped"`
+ } `json:"networks"`
+ BlkioStats struct {
+ IoServiceBytesRecursive []struct {
+ Major uint64 `json:"major"`
+ Minor uint64 `json:"minor"`
+ Op string `json:"op"`
+ Value uint64 `json:"value"`
+ } `json:"io_service_bytes_recursive"`
+ } `json:"blkio_stats"`
+}
+
+// ExecResult execution result
+type ExecResult struct {
+ ExitCode int `json:"exit_code"`
+ Output string `json:"output"`
+}
+
+type ListContainerReq struct {
+ g.Meta `path:"/docker_api/list" tags:"DockerApi" method:"get" summary:"list containers"`
+}
+
+type ListContainerRes struct {
+ api_v1.StandardRes
+ Data []container.Summary `json:"data"`
+}
+
+type ContainerStateReq struct {
+ g.Meta `path:"/docker_api/state" tags:"DockerApi" method:"get" summary:"get container status"`
+ ContainerID string `json:"container_id" v:"required|min-length:1" dc:"Container ID" dc:"Container ID"`
+}
+
+type ContainerStateRes struct {
+ api_v1.StandardRes
+ Data *ContainerStats `json:"data"`
+}
+
+type RestartContainerReq struct {
+ g.Meta `path:"/docker_api/restart" tags:"DockerApi" method:"post" summary:"restart container"`
+ ContainerID string `json:"container_id" v:"required|min-length:1" dc:"Container ID" dc:"Container ID"`
+}
+
+type RestartContainerRes struct {
+ api_v1.StandardRes
+}
diff --git a/core/api/settings/settings.go b/core/api/settings/settings.go
deleted file mode 100644
index 33106513..00000000
--- a/core/api/settings/settings.go
+++ /dev/null
@@ -1,16 +0,0 @@
-// =================================================================================
-// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
-// =================================================================================
-
-package settings
-
-import (
- "context"
-
- "billionmail-core/api/settings/v1"
-)
-
-type ISettingsV1 interface {
- Status(ctx context.Context, req *v1.StatusReq) (res *v1.StatusRes, err error)
- Restart(ctx context.Context, req *v1.RestartReq) (res *v1.RestartRes, err error)
-}
diff --git a/core/api/settings/v1/dockerapi.go b/core/api/settings/v1/dockerapi.go
deleted file mode 100644
index 0eacdd0d..00000000
--- a/core/api/settings/v1/dockerapi.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package v1
-
-import (
- "billionmail-core/utility/types/api_v1"
- "github.com/gogf/gf/v2/frame/g"
-)
-
-type StatusReq struct {
- g.Meta `path:"/status" tags:"DockerApi" method:"get" summary:"get container status"`
- Name string `json:"name" v:"required|min-length:1" dc:"Name" dc:"Container name"`
-}
-
-type StatusRes struct {
- api_v1.StandardRes
-}
-
-type RestartReq struct {
- g.Meta `path:"/restart" tags:"DockerApi" method:"post" summary:"restart container"`
- Name string `json:"name" v:"required|min-length:1" dc:"Name" dc:"Container name"`
-}
-
-type RestartRes struct {
- api_v1.StandardRes
-}
diff --git a/core/internal/cmd/cmd.go b/core/internal/cmd/cmd.go
index 4dc126e8..6348e2aa 100644
--- a/core/internal/cmd/cmd.go
+++ b/core/internal/cmd/cmd.go
@@ -3,13 +3,14 @@ package cmd
import (
"billionmail-core/internal/consts"
"billionmail-core/internal/controller/account"
+ "billionmail-core/internal/controller/dockerapi"
"billionmail-core/internal/controller/domains"
"billionmail-core/internal/controller/mail_boxes"
"billionmail-core/internal/controller/overview"
- "billionmail-core/internal/controller/settings"
"billionmail-core/internal/service/database_initialization"
+ docker "billionmail-core/internal/service/dockerapi"
+ "billionmail-core/internal/service/middlewares"
"billionmail-core/internal/service/phpfpm"
- "billionmail-core/internal/service/public"
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
@@ -30,15 +31,33 @@ var (
return err
}
+ dk, err := docker.NewDockerAPI()
+
+ if err != nil {
+ glog.Error(ctx, err)
+ return err
+ }
+
+ defer dk.Close()
+
s := g.Server(consts.DEFAULT_SERVER_NAME)
- s.Group("/", func(group *ghttp.RouterGroup) {
- group.Middleware(ghttp.MiddlewareHandlerResponse)
+
+ s.Group("/api", func(group *ghttp.RouterGroup) {
+ group.Middleware(func(r *ghttp.Request) {
+ r.SetCtxVar(consts.DEFAULT_DOCKER_CLIENT_CTX_KEY, dk)
+ r.Middleware.Next()
+ })
+
+ // group.Middleware(ghttp.MiddlewareHandlerResponse)
+
+ group.Middleware(middlewares.HandleApiResponse)
+
group.Bind(
account.NewV1(),
domains.NewV1(),
mail_boxes.NewV1(),
overview.NewV1(),
- settings.NewV1(),
+ dockerapi.NewV1(),
)
})
@@ -50,10 +69,6 @@ var (
Static: consts.ROUNDCUBE_ROOT_PATH,
}))
- res, err := public.M("mailbox").All()
-
- glog.Debug(context.Background(), res, err)
-
s.Run()
return nil
},
diff --git a/core/internal/consts/consts.go b/core/internal/consts/consts.go
index 26f7322b..07e55bb2 100644
--- a/core/internal/consts/consts.go
+++ b/core/internal/consts/consts.go
@@ -7,4 +7,5 @@ const (
ROUNDCUBE_ROOT_PATH = "../webmail-data"
ROUNDCUBE_ROOT_PATH_IN_CONTAINER = "/var/www/html"
POSTGRESQL_SOCK = "../postgresql-socket"
+ DEFAULT_DOCKER_CLIENT_CTX_KEY = "dockerapi"
)
diff --git a/core/internal/controller/settings/settings.go b/core/internal/controller/dockerapi/dockerapi.go
similarity index 93%
rename from core/internal/controller/settings/settings.go
rename to core/internal/controller/dockerapi/dockerapi.go
index 0ebe6674..67bce0b7 100644
--- a/core/internal/controller/settings/settings.go
+++ b/core/internal/controller/dockerapi/dockerapi.go
@@ -2,4 +2,4 @@
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
-package settings
+package dockerapi
diff --git a/core/internal/controller/settings/settings_new.go b/core/internal/controller/dockerapi/dockerapi_new.go
similarity index 78%
rename from core/internal/controller/settings/settings_new.go
rename to core/internal/controller/dockerapi/dockerapi_new.go
index 064915f3..d5001690 100644
--- a/core/internal/controller/settings/settings_new.go
+++ b/core/internal/controller/dockerapi/dockerapi_new.go
@@ -2,14 +2,14 @@
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
-package settings
+package dockerapi
import (
- "billionmail-core/api/settings"
+ "billionmail-core/api/dockerapi"
)
type ControllerV1 struct{}
-func NewV1() settings.ISettingsV1 {
+func NewV1() dockerapi.IDockerapiV1 {
return &ControllerV1{}
}
diff --git a/core/internal/controller/dockerapi/dockerapi_v1_container_state.go b/core/internal/controller/dockerapi/dockerapi_v1_container_state.go
new file mode 100644
index 00000000..959ce137
--- /dev/null
+++ b/core/internal/controller/dockerapi/dockerapi_v1_container_state.go
@@ -0,0 +1,18 @@
+package dockerapi
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+
+ "billionmail-core/api/dockerapi/v1"
+)
+
+func (c *ControllerV1) ContainerState(ctx context.Context, req *v1.ContainerStateReq) (res *v1.ContainerStateRes, err error) {
+ res = &v1.ContainerStateRes{}
+
+ res.Data, err = public.DockerApiFromCtx(ctx).GetContainerStats(ctx, req.ContainerID)
+
+ res.SetSuccess("Success")
+
+ return
+}
diff --git a/core/internal/controller/dockerapi/dockerapi_v1_list_container.go b/core/internal/controller/dockerapi/dockerapi_v1_list_container.go
new file mode 100644
index 00000000..8ddaa127
--- /dev/null
+++ b/core/internal/controller/dockerapi/dockerapi_v1_list_container.go
@@ -0,0 +1,24 @@
+package dockerapi
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/errors/gcode"
+ "github.com/gogf/gf/v2/errors/gerror"
+
+ "billionmail-core/api/dockerapi/v1"
+)
+
+func (c *ControllerV1) ListContainer(ctx context.Context, req *v1.ListContainerReq) (res *v1.ListContainerRes, err error) {
+ res = &v1.ListContainerRes{}
+
+ res.Data, err = public.DockerApiFromCtx(ctx).ListContainers(ctx)
+
+ if err != nil {
+ return nil, gerror.NewCode(gcode.CodeNotFound, "获取容器列表失败")
+ }
+
+ res.SetSuccess("Success")
+
+ return
+}
diff --git a/core/internal/controller/dockerapi/dockerapi_v1_restart_container.go b/core/internal/controller/dockerapi/dockerapi_v1_restart_container.go
new file mode 100644
index 00000000..d78bf56e
--- /dev/null
+++ b/core/internal/controller/dockerapi/dockerapi_v1_restart_container.go
@@ -0,0 +1,23 @@
+package dockerapi
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+
+ "billionmail-core/api/dockerapi/v1"
+)
+
+func (c *ControllerV1) RestartContainer(ctx context.Context, req *v1.RestartContainerReq) (res *v1.RestartContainerRes, err error) {
+ res = &v1.RestartContainerRes{}
+
+ err = public.DockerApiFromCtx(ctx).RestartContainer(ctx, req.ContainerID)
+
+ if err != nil {
+ res.SetError(err)
+ return
+ }
+
+ res.SetSuccess("Success")
+
+ return
+}
diff --git a/core/internal/controller/settings/settings_v1_restart.go b/core/internal/controller/settings/settings_v1_restart.go
deleted file mode 100644
index 456ab2ad..00000000
--- a/core/internal/controller/settings/settings_v1_restart.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package settings
-
-import (
- "context"
-
- "github.com/gogf/gf/v2/errors/gcode"
- "github.com/gogf/gf/v2/errors/gerror"
-
- "billionmail-core/api/settings/v1"
-)
-
-func (c *ControllerV1) Restart(ctx context.Context, req *v1.RestartReq) (res *v1.RestartRes, err error) {
- return nil, gerror.NewCode(gcode.CodeNotImplemented)
-}
diff --git a/core/internal/controller/settings/settings_v1_status.go b/core/internal/controller/settings/settings_v1_status.go
deleted file mode 100644
index 04449326..00000000
--- a/core/internal/controller/settings/settings_v1_status.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package settings
-
-import (
- "context"
-
- "github.com/gogf/gf/v2/errors/gcode"
- "github.com/gogf/gf/v2/errors/gerror"
-
- "billionmail-core/api/settings/v1"
-)
-
-func (c *ControllerV1) Status(ctx context.Context, req *v1.StatusReq) (res *v1.StatusRes, err error) {
- return nil, gerror.NewCode(gcode.CodeNotImplemented)
-}
diff --git a/core/internal/service/dockerapi/dockerapi.go b/core/internal/service/dockerapi/dockerapi.go
index ba2f4297..cdcd301e 100644
--- a/core/internal/service/dockerapi/dockerapi.go
+++ b/core/internal/service/dockerapi/dockerapi.go
@@ -1,6 +1,7 @@
package docker
import (
+ v1 "billionmail-core/api/dockerapi/v1"
"context"
"encoding/json"
"fmt"
@@ -33,12 +34,6 @@ func NewDockerAPI() (*DockerAPI, error) {
}, nil
}
-// ContainerAction container operation type
-type ContainerAction struct {
- ContainerID string
- Action string
-}
-
// StartContainer starts a container
func (d *DockerAPI) StartContainer(ctx context.Context, containerID string) error {
return d.client.ContainerStart(ctx, containerID, container.StartOptions{})
@@ -60,87 +55,15 @@ func (d *DockerAPI) RestartContainer(ctx context.Context, containerID string) er
})
}
-// ContainerStats container status struct
-type ContainerStats struct {
- CPU float64 `json:"cpu_percent"`
- Memory float64 `json:"memory_percent"`
- MemoryMB float64 `json:"memory_mb"`
- NetIO struct {
- In float64 `json:"in"`
- Out float64 `json:"out"`
- } `json:"net_io"`
- BlockIO struct {
- In float64 `json:"in"`
- Out float64 `json:"out"`
- } `json:"block_io"`
-}
-
-// DockerStatsJSON container statistics JSON struct
-type DockerStatsJSON struct {
- CPUStats struct {
- CPUUsage struct {
- TotalUsage uint64 `json:"total_usage"`
- PercpuUsage []uint64 `json:"percpu_usage"`
- UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
- UsageInUsermode uint64 `json:"usage_in_usermode"`
- } `json:"cpu_usage"`
- SystemUsage uint64 `json:"system_usage"`
- OnlineCPUs uint32 `json:"online_cpus"`
- ThrottlingData struct {
- Periods uint64 `json:"periods"`
- ThrottledPeriods uint64 `json:"throttled_periods"`
- ThrottledTime uint64 `json:"throttled_time"`
- } `json:"throttling_data"`
- } `json:"cpu_stats"`
- PreCPUStats struct {
- CPUUsage struct {
- TotalUsage uint64 `json:"total_usage"`
- PercpuUsage []uint64 `json:"percpu_usage"`
- UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
- UsageInUsermode uint64 `json:"usage_in_usermode"`
- } `json:"cpu_usage"`
- SystemUsage uint64 `json:"system_usage"`
- OnlineCPUs uint32 `json:"online_cpus"`
- ThrottlingData struct {
- Periods uint64 `json:"periods"`
- ThrottledPeriods uint64 `json:"throttled_periods"`
- ThrottledTime uint64 `json:"throttled_time"`
- } `json:"throttling_data"`
- } `json:"precpu_stats"`
- MemoryStats struct {
- Usage uint64 `json:"usage"`
- MaxUsage uint64 `json:"max_usage"`
- Limit uint64 `json:"limit"`
- } `json:"memory_stats"`
- Networks map[string]struct {
- RxBytes uint64 `json:"rx_bytes"`
- RxPackets uint64 `json:"rx_packets"`
- RxErrors uint64 `json:"rx_errors"`
- RxDropped uint64 `json:"rx_dropped"`
- TxBytes uint64 `json:"tx_bytes"`
- TxPackets uint64 `json:"tx_packets"`
- TxErrors uint64 `json:"tx_errors"`
- TxDropped uint64 `json:"tx_dropped"`
- } `json:"networks"`
- BlkioStats struct {
- IoServiceBytesRecursive []struct {
- Major uint64 `json:"major"`
- Minor uint64 `json:"minor"`
- Op string `json:"op"`
- Value uint64 `json:"value"`
- } `json:"io_service_bytes_recursive"`
- } `json:"blkio_stats"`
-}
-
// GetContainerStats gets container status
-func (d *DockerAPI) GetContainerStats(ctx context.Context, containerID string) (*ContainerStats, error) {
+func (d *DockerAPI) GetContainerStats(ctx context.Context, containerID string) (*v1.ContainerStats, error) {
stats, err := d.client.ContainerStats(ctx, containerID, false)
if err != nil {
return nil, err
}
defer stats.Body.Close()
- var statsJSON DockerStatsJSON
+ var statsJSON v1.DockerStatsJSON
if err := json.NewDecoder(stats.Body).Decode(&statsJSON); err != nil {
return nil, err
}
@@ -170,7 +93,7 @@ func (d *DockerAPI) GetContainerStats(ctx context.Context, containerID string) (
}
}
- return &ContainerStats{
+ return &v1.ContainerStats{
CPU: cpuPercent,
Memory: memoryPercent,
MemoryMB: memoryMB,
@@ -192,7 +115,7 @@ func (d *DockerAPI) GetContainerStats(ctx context.Context, containerID string) (
}
// Calculate CPU usage percentage
-func calculateCPUPercentUnix(stats DockerStatsJSON) float64 {
+func calculateCPUPercentUnix(stats v1.DockerStatsJSON) float64 {
cpuPercent := 0.0
// Calculate CPU usage
cpuDelta := float64(stats.CPUStats.CPUUsage.TotalUsage) - float64(stats.PreCPUStats.CPUUsage.TotalUsage)
@@ -204,14 +127,8 @@ func calculateCPUPercentUnix(stats DockerStatsJSON) float64 {
return cpuPercent
}
-// ExecResult execution result
-type ExecResult struct {
- ExitCode int `json:"exit_code"`
- Output string `json:"output"`
-}
-
// ExecCommand executes a command in a container
-func (d *DockerAPI) ExecCommand(ctx context.Context, containerID string, cmd []string, user string) (*ExecResult, error) {
+func (d *DockerAPI) ExecCommand(ctx context.Context, containerID string, cmd []string, user string) (*v1.ExecResult, error) {
execConfig := container.ExecOptions{
Cmd: cmd,
User: user,
@@ -252,7 +169,7 @@ func (d *DockerAPI) ExecCommand(ctx context.Context, containerID string, cmd []s
output += errBuf.String()
}
- return &ExecResult{
+ return &v1.ExecResult{
ExitCode: inspect.ExitCode,
Output: output,
}, nil
diff --git a/core/internal/service/middlewares/HandleApiResponse.go b/core/internal/service/middlewares/HandleApiResponse.go
new file mode 100644
index 00000000..bb2e2c83
--- /dev/null
+++ b/core/internal/service/middlewares/HandleApiResponse.go
@@ -0,0 +1,60 @@
+package middlewares
+
+import (
+ "billionmail-core/internal/service/public"
+ "billionmail-core/utility/types/api_v1"
+ "github.com/gogf/gf/util/gvalid"
+ "github.com/gogf/gf/v2/net/ghttp"
+ "strings"
+)
+
+func HandleApiResponse(r *ghttp.Request) {
+ r.Middleware.Next()
+
+ // If the request has been exited, do nothing.
+ if r.Response.BufferLength() > 0 {
+ return
+ }
+
+ // Handle the error if it exists.
+ if r.GetError() != nil {
+ // Clear the response buffer.
+ r.Response.ClearBuffer()
+
+ // Catch validation errors and respond with 412.
+ if v, ok := r.GetError().(gvalid.Error); ok {
+ errorStr := v.Error()
+ errorLen := len(errorStr)
+ // If the error message is in the format Lang{xxx}, convert it to the corresponding language.
+ if strings.Contains(errorStr, "Lang{") && errorStr[errorLen-1] == '}' {
+ errorStr = errorStr[5 : errorLen-1]
+ errorStr = public.LangCtx(r.Context(), errorStr)
+ }
+
+ r.Response.WriteJson(api_v1.StandardRes{
+ Success: false,
+ Code: 412,
+ Msg: errorStr,
+ })
+
+ return
+ }
+
+ // Respond with 500 error.
+ r.Response.WriteJson(api_v1.StandardRes{
+ Success: false,
+ Code: 500,
+ Msg: r.GetError().Error(),
+ })
+
+ return
+ }
+
+ // Get the response data.
+ resp := r.GetHandlerResponse()
+
+ // Respond with the data if it exists.
+ if resp != nil {
+ r.Response.WriteJson(resp)
+ }
+}
diff --git a/core/internal/service/public/common.go b/core/internal/service/public/common.go
index 0b327c11..cca4b0be 100644
--- a/core/internal/service/public/common.go
+++ b/core/internal/service/public/common.go
@@ -1,6 +1,8 @@
package public
import (
+ docker "billionmail-core/internal/service/dockerapi"
+ "billionmail-core/utility/types/api_v1"
"bufio"
"context"
"crypto/md5"
@@ -53,29 +55,12 @@ type CodeStatus struct {
ErrorMsg string
}
-type StandardRes struct {
- g.Meta `mime:"application/json"`
- Status bool `json:"status" description:"Status"`
- Code int `json:"code" description:"Status code"`
- Msg string `json:"msg" description:"Message"`
- ErrorMsg string `json:"error_msg" description:"Error message"`
- Message interface{} `json:"message" description:"Data"`
-}
-
type AccountSession struct {
Username string `json:"username" description:"username"`
AccountId int `json:"account_id" description:"Account ID"`
Email string `json:"email" description:"Email"`
}
-type ReturnData struct {
- Status int `json:"status" description:"状态 0:成功 -1:失败"`
- Code int `json:"code" description:"状态码,请参考CodeMap"`
- Msg string `json:"msg" description:"提示信息"`
- ErrorMsg string `json:"error_msg" description:"错误信息"`
- Message interface{} `json:"message" description:"数据"`
-}
-
type DefaultYamlConfig struct {
Server struct {
Address string `yaml:"address"`
@@ -263,7 +248,7 @@ func MR(db string, table string) *gdb.Model {
}
// Respond with JSON
-func ReturnJson(ctx context.Context, data ReturnData) {
+func ReturnJson(ctx context.Context, data api_v1.StandardRes) {
jsonStr, _ := json.Marshal(data)
// Respond with JSON and immediately exit the goroutine, terminating subsequent code execution
@@ -271,62 +256,13 @@ func ReturnJson(ctx context.Context, data ReturnData) {
}
// Respond with JSON
-func Json(ctx context.Context, data ReturnData) {
+func Json(ctx context.Context, data api_v1.StandardRes) {
ReturnJson(ctx, data)
}
// Default response
-func ReturnDefault(data interface{}) ReturnData {
- return ReturnData{Status: 0, Code: 200, Msg: "ok", Message: data}
-}
-
-// Response with text
-func ReturnText(ctx context.Context, data string) {
- g.RequestFromCtx(ctx).Response.Write(data)
-}
-
-// Standard response
-func Return(ctx context.Context, status bool, code int, msg string, data interface{}, error_msg string) {
- int_status := 0
- if !status {
- int_status = -1
- }
-
- rdata := ReturnData{}
- rdata.Status = int_status
- rdata.Code = code
- rdata.Msg = msg
- rdata.ErrorMsg = error_msg
- rdata.Message = data
- if rdata.Msg == "" {
- rdata.Msg = error_msg
- }
-
- ReturnJson(ctx, rdata)
-}
-
-// Standard response -- success
-func Success(ctx context.Context, msg string, data ...interface{}) {
- length := len(data)
- error_msg := ""
- switch length {
- case 0:
- Return(ctx, true, 200, msg, nil, error_msg)
- case 1:
- Return(ctx, true, 200, msg, data[0], error_msg)
- default:
- Return(ctx, true, 200, msg, data, error_msg)
- }
-}
-
-// Standard response -- failure
-func Error(ctx context.Context, msg string, error_msg string) {
- Return(ctx, false, 500, msg, nil, error_msg)
-}
-
-// Response based on status code
-func ReturnCode(ctx context.Context, code int, data interface{}) {
- Return(ctx, CodeMap[code].Status, code, CodeMap[code].Msg, data, CodeMap[code].ErrorMsg)
+func ReturnDefault(data interface{}) api_v1.StandardRes {
+ return api_v1.StandardRes{Success: false, Code: 200, Msg: "ok", Data: data}
}
// Get HTTP client object
@@ -2288,3 +2224,8 @@ func ReloadFirewall() (err error) {
return
}
+
+// DockerApiFromCtx Get Docker API from context
+func DockerApiFromCtx(ctx context.Context) *docker.DockerAPI {
+ return ctx.Value(consts.DEFAULT_DOCKER_CLIENT_CTX_KEY).(*docker.DockerAPI)
+}
diff --git a/core/utility/types/api_v1/common.go b/core/utility/types/api_v1/common.go
index 8f15960e..3082aa7d 100644
--- a/core/utility/types/api_v1/common.go
+++ b/core/utility/types/api_v1/common.go
@@ -4,16 +4,27 @@
package api_v1
-import "github.com/gogf/gf/v2/frame/g"
+import (
+ "github.com/gogf/gf/v2/frame/g"
+)
// StandardRes response format
type StandardRes struct {
- g.Meta `mime:"application/json"`
- Success bool `json:"success"`
- Code int `json:"code"`
- Msg string `json:"msg" dc:"Success message"`
- ErrorMsg string `json:"error_msg" dc:"Error message"`
- Data interface{} `json:"data"`
+ g.Meta `mime:"application/json"`
+ Success bool `json:"success"`
+ Code int `json:"code"`
+ Msg string `json:"msg" dc:"Success message"`
+ Data interface{} `json:"data"`
+}
+
+func (resp *StandardRes) SetSuccess(msg string) {
+ resp.Success = true
+ resp.Msg = msg
+}
+
+func (resp *StandardRes) SetError(err error) {
+ resp.Success = false
+ resp.Msg = err.Error()
}
// StandardDownloadRes download response format