-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples_test.go
More file actions
55 lines (46 loc) · 1.6 KB
/
examples_test.go
File metadata and controls
55 lines (46 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package restapi_test
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"github.com/Arhius/restapi"
"github.com/gin-gonic/gin"
)
// Example_success shows how to write a successful JSON response.
func Example_success() {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
restapi.Success(c, http.StatusOK, map[string]string{"name": "alice"})
var body restapi.ResponseBody
_ = json.Unmarshal(w.Body.Bytes(), &body)
data := body.Data.(map[string]any)
fmt.Printf("status=%d name=%s\n", w.Code, data["name"])
// Output: status=200 name=alice
}
// ExampleAPI_Error shows how to write an error response that maps to an HTTP
// status via the registry.
func ExampleAPI_Error() {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
restapi.Default().Error(c, restapi.CodeNotFound, restapi.WithMessage("user not found"))
var body restapi.ResponseBody
_ = json.Unmarshal(w.Body.Bytes(), &body)
fmt.Printf("status=%d code=%d msg=%s\n", w.Code, body.Errors[0].Code, body.Errors[0].Message)
// Output: status=404 code=1003 msg=user not found
}
// Example_pagination shows using the offset pagination helpers.
func Example_pagination() {
req := restapi.OffsetPaginationRequest{Limit: 10, Offset: 20}
if err := req.Validate(); err != nil {
fmt.Println(err)
return
}
resp := req.Response(1000)
fmt.Printf("limit=%d offset=%d total=%d\n", resp.Limit, resp.Offset, resp.Total)
// Output: limit=10 offset=20 total=1000
}