rest

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2019 License: MIT Imports: 19 Imported by: 0

README

Rest

Build Status Coverage Status Go Report Card GoDoc license

Is a collection of convenience functions for the http.ServeMux.

Introduction

Rest provides functions for:

  • Single http method restriction
  • Writing JSON responses to the client
  • Writing String responses to the client
  • Path parameter extraction
  • Basic Authentication
  • Request logging
Basic Usage

Instead of boilerplate like this:

http.HandleFunc("/api/ping", func(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		// respond
	default:
		http.Error(w, "only GET allowed", http.StatusMethodNotAllowed)
	}
})

You can write this:

rest.GET(http.DefaultServeMux, "/api/ping", func(w http.ResponseWriter, r *http.Request) {
	// respond
})

Or a short way to write a JSON response:

rest.JSON(w, someStruct, http.StatusOK)

The same goes for a string:

rest.String(w, "Hallo Gopher!", http.StatusAccepted)

Given a path like '/api/foo/bar' you can extract foo and bar like this:

bar, err := rest.StringFromURL(r.URL,0) // bar
foo, err := rest.StringFromURL(r.URL,1) // foo

If foo is an int you can do:

foo, err := rest.IntFromURL(r.URL, 1) // int of foo

To setup basic authentication:

mux := http.NewServeMux()
// ... 
rest.BasicAuthent(mux, "Your server", func(user, password string) bool {
	// some lookup
	return lookupResult
})
log.Println(http.ListenAndServe(":2121", loggingMux))

A log like this:

2017/01/12 08:05:55.767727 <-- GET /api/ping 127.0.0.1:2121 202 29.935µs HTTP/1.1

Can be set up like this:

mux := http.NewServeMux()
// ... 
loggingMux := rest.RequestLogger(mux, logger, errLog)
log.Println(http.ListenAndServe(":2121", loggingMux))
Self signed certificate creation

Caution: Before using this consider using a secure certificate from https://letsencrypt.org/. Since a self signed certificate is less secure than a proper one. Mainly because the identity of the server using this self signed certificate cannot be confirmed. Which makes it especially vulnerable for man in the middle attacks. Do not use this with public servers!

For more information see: https://en.wikipedia.org/wiki/Self-signed_certificate#Security_issues. https://en.wikipedia.org/wiki/Man-in-the-middle_attack

For letsencrypt in go you can use: https://github.com/ericchiang/letsencrypt to get the cert.

A self signed certificate can be created as follows:

func main() {
	subject := pkix.Name{
		Country:            []string{"Your country"},
		Organization:       []string{"Your organization"},
		OrganizationalUnit: []string{"Your unit"},
		Locality:           []string{"Your locality"},
		Province:           []string{"Your province"},
		StreetAddress:      []string{"Your street address"},
		PostalCode:         []string{"Your postal code"},
		CommonName:         "Your common name",
	}
	addrs := []string{"127.0.0.1", "192.168.0.100"}

	conf := rest.NewCertConf(subject, addrs)
	if err := rest.GenerateTLSCertificate(conf); err != nil {
		fmt.Printf("error while creating TLS cert, %v", err)
	}
}

When using the default CertConf the created certificate can be found in the current directory (./).

Documentation

Overview

Package rest provides convenience functions for the default http.ServeMux.

Index

Constants

View Source
const (
	ContentType          = "Content-Type"
	ContentTypePlainText = "text/plain; charset=utf-8"
	ContentTypeJSON      = "application/json"
)

ContentType constants

Variables

This section is empty.

Functions

func BasicAuthent

func BasicAuthent(handler http.Handler, realm string, authorized func(user, password string) bool) http.Handler

BasicAuthent adds the BasicAuthentMiddleware to the given handler.

func Chain

func Chain(f http.HandlerFunc, middlewares ...Middleware) http.HandlerFunc

Chain executes all given middleware functions for a given http.HandlerFunc.

func ChainHandler

func ChainHandler(f http.Handler, middlewares ...Middleware) http.Handler

ChainHandler like Chain for http.Handlers, it executes all middleware on the given http.Handler

func DELETE

func DELETE(mux *http.ServeMux, path string, f func(w http.ResponseWriter, r *http.Request))

DELETE restricts the given handler func to the DELETE method for the given path.

func GET

func GET(mux *http.ServeMux, path string, f func(w http.ResponseWriter, r *http.Request))

GET restricts the given handler func to the GET method for the given path.

func GenerateTLSCertificate

func GenerateTLSCertificate(conf CertConf) error

GenerateTLSCertificate generates a TLS cert specified by the given configuration asynchronously.

Caution: Before using this consider using a secure certificate from https://letsencrypt.org/. Since a self signed certificate is less secure than a proper one. Mainly because the identity of the server using this self signed certificate cannot be confirmed. Which makes it especially vulnerable for man in the middle attacks. Do not use this with public servers!

For more information see: https://en.wikipedia.org/wiki/Self-signed_certificate#Security_issues. https://en.wikipedia.org/wiki/Man-in-the-middle_attack

For https://letsencrypt.org/ in go. You can use: https://github.com/ericchiang/letsencrypt to get the cert.

func IntFromURL

func IntFromURL(url *url.URL, position int) (int64, error)

IntFromURL extracts the int value on the given position counted backwards beginning by 0. E. g. given the path /foo/bar/10/20 position 0 would be 20 position 1 would be 10.

func JSON

func JSON(w http.ResponseWriter, res interface{}, code int)

JSON writes a JSON response to the client. If the given interface can not be marshaled an error message with Status InternalServerError is returned.

func OPTIONS

func OPTIONS(mux *http.ServeMux, path string, f func(w http.ResponseWriter, r *http.Request))

OPTIONS restricts the given handler func to the OPTIONS method for the given path.

func PATCH

func PATCH(mux *http.ServeMux, path string, f func(w http.ResponseWriter, r *http.Request))

PATCH restricts the given handler func to the PATCH method for the given path.

func POST

func POST(mux *http.ServeMux, path string, f func(w http.ResponseWriter, r *http.Request))

POST restricts the given handler func to the POST method for the given path.

func PUT

func PUT(mux *http.ServeMux, path string, f func(w http.ResponseWriter, r *http.Request))

PUT restricts the given handler func to the PUT method for the given path.

func RequestLogger

func RequestLogger(handler http.Handler, logger, errlog *log.Logger) http.Handler

RequestLogger adds the RequestLoggerMiddleware to the given handler.

func String

func String(w http.ResponseWriter, res string, code int)

String writes the given string to the client as content type plain/text UTF-8.

func StringFromURL

func StringFromURL(url *url.URL, position int) (string, error)

StringFromURL extracts the string value on the given position counted backwards beginning by 0. E. g. given the path /foo/bar position 0 would be 'bar' position 1 would be 'foo'.

func TRACE

func TRACE(mux *http.ServeMux, path string, f func(w http.ResponseWriter, r *http.Request))

TRACE restricts the given handler func to the TRACE method for the given path.

Types

type CertConf

type CertConf struct {
	ValidFor  time.Duration
	RASBits   int
	Subject   pkix.Name
	CertOut   func() (io.WriteCloser, error) // Will write to the writer and then close.
	KeyOut    func() (io.WriteCloser, error) // Will write to the writer and then close.
	Random    io.Reader
	HostAddrs []string
}

CertConf holds the TLS certificate configuration.

func NewCertConf

func NewCertConf(subject pkix.Name, hostAddrs []string) CertConf

NewCertConf returns a default certificate configuration for the given subject and hostAddrs. Default valid for is 365 days. Default cert RSA bits 4096. Default cert out ./cert.pem Default key out ./key.pem

type Middleware

type Middleware func(http.HandlerFunc) http.HandlerFunc

Middleware defines the http.HandlerFunc as middleware.

func BasicAuthentMiddleware

func BasicAuthentMiddleware(realm string, authorized func(user, password string) bool) Middleware

BasicAuthentMiddleware is a basic authentication middleware that checks authentication against the given authorized function.

func Method

func Method(method string) Middleware

Method returns a middleware that restricts the allowed http method to the given string.

func RequestLoggerMiddleware

func RequestLoggerMiddleware(logger, errlog *log.Logger) Middleware

RequestLoggerMiddleware is a middleware that logs incoming request to the provided loggers.

type Response

type Response struct {
	Status    int
	StartTime time.Time
	ResBuf    *bytes.Buffer
	// contains filtered or unexported fields
}

Response can be used to capture the status code, running time and error error response (if present) of a given request.

func NewResponse

func NewResponse(w http.ResponseWriter) *Response

NewResponse returns an with StartTime now and status 200 initialised Response.

func (*Response) Header

func (r *Response) Header() http.Header

Header wraps the call to the http.ResponseWriter.

func (*Response) Write

func (r *Response) Write(data []byte) (int, error)

Write wraps the call to the http.ResponseWriter. In case of an error it captures up to 50 bytes of the error response.

func (*Response) WriteHeader

func (r *Response) WriteHeader(status int)

WriteHeader wraps the call to http.ResponseWriter and captures the status code.

Jump to

Keyboard shortcuts

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