httpx

package
v0.0.0-...-bfab8ab Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2023 License: BSD-3-Clause Imports: 19 Imported by: 1

Documentation

Overview

Example (WriteStatusContent)
r := NewRecorder()

// No content
writeStatusContent[runtimetest.DebugError](r, runtime.NewStatusOK(), "test location")
r.Result().Header = r.Header()
buf, status := io2.ReadAll(r.Result().Body)
fmt.Printf("test: writeStatusContent() -> %v [header:%v] [body:%v] [ReadAll:%v]\n", r.Result().StatusCode, r.Result().Header, string(buf), status)

// Error message
r = NewRecorder()
writeStatusContent[runtimetest.DebugError](r, runtime.NewStatus(http.StatusInternalServerError).SetContent("error message", false), "test location")
r.Result().Header = r.Header()
buf, status = io2.ReadAll(r.Result().Body)
fmt.Printf("test: writeStatusContent() -> %v [header:%v] [body:%v] [ReadAll:%v]\n", r.Result().StatusCode, r.Result().Header, string(buf), status)

// Json
d := data{Item: "test item", Count: 500}
r = NewRecorder()
writeStatusContent[runtimetest.DebugError](r, runtime.NewStatus(http.StatusInternalServerError).SetContent(d, true), "test location")
r.Result().Header = r.Header()
buf, status = io2.ReadAll(r.Result().Body)
fmt.Printf("test: writeStatusContent() -> %v [header:%v] [body:%v] [ReadAll:%v]\n", r.Result().StatusCode, r.Result().Header, string(buf), status)
Output:

test: writeStatusContent() -> 200 [header:map[]] [body:] [ReadAll:OK]
test: writeStatusContent() -> 200 [header:map[Content-Length:[13] Content-Type:[text/plain; charset=utf-8]]] [body:error message] [ReadAll:OK]
test: writeStatusContent() -> 200 [header:map[Content-Length:[32] Content-Type:[application/json]]] [body:{"Item":"test item","Count":500}] [ReadAll:OK]

Index

Examples

Constants

View Source
const (
	ContentLocation = "Content-Location"
	ContentTypeText = "text/plain" // charset=utf-8
	ContentTypeJson = "application/json"
	ContentType     = "Content-Type"
	ContentLength   = "Content-Length"
)
View Source
const (
	SchemeName = "scheme"
	HostName   = "host"
	PathName   = "path"
	QueryName  = "query"
)
View Source
const (
	UrnScheme  = "urn"
	FileScheme = "file://"
)
View Source
const DefaultRemoteAddr = "1.2.3.4"

DefaultRemoteAddr is the default remote address to return in RemoteAddr if an explicit DefaultRemoteAddr isn't set on ResponseRecorder.

Variables

View Source
var (
	Client = http.DefaultClient
)
View Source
var (
	PkgUri = reflect.TypeOf(any(pkg{})).PkgPath()
)

Functions

func AddHeaders

func AddHeaders(req *http.Request, header http.Header)

func AddRequestId

func AddRequestId(req *http.Request) string

func AddResolver

func AddResolver(fn Resolver)

func BuildUrl

func BuildUrl(url *url.URL, template string) (*url.URL, error)

func CreateHeaders

func CreateHeaders(h http.Header, resp *http.Response, keys ...string)

func Deserialize

func Deserialize[T any](body io.ReadCloser) (T, *runtime.Status)

Deserialize - provide deserialization of a request/response body

Example
result, status := Deserialize[[]byte](nil)
fmt.Printf("test: Deserialize[[]byte](nil) -> [%v] [status:%v]\n", string(result), status)

resp := new(http.Response)
result, status = Deserialize[[]byte](resp.Body)
fmt.Printf("test: Deserialize[[]byte](resp) -> [%v] [status:%v]\n", string(result), status)

resp.Body = io.NopCloser(strings.NewReader("Hello World String"))
result, status = Deserialize[[]byte](resp.Body)
fmt.Printf("test: Deserialize[[]byte](resp) -> [%v] [status:%v]\n", string(result), status)

resp.Body = io.NopCloser(bytes.NewReader([]byte("Hello World []byte")))
result2, status2 := Deserialize[[]byte](resp.Body)
fmt.Printf("test: Deserialize[[]byte](resp) -> [%v] [status:%v]\n", string(result2), status2)
Output:

test: Deserialize[[]byte](nil) -> [] [status:Invalid Content [body is nil]]
test: Deserialize[[]byte](resp) -> [] [status:Invalid Content [body is nil]]
test: Deserialize[[]byte](resp) -> [Hello World String] [status:OK]
test: Deserialize[[]byte](resp) -> [Hello World []byte] [status:OK]

func Do

func Do(req *http.Request) (resp *http.Response, status *runtime.Status)

func DoT

func DoT[T any](req *http.Request) (resp *http.Response, t T, status *runtime.Status)

func GetContentLocation

func GetContentLocation(req *http.Request) string

func GetContentType

func GetContentType(headers any) string

func HeaderValue

func HeaderValue(name string, r *http.Request) string

func LookupUrl

func LookupUrl(name string, url *url.URL) (string, error)

func NewRequest

func NewRequest(ctx any, method, uri, variant string) (*http.Request, *runtime.Status)

func ParseRaw

func ParseRaw(rawUri string) *url.URL

ParseRaw - parse a raw Uri without error

func ParseUri

func ParseUri(uri string) (scheme, host, path string)

ParseUri - urn safe Uri parser

func ReadCookies

func ReadCookies(req *http.Request) map[string]*http.Cookie

func ReadResponse

func ReadResponse(uri *url.URL) (*http.Response, error)

func Resolve

func Resolve(s string) string

Resolve - resolve a string to an url.

func SetDefaultOrigin

func SetDefaultOrigin(s string)

func SetHeaders

func SetHeaders(w http.ResponseWriter, headers any)

func UpdateHeaders

func UpdateHeaders(req *http.Request) *http.Request

func ValidTrailerHeader

func ValidTrailerHeader(name string) bool

ValidTrailerHeader reports whether name is a valid header field name to appear in trailers. See RFC 7230, Section 4.1.2

func WriteBytes

func WriteBytes(content any, contentType string) ([]byte, string, *runtime.Status)

func WriteResponse

func WriteResponse[E runtime.ErrorHandler](w http.ResponseWriter, content any, status *runtime.Status, headers any)

WriteResponse - write a http.Response, utilizing the content, status, and headers Only supports []byte, string, io.Reader, and io.ReaderCloser for T

Types

type Attr

type Attr struct {
	Key string
	Val string
}

type Exchange

type Exchange func(req *http.Request) (*http.Response, error)

Exchange - interface for Http request/response interaction

type Resolver

type Resolver func(string) string

type ResponseRecorder

type ResponseRecorder struct {
	// Code is the HTTP response code set by WriteHeader.
	//
	// Note that if a Handler never calls WriteHeader or Write,
	// this might end up being 0, rather than the implicit
	// http.StatusOK. To get the implicit value, use the Result
	// method.
	Code int

	// HeaderMap contains the headers explicitly set by the Handler.
	// It is an internal detail.
	//
	// Deprecated: HeaderMap exists for historical compatibility
	// and should not be used. To access the headers returned by a handler,
	// use the Response.Header map as returned by the Result method.
	HeaderMap http.Header

	// Body is the buffer to which the Handler's Write calls are sent.
	// If nil, the Writes are silently discarded.
	Body *bytes.Buffer

	// Flushed is whether the Handler called Flush.
	Flushed bool
	// contains filtered or unexported fields
}

ResponseRecorder is an implementation of http.ResponseWriter that records its mutations for later inspection in tests.

func NewRecorder

func NewRecorder() *ResponseRecorder

NewRecorder returns an initialized ResponseRecorder.

func (*ResponseRecorder) Flush

func (rw *ResponseRecorder) Flush()

Flush implements http.Flusher. To test whether Flush was called, see rw.Flushed.

func (*ResponseRecorder) Header

func (rw *ResponseRecorder) Header() http.Header

Header implements http.ResponseWriter. It returns the response headers to mutate within a handler. To test the headers that were written after a handler completes, use the Result method and see the returned Response value's Header.

func (*ResponseRecorder) Result

func (rw *ResponseRecorder) Result() *http.Response

Result returns the response generated by the handler.

The returned Response will have at least its StatusCode, Header, Body, and optionally Trailer populated. More fields may be populated in the future, so callers should not DeepEqual the result in tests.

The Response.Header is a snapshot of the headers at the time of the first write call, or at the time of this call, if the handler never did a write.

The Response.Body is guaranteed to be non-nil and Body.Read call is guaranteed to not return any error other than io.EOF.

Result must only be called after the handler has finished running.

func (*ResponseRecorder) Write

func (rw *ResponseRecorder) Write(buf []byte) (int, error)

Write implements http.ResponseWriter. The data in buf is written to rw.Body, if not nil.

func (*ResponseRecorder) WriteHeader

func (rw *ResponseRecorder) WriteHeader(code int)

WriteHeader implements http.ResponseWriter.

func (*ResponseRecorder) WriteString

func (rw *ResponseRecorder) WriteString(str string) (int, error)

WriteString implements io.StringWriter. The data in str is written to rw.Body, if not nil.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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