OSDN Git Service

add list chains api (#389)
[bytom/vapor.git] / toolbar / federation / api / response.go
1 package api
2
3 import (
4         "fmt"
5         "net/http"
6         "strings"
7
8         "github.com/gin-gonic/gin"
9         log "github.com/sirupsen/logrus"
10 )
11
12 // response describes the response standard. Code & Msg are always present.
13 // Data is present for a success response only.
14 type response struct {
15         Code   int                    `json:"code"`
16         Msg    string                 `json:"msg"`
17         Result map[string]interface{} `json:"result,omitempty"`
18 }
19
20 func respondErrorResp(c *gin.Context, err error) {
21         log.WithFields(log.Fields{
22                 "url":     c.Request.URL,
23                 "request": c.Value(reqBodyLabel),
24                 "err":     err,
25         }).Error("request fail")
26         resp := formatErrResp(err)
27         c.AbortWithStatusJSON(http.StatusOK, resp)
28 }
29
30 func respondSuccessResp(c *gin.Context, data interface{}) {
31         result := make(map[string]interface{})
32         result["data"] = data
33         c.AbortWithStatusJSON(http.StatusOK, response{Code: 200, Result: result})
34 }
35
36 type links struct {
37         Next string `json:"next,omitempty"`
38 }
39
40 func respondSuccessPaginationResp(c *gin.Context, data interface{}, paginationInfo *PaginationInfo) {
41         url := fmt.Sprintf("%v", c.Request.URL)
42         base := strings.Split(url, "?")[0]
43         start := paginationInfo.Start
44         limit := paginationInfo.Limit
45
46         l := links{}
47         if paginationInfo.HasNext {
48                 // To efficiently build a string using Write methods
49                 // https://stackoverflow.com/questions/1760757/how-to-efficiently-concatenate-strings-in-go
50                 // https://tip.golang.org/pkg/strings/#Builder
51                 var b strings.Builder
52                 fmt.Fprintf(&b, "%s?limit=%d&start=%d", base, limit, start+limit)
53                 l.Next = b.String()
54         }
55         result := make(map[string]interface{})
56         result["data"] = data
57         result["start"] = start
58         result["limit"] = limit
59         result["_links"] = l
60
61         c.AbortWithStatusJSON(http.StatusOK, response{
62                 Code:   http.StatusOK,
63                 Result: result,
64         })
65 }