github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/stub/README.MD (about)

     1  # STUB
     2  
     3  This package provides a set of utilities and helper methods to call a REST or RPC (over websocket)
     4  By using this package many of the boilerplate codes are not necessary anymore.
     5  
     6  REST example:
     7  
     8  ```go
     9  package main
    10  
    11  import (
    12  	"context"
    13  	"net/http"
    14  
    15  	"github.com/clubpay/ronykit/kit/stub"
    16  )
    17  
    18  func main() {
    19  	ctx := context.Background()
    20  	s := stub.New("webhook.site", stub.Secure())
    21  	httpCtx := s.REST().
    22  		SetMethod(http.MethodGet).
    23  		SetHeader("Content-Type", "application/json").
    24  		SetPath("/22fda9e7-1660-406e-b11e-993e070f175e").
    25  		SetQuery("someKey", "someValue").
    26  		Run(ctx)
    27  	defer httpCtx.Release()
    28  }
    29  
    30  ```
    31  
    32  ## REST
    33  ### Response Handler
    34  When you call a REST endpoint, you can use `SetResponseHandler` to handle the response.
    35  There are a few helper methods to write handlers for different response status codes.
    36  Also, you use `DefaultResponseHandler` to set a default handler for all status codes,
    37  which are not handled by other handlers.
    38  
    39  ```go
    40  package main
    41  
    42  import (
    43  	"context"
    44  
    45  	"github.com/clubpay/ronykit/kit"
    46  	"github.com/clubpay/ronykit/kit/stub"
    47  )
    48  
    49  type ErrorMessage struct {
    50  	Message string `json:"message"`
    51  }
    52  
    53  type SuccessMessage struct {
    54  	Message string `json:"message"`
    55  }
    56  
    57  func main() {
    58  	ctx := context.Background()
    59  	s := stub.New("webhook.site", stub.Secure())
    60  	httpCtx := s.REST().
    61  		POST("/someendPoint/slug1").
    62  		SetHeader("Content-Type", "application/json").
    63  		SetQuery("someKey", "someValue").
    64  		SetResponseHandler(
    65  			400,
    66  			func(ctx context.Context, r stub.RESTResponse) *stub.Error {
    67  				res := &ErrorMessage{}
    68  				err := stub.WrapError(kit.UnmarshalMessage(r.GetBody(), res))
    69  				if err != nil {
    70  					return err
    71  				}
    72  
    73  				return stub.NewErrorWithMsg(res)
    74  			},
    75  		).
    76  		DefaultResponseHandler(
    77  			func(ctx context.Context, r stub.RESTResponse) *stub.Error {
    78  				res := &SuccessMessage{}
    79  
    80  				return stub.WrapError(kit.UnmarshalMessage(r.GetBody(), res))
    81  			},
    82  		).
    83  		Run(ctx)
    84  	defer httpCtx.Release()
    85  
    86    if httpCtx.Error() != nil {
    87  		// handle error
    88  	}
    89  }
    90  
    91  
    92  ```