mirror of
https://github.com/kataras/iris.git
synced 2025-12-23 04:47:02 +00:00
first release of SSO package and more examples
This commit is contained in:
@@ -1,15 +1,15 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
stdContext "context"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/kataras/iris/v12"
|
||||
"github.com/kataras/iris/v12/httptest"
|
||||
)
|
||||
|
||||
var defaultCtx = stdContext.Background()
|
||||
var defaultCtx = context.Background()
|
||||
|
||||
type testValue struct {
|
||||
Firstname string `json:"firstname"`
|
||||
@@ -18,40 +18,41 @@ type testValue struct {
|
||||
func TestClientJSON(t *testing.T) {
|
||||
expectedJSON := testValue{Firstname: "Makis"}
|
||||
|
||||
app := iris.New()
|
||||
app.Get("/", sendJSON(t, expectedJSON))
|
||||
app := http.NewServeMux()
|
||||
app.HandleFunc("/send", sendJSON(t, expectedJSON))
|
||||
|
||||
var irisGotJSON testValue
|
||||
app.Post("/", readJSON(t, &irisGotJSON, &expectedJSON))
|
||||
app.HandleFunc("/read", readJSON(t, &irisGotJSON, &expectedJSON))
|
||||
|
||||
srv := httptest.NewServer(t, app)
|
||||
srv := httptest.NewServer(app)
|
||||
client := New(BaseURL(srv.URL))
|
||||
|
||||
// Test ReadJSON (read from server).
|
||||
var got testValue
|
||||
if err := client.ReadJSON(defaultCtx, &got, iris.MethodGet, "/", nil); err != nil {
|
||||
if err := client.ReadJSON(defaultCtx, &got, http.MethodGet, "/send", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Test JSON (send to server).
|
||||
resp, err := client.JSON(defaultCtx, iris.MethodPost, "/", expectedJSON)
|
||||
resp, err := client.JSON(defaultCtx, http.MethodPost, "/read", expectedJSON)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client.DrainResponseBody(resp)
|
||||
}
|
||||
|
||||
func sendJSON(t *testing.T, v interface{}) iris.Handler {
|
||||
return func(ctx iris.Context) {
|
||||
if _, err := ctx.JSON(v); err != nil {
|
||||
func sendJSON(t *testing.T, v interface{}) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readJSON(t *testing.T, ptr interface{}, expected interface{}) iris.Handler {
|
||||
return func(ctx iris.Context) {
|
||||
if err := ctx.ReadJSON(ptr); err != nil {
|
||||
func readJSON(t *testing.T, ptr interface{}, expected interface{}) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := json.NewDecoder(r.Body).Decode(ptr); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user