httputils

package
v0.9.13 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2021 License: Apache-2.0 Imports: 23 Imported by: 0

README

[TOC]

RPC error code / HTTP mapping

HTTP → RPC

HTTP RPC
2xx (0) OK
3xx (2) UNKNOWN
400 Bad request (3) INVALID_ARGUMENT
401 Unauthorized (16) UNAUTHENTICATED
403 Forbidden (7) PERMISSION_DENIED
404 Not found (5) NOT_FOUND
409 Conflict (10) ABORTED
416 Requested range not satisfiable (11) OUT_OF_RANGE
429 Too many requests (8) RESOURCE_EXHAUSTED
499 Client closed request (1) CANCELLED
4xx Other 4xx (9) FAILED_PRECONDITION
501 Not implemented (12) UNIMPLEMENTED
503 Service unavailable (14) UNAVAILABLE
504 Gateway time-out (4) DEADLINE_EXCEEDED
5xx Other 5xx (13) INTERNAL
All others (includes 100s) (2) UNKNOWN

RPC → HTTP

RPC HTTP
(0) OK 200 OK
(1) CANCELLED 499 Client closed request
(2) UNKNOWN 500 Internal server error
(3) INVALID_ARGUMENT 400 Bad request
(4) DEADLINE_EXCEEDED 504 Gateway Time-out
(5) NOT_FOUND 404 Not found
(6) ALREADY_EXISTS 409 Conflict
(7) PERMISSION_DENIED 403 Forbidden
(8) RESOURCE_EXHAUSTED 429 Too many requests
(9) FAILED_PRECONDITION 400 Bad request
(10) ABORTED 409 Conflict
(11) OUT_OF_RANGE 400 Bad request
(12) UNIMPLEMENTED 501 Not implemented
(13) INTERNAL 500 Internal server error
(14) UNAVAILABLE 503 Service unavailable
(15) DATA_LOSS 500 Internal server error
(16) UNAUTHENTICATED 401 Unauthorized

References

Documentation

Overview

Package httputils contains utilities for handling HTTP requests.

Index

Constants

This section is empty.

Variables

View Source
var HTMLReplacer = strings.NewReplacer(
	"&", "&",
	"<", "&lt;",
	">", "&gt;",
	`"`, "&#34;",
	"'", "&#39;",
)

HTMLReplacer escape URL parameters for HTML. This is copied from http package.

View Source
var (
	// NewStatus is temprorary aliases.
	NewStatus = status.New
)

Functions

func AbsolutePath

func AbsolutePath(r *http.Request) string

AbsolutePath find the registered path in the mux router. eg. register "/path/{var}" in router, request to "/path/a" AbsolutePath(r) will return "/path/{var}".

func AddStatusDetails

func AddStatusDetails(s *status.Status, details ...proto.Message) *status.Status

AddStatusDetails adds a details message to a status.

func AddStatusInfo

func AddStatusInfo(s *status.Status, name, msg string) *status.Status

AddStatusInfo returns a new status that includes an additional ErrorInfo entry.

func CheckName

func CheckName(field, name string, regexps map[string]*regexp.Regexp) error

CheckName checks name for a field satisfies the naming rules for it.

func DecodeJSON

func DecodeJSON(r io.Reader, v interface{}) error

DecodeJSON reads JSON from io.Reader and decodes it into an object.

func DecodeJSONPB

func DecodeJSONPB(r io.Reader, m proto.Message) error

DecodeJSONPB reads JSONPB from io.Reader and decodes it into an object.

func DecodeProto

func DecodeProto(m proto.Message, b io.Reader) error

DecodeProto decodes a reader with JSON coded protobuffer message content.

func DecodeProtoReq

func DecodeProtoReq(m proto.Message, req *http.Request) error

DecodeProtoReq decodes a request with protobuffer message body.

func EncodeJSON

func EncodeJSON(w io.Writer, v interface{}) error

EncodeJSON encodes an object into JSON and writes it to io.Writer.

func EncodeJSONPB

func EncodeJSONPB(w io.Writer, m proto.Message) error

EncodeJSONPB encodes an object into JSONPB and writes it to io.Writer.

func EncodeProto

func EncodeProto(m proto.Message) (io.Reader, error)

EncodeProto decodes a reader with JSON coded protobuffer message content.

func FromError

func FromError(err error) int

FromError translates a canonical error into an HTTP status.

func HTTPStatus

func HTTPStatus(code codes.Code) int

HTTPStatus translates a codes.Code into an HTTP status.

func IsHTTPClientError

func IsHTTPClientError(code int) bool

IsHTTPClientError check if http code is client error code: 4xx

func IsHTTPError

func IsHTTPError(code int) bool

IsHTTPError check if http code is error code: 4xx or 5xx

func IsHTTPRedirect

func IsHTTPRedirect(code int) bool

IsHTTPRedirect check if http code is redirect code: 3xx

func IsHTTPS added in v0.9.3

func IsHTTPS(in string) bool

IsHTTPS checks if the url is using https

func IsHTTPServerError

func IsHTTPServerError(code int) bool

IsHTTPServerError check if http code is server error code: 5xx

func IsHTTPSuccess

func IsHTTPSuccess(code int) bool

IsHTTPSuccess check if http code is success code: 2xx See: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

func IsJSON

func IsJSON(str string) bool

IsJSON returns true when the data format is JSON.

func IsLocalhost added in v0.9.3

func IsLocalhost(in string) bool

IsLocalhost checks if the url is hosting in local

func LivenessCheckHandler

func LivenessCheckHandler(w http.ResponseWriter, r *http.Request)

LivenessCheckHandler implements an application liveness checker for Google App Engine Flex apps

func MustDecodeJSONPBResp

func MustDecodeJSONPBResp(t *testing.T, resp *http.Response, m proto.Message)

MustDecodeJSONPBResp is the test helper for DecodeJSONPB. TODO: move to a test package.

func MustDecodeJSONResp

func MustDecodeJSONResp(t *testing.T, resp *http.Response, v interface{})

MustDecodeJSONResp is the test helper for DecodeJSON. TODO: move to a test package.

func MustDecodeProto

func MustDecodeProto(m proto.Message, b io.Reader)

MustDecodeProto decodes a reader with JSON coded protobuffer message content.

func MustEncodeProto

func MustEncodeProto(m proto.Message) io.Reader

MustEncodeProto decodes a reader with JSON coded protobuffer message content.

func MustNewReq

func MustNewReq(method, url string, body io.Reader) *http.Request

MustNewReq creates a request. Crashes on error.

func NewInfoStatus

func NewInfoStatus(code codes.Code, name, msg string) *status.Status

NewInfoStatus returns a standard RPC-style error message with ErrorInfo details.

func NewPageHandler

func NewPageHandler(page string, additionalCSP *CSP) func(w http.ResponseWriter, r *http.Request)

NewPageHandler creates a new handler that serves the given HTML page.

func QueryParam

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

QueryParam returns a URL query parameter value.

func QueryParamInt

func QueryParamInt(r *http.Request, name string) int

QueryParamInt returns a URL query parameter value of int type. Returns 0 if missing or invalid.

func QueryParamWithDefault

func QueryParamWithDefault(r *http.Request, name string, d string) string

QueryParamWithDefault returns a URL query parameter value. If not set or empty, the provided default value is returned.

func RPCCode

func RPCCode(code int) codes.Code

RPCCode translates an HTTP status into a codes.Code

func RedirectHTMLPage

func RedirectHTMLPage(dst string) string

RedirectHTMLPage retuns the HTML page generated by http.Redirect. This is copied from http package.

func RequesterIP

func RequesterIP(r *http.Request) string

RequesterIP find the requester ip from http request.

func StatusPath

func StatusPath(list ...string) string

StatusPath combines multiple path elements into one string path.

func StopHandler

func StopHandler(w http.ResponseWriter, r *http.Request)

StopHandler will cause make the server exit.

func TemplateFromFiles added in v0.9.2

func TemplateFromFiles(paths ...string) (*template.Template, error)

TemplateFromFiles constructs the html safe template from given file. name: name of temaplate. path: path of the template file.

func WriteCorsHeaders

func WriteCorsHeaders(w http.ResponseWriter)

WriteCorsHeaders writes CORS headers (https://www.w3.org/TR/cors) to the response.

func WriteError

func WriteError(w http.ResponseWriter, err error)

WriteError writes an error to the response. Does nothing if status is nil.

func WriteHTMLResp

func WriteHTMLResp(w http.ResponseWriter, b string, additionalCSP *CSP)

WriteHTMLResp writes a "text/html" type string to the ResponseWriter.

func WriteNonProtoResp

func WriteNonProtoResp(w http.ResponseWriter, resp interface{})

WriteNonProtoResp writes a reponse. For protobuf message responses use WriteResp(w, resp) instead.

func WriteRedirect

func WriteRedirect(w http.ResponseWriter, r *http.Request, redirect string)

WriteRedirect writes a redirect to the provider URL. If the provided URL is relative, it will be relative to the request URL.

func WriteResp

func WriteResp(w http.ResponseWriter, m proto.Message)

WriteResp writes an protobuf message to the response.

Types

type CSP added in v0.9.4

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

CSP handles Content Security Policy headers. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP

func CSPFromString added in v0.9.4

func CSPFromString(str string) *CSP

CSPFromString reads csp from header.

type FakeWriter

type FakeWriter struct {
	Headers http.Header
	Body    string
	Code    int
}

FakeWriter is a fake HTTP response writer. See http.ResponseWriter.

func NewFakeWriter

func NewFakeWriter() *FakeWriter

NewFakeWriter creates a new FakeWriter.

func (*FakeWriter) Header

func (w *FakeWriter) Header() http.Header

Header returns the header.

func (*FakeWriter) Write

func (w *FakeWriter) Write(b []byte) (int, error)

Write appends to the Body.

func (*FakeWriter) WriteHeader

func (w *FakeWriter) WriteHeader(code int)

WriteHeader writes the HTTP status code.

type Page

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

Page is handler for a fixed HTML page.

func (Page) Handler

func (s Page) Handler(w http.ResponseWriter, r *http.Request)

Handler serve the stored page.

Jump to

Keyboard shortcuts

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