Skip to content

Commit

Permalink
feat: tcp 响应处理
Browse files Browse the repository at this point in the history
  • Loading branch information
minibear2333 committed Jun 13, 2021
1 parent 572c950 commit 56eac52
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 3 deletions.
15 changes: 12 additions & 3 deletions internal/routers/api/v1/article.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
package v1

import "github.com/gin-gonic/gin"
import (
"github.com/gin-gonic/gin"
"github.com/golang-minibear2333/gin-blog/pkg/app"
"github.com/golang-minibear2333/gin-blog/pkg/errcode"
)

type Article struct{}

func NewArticle() Article {
return Article{}
}

func (a Article) Get(c *gin.Context) {}
func (a Article) List(c *gin.Context) {}
func (a Article) Get(c *gin.Context) {
}
func (a Article) List(c *gin.Context) {
// 接口测试 http://localhost:8000/api/v1/article
app.NewResponse(c).ToErrorResponse(errcode.ServerError)
return
}
func (a Article) Create(c *gin.Context) {}
func (a Article) Update(c *gin.Context) {}
func (a Article) Delete(c *gin.Context) {}
49 changes: 49 additions & 0 deletions pkg/app/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package app

import (
"github.com/gin-gonic/gin"
"github.com/golang-minibear2333/gin-blog/pkg/errcode"
"net/http"
)

type Response struct {
Ctx *gin.Context
}

type Pager struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
TotalRows int `json:"total_rows"`
}

func NewResponse(ctx *gin.Context) *Response {
return &Response{Ctx: ctx}
}

func (r *Response) ToResponse(data interface{}) {
if data == nil {
data = gin.H{}
}
r.Ctx.JSON(http.StatusOK, data)
}

func (r *Response) ToResponseList(list interface{}, totalRows int) {
r.Ctx.JSON(http.StatusOK, gin.H{
"list": list,
"pager": Pager{
Page: GetPage(r.Ctx),
PageSize: GetPageSize(r.Ctx),
TotalRows: totalRows,
},
})
}

func (r *Response) ToErrorResponse(err *errcode.Error) {
response := gin.H{"code": err.Code(), "msg": err.Msg()}
details := err.Details()
if len(details) > 0 {
response["details"] = details
}

r.Ctx.JSON(err.StatusCode(), response)
}

0 comments on commit 56eac52

Please sign in to comment.