rest

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2023 License: Apache-2.0 Imports: 18 Imported by: 0

README

rest

restful api Go HTTP client,like k8s client-go

Get Started

install

You first need Go installed (version 1.17+ is required), then you can use the below Go command to install req:

go get -u github.com/crochee/rest

Usage

Basic
package main

import (
    "context"
    "log"
    "net/http"

    "github.com/crochee/rest"
)

type Opts struct {
    Offset int `form:"offset"`
    Limit  int `form:"limit"`
}

func main() {
	var result struct {
		Content string `json:"content"`
	}
	if err := rest.Get().
        Endpoint("http://localhost:80").
        Prefix("v2").
        Resource("books").
        Query("limit", "20").
        Do(context.Background(), &result); err != nil {
            log.Println(err)
	}
    // curl 'http://localhost:80/v2/books?limit=20'

    if err := rest.Get().
    	Endpoint("http://localhost:80").
        Prefix("v2").
        Resource("books").
        Querys(Opts{Offset: 0, Limit: 20}).
        Do(context.Background(), &result); err != nil {
            log.Println(err)
	}
    // curl 'http://localhost:80/v2/books?limit=20'

    if err := rest.Post().
    	Endpoint("http://localhost:80").
        Prefix("v2").
        Resource("books").
        Body(map[string]interface{}{"name": "test"}]).
        Do(context.Background(), &result); err != nil {
            log.Println(err)
	}
    // curl -X POST 'http://localhost:80/v2/books' -d '{"name": "test"}'
}
Multiple

client.go

package main

import (
    "context"
    "log"
    "net/http"

    "github.com/crochee/rest"
)

type IClient interface {
	Area() AreaSrv
}

func NewGateway() IClient {
	return &baseClient{reqest.NewHandler().Endpoint("http://localhost:80")}
}

type baseClient struct {
	rest.Handler
}

func (c baseClient) Area() AreaSrv {
	return areaSrv{c.Resource("areas")}
}

type AreaSrv interface {
	Get(ctx context.Context, id string) (*Areas, error)
}

type areaSrv struct {
	rest.Handler
}

func (a areaSrv) Get(ctx context.Context, id string) (*Areas, error) {
	var result Areas
	if err := a.To().
		Get().
		Prefix("v2").
		Name(id).
		Do(ctx, &result); err != nil {
		return nil, err
	}
	return &result, nil
}

type Areas struct {
	List     []string `json:"list"`
	PageNum  int      `json:"page_num"`
	PageSize int      `json:"page_size"`
	Total    int      `json:"total"`
}

func main() {
	result, err := NewGateway().Area().Get(context.Background(), "12")
	if err != nil {
		log.Fatal(err)
	}
	log.Println(result)
}

Contributing

If you have a bug report or feature request, you can open an issue or pull request.

Documentation

Index

Constants

This section is empty.

Variables

DefaultTransport 默认配置的传输层实现

View Source
var NameMayNotBe = []string{".", ".."}

NameMayNotBe specifies strings that cannot be used as names specified as path segments (like the REST API or etcd store)

View Source
var NameMayNotContain = []string{"/", "%"}

NameMayNotContain specifies substrings that cannot be used in names specified as path segments (like the REST API or etcd store)

Functions

func ErrorFunc

func ErrorFunc(expectStatusCode int) func(*http.Response) error

func IsValidPathSegmentName

func IsValidPathSegmentName(name string) []string

IsValidPathSegmentName validates the name can be safely encoded as a path segment

func NewRESTClient

func NewRESTClient(transport Transport, method string) *restfulClient

NewRESTClient start to reqest

func OnRetryCondition

func OnRetryCondition(resp *http.Response, err error) bool

OnRetryCondition is a function to determine whether to retry

Types

type Handler

type Handler interface {
	Endpoint(endpoint string) Handler
	Resource(resource string) Handler
	To() Transport
}

func NewHandler

func NewHandler() Handler

type JsonRequest

type JsonRequest struct {
}

func (JsonRequest) Build

func (j JsonRequest) Build(ctx context.Context, method string, url string, body interface{}, headers http.Header) (*http.Request, error)

type JsonResponse

type JsonResponse struct {
}

func (JsonResponse) Parse

func (j JsonResponse) Parse(resp *http.Response, result interface{}, opts ...func(*http.Response) error) error

type Logger

type Logger interface {
	Debugf(format string, v ...interface{})
	Infof(format string, v ...interface{})
	Warnf(format string, v ...interface{})
	Errorf(format string, v ...interface{})
}

func Nop

func Nop(context.Context) Logger

type MockRoundTripper

type MockRoundTripper struct {
	// contains filtered or unexported fields
}

MockRoundTripper is a mock of RoundTripper interface.

func NewMockRoundTripper

func NewMockRoundTripper(ctrl *gomock.Controller) *MockRoundTripper

NewMockRoundTripper creates a new mock instance.

func (*MockRoundTripper) EXPECT

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockRoundTripper) RoundTrip

func (m *MockRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip mocks base method.

type MockRoundTripperMockRecorder

type MockRoundTripperMockRecorder struct {
	// contains filtered or unexported fields
}

MockRoundTripperMockRecorder is the mock recorder for MockBuildProcess.

func (*MockRoundTripperMockRecorder) RoundTrip

func (mr *MockRoundTripperMockRecorder) RoundTrip(req interface{}) *gomock.Call

RoundTrip indicates an expected call of RoundTrip.

type RESTClient

type RESTClient interface {
	// Endpoints  add  endpoints to the client
	Endpoints(endpoint string) RESTClient

	Prefix(segments ...string) RESTClient

	Suffix(segments ...string) RESTClient

	Resource(resource string) RESTClient

	Name(resourceName string) RESTClient

	SubResource(subResources ...string) RESTClient

	Query(key string, value ...string) RESTClient

	Querys(value interface{}) RESTClient

	Headers(header http.Header) RESTClient

	Header(key string, values ...string) RESTClient

	Body(obj interface{}) RESTClient

	Retry(backoff backoff.BackOff,
		shouldRetryFunc func(*http.Response, error) bool) RESTClient

	Do(ctx context.Context, result interface{}, opts ...func(*http.Response) error) error

	DoNop(ctx context.Context, opts ...func(*http.Response) error) error

	DoRaw(ctx context.Context) ([]byte, error)

	Stream(ctx context.Context) (io.ReadCloser, error)
}

func Delete

func Delete() RESTClient

func Get

func Get() RESTClient

func Method

func Method(method string) RESTClient

Method start to reqest

func Patch

func Patch() RESTClient

func Post

func Post() RESTClient

func Put

func Put() RESTClient

type Requester

type Requester interface {
	Build(ctx context.Context, method, url string, body interface{}, headers http.Header) (*http.Request, error)
}

type Response

type Response interface {
	Parse(resp *http.Response, result interface{}, opts ...func(*http.Response) error) error
}

type Transport

type Transport interface {
	http.RoundTripper
	WithRequest(requester Requester) Transport
	WithClient(roundTripper http.RoundTripper) Transport
	WithResponse(response Response) Transport

	Request() Requester
	Response() Response
	Client() http.RoundTripper

	Method(string) RESTClient
}

func NewTransporter

func NewTransporter(req Requester, roundTripper http.RoundTripper, resp Response) Transport

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL