there

package module
v2.0.11 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2021 License: GPL-3.0 Imports: 12 Imported by: 0

README

there

there, also called GoThere, aims to be a simple Go Library to reduce redundant code for REST APIs. The name GoThere because it tells the incoming requests to "go there". With there it is a delight to create a REST API. You can focus on writing your API without writing boilerplate and duplicate code. Just start coding and save time!

Table of contents

If it states Complete example, you can just copy the whole example and run it directly without changing something.

Install

go get -u github.com/Gebes/there/v2

Examples

Let's go through some basic examples, which make you understand the library in less than 10 minutes. Feel free to play around!

I recommend you import there in every file you use it like the following:

import (
	. "github.com/Gebes/there/v2"
)

If you are not familiar with this syntax, this allows you to use there without the there. prefix.

Create a router
func main(){
	router := NewRouter().
		Get("/user/:id", GetUser).
		Post("/user", PostUser).
		Patch("/user/:id", PatchUser).
		Delete("/user/:id", DeleteUser)
}

Just create a new router instance and register some routes. there provides simple builder patterns, so you don't need to write router. for every route or middleware.

Listen to a port
func main(){
	router := NewRouter()
	// ...
	err := router.Listen(8080)
	if err != nil {
		log.Fatalln("Could not start listening on port 8080", err)
	}
}

The Listen method binds the router blocking to this port. A possible error could be that the port is already in use by a different program.

Handle a request

We already know how to define routes. But how do we handle them?

We need to pass a handler function, as the following

router := NewRouter().
		Get("/route", func(request HttpRequest) HttpResponse {
		
		})

or

func main() {
	router := NewRouter().
		Get("/route", RouteHandler)
}

func RouteHandler(request HttpRequest) HttpResponse {

}
Complete example: returning Json, Xml, Yaml or Msgpack

This example provides a /users route, which returns a list of users in the JSON Format.

If you want to, you can also return the data in Xml, Yaml, or even Msgpack.

package main

import (
	. "github.com/Gebes/there/v2"
	"log"
)

type User struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

func NewUser(name string, description string) *User {
	return &User{Name: name, Description: description}
}

var (
	users = []*User{
		NewUser("Steve Jobs", "Apple Founder"),
		NewUser("Elon Musk", "Cool guy"),
		NewUser("Bill Gates", "Microsoft Founder"),
		NewUser("Tim Cook", "Current Apple Ceo"),
	}
)

func main() {
	router := NewRouter().
		Get("/users", GetUsers)

	err := router.Listen(8080)
	if err != nil {
		log.Fatalln("Could not start listening on port 8080", err)
	}
}

func GetUsers(request HttpRequest) HttpResponse {
	// there automatically sets the Content-Type header
	return Json(StatusOK, users) // return all the users as JSON
//	return Xml(StatusOK, users)
//	return Yaml(StatusOK, users)
//	return Msgpack(StatusOK, users) // Msgpack is supported out of the box
}


If you run this example and open localhost:8080/users in your browser, then you get the following result:

[{"name":"Steve Jobs","description":"Apple Founder"},{"name":"Elon Musk","description":"Cool guy"},{"name":"Bill Gates","description":"Microsoft Founder"},{"name":"Tim Cook","description":"Current Apple Ceo"}]

Here is the result formatted:

[
  {
    "name": "Steve Jobs",
    "description": "Apple Founder"
  },
  {
    "name": "Elon Musk",
    "description": "Cool guy"
  },
  {
    "name": "Bill Gates",
    "description": "Microsoft Founder"
  },
  {
    "name": "Tim Cook",
    "description": "Current Apple Ceo"
  }
]
All HttpResponses

Here is a list of all the valid HttpResponse Returns you can make:

func RouteHandler(request HttpRequest) HttpResponse {
	return Empty(StatusOK)                      // Returns nothing

	return Bytes(StatusOK, []byte("A message")) // Same result, but the input is a byte array
	return String(StatusOK, "A message")        // Just return a plain string

	return Redirect("https://www.google.com")   // Redirect the request to another page

	return Error(StatusInternalServerError, errors.New("parse an error")) // Will be formatted accordingly to router.RouterConfiguration.ErrorMarshal
	// Default is JSON: {"error": "parse an error"}
	
	return Json(StatusOK, users)
	return Xml(StatusOK, users)
	return Yaml(StatusOK, users)
	return Msgpack(StatusOK, users)                                  // Msgpack is supported out of the box
	return Html(StatusOK, "./files/index.html", map[string]string{}) // Reads the HTML File and uses it as a template. Variables from the map will be replaced into the response
}

If you are up to it, you can also create your own Response by creating a struct that implements the HttpResponse interface.

Middlewares

Of course, there has middleware support. You can either have global middlewares by using router.Use(middleware) or route-specific middlewares by using router.Get("/route", handler).With(middleware).
You cannot do router.With(middleware) because the .With(middleware) method requires a route to be defined before. It will add the middleware always to the last added route.

package main

import (
	"context"
	"errors"
	. "github.com/Gebes/there/v2"
)

func main() {

	// Register global middleware 
	router := NewRouter().Use(RandomMiddleware).Use(CorsMiddleware(AllowAllConfiguration()))

	router.
		// Registers Middleware only for the "/" route
		Get("/", GetAuthHeader).With(DataMiddleware)

	err := router.Listen(8080)
	if err != nil {
		panic(err)
	}
}

var count = 0

//RandomMiddleware returns an example error for every second request
func RandomMiddleware(HttpRequest) HttpResponse {
	count++
	if count%2 == 0 {
		// If you do not return Next(), then the Invocation-Chain will be broken, and the Response will be returned
		return Error(StatusInternalServerError, errors.New("lost database connection"))
	}
	// Next() means, that either the next middleware or Handler (if it is the last middleware) should be executed
	return Next()
}

//DataMiddleware checks if the user provided an Authorization header. If so, then it will be passed on to the handler via Context
func DataMiddleware(request HttpRequest) HttpResponse {
	auth := request.Headers.GetDefault(RequestHeaderAuthorization, "")
	if len(auth) == 0 {
		return Error(StatusBadRequest, errors.New("no authorization header provider"))
	}
	// We wrap Next() with a Context, by using the WithContext Wrapper.
	// In the GetAuthHeader Handler, we can then use the current Context to read "auth"
	// WithContext can also be returned in a regular Handler, but it would make no sense. To where do you want to pass the context???
	// The WithContext() and Next() HttpResponse should only be used for middlewares
	return WithContext(context.WithValue(request.Context(), "auth", auth), Next())
}

func GetAuthHeader(request HttpRequest) HttpResponse {
	// Read from the context
	data, ok := request.Context().Value("auth").(string)

	if !ok { // Could not read from the context... should not happen, except we forgot to add the DataMiddleware to the Route
		return Error(StatusUnprocessableEntity, errors.New("could not get auth from context"))
	}

	return String(StatusOK, "Auth: "+data)
}

The example seems a bit too big, but it shows everything that you can do with middlewares. We added two global middlewares. One which we defined on our own and one cors middleware, which allows everything.
Our RandomMiddleware is now used globally, which means it will be called before any Route Handler. As a result, every second call to our API will fail with the defined error.
Our DataMiddleware is only used for the GetAuthHeader Route. Therefore, it gets the "Authorization" Header. If the Header is empty, then it will return an error. If not, it will pass the Authorization Header via Context to the next middleware or final Route Handler. In this case, we do not have any extra middlewares, so it will call the GetAuthHeader handler, read from the Context, and return it as a String.

Contact

Feel free to join the there Discord Server

Documentation

Index

Constants

View Source
const (
	MethodGet     = "GET"
	MethodHead    = "HEAD"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodPatch   = "PATCH" // RFC 5789
	MethodDelete  = "DELETE"
	MethodConnect = "CONNECT"
	MethodOptions = "OPTIONS"
	MethodTrace   = "TRACE"
)
View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusTooEarly                     = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes as registered with IANA. See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

View Source
const (
	ContentTypeApplicationJavaDashArchive                = "application/java-archive"
	ContentTypeApplicationEdiDashX12                     = "application/EDI-X12"
	ContentTypeApplicationEdifact                        = "application/EDIFACT"
	ContentTypeApplicationJavascript                     = "application/javascript"
	ContentTypeApplicationOctetDashStream                = "application/octet-stream"
	ContentTypeApplicationOgg                            = "application/ogg"
	ContentTypeApplicationPdf                            = "application/pdf"
	ContentTypeApplicationXhtmlPlusXml                   = "application/xhtml+xml"
	ContentTypeApplicationXDashShockwaveDashFlash        = "application/x-shockwave-flash"
	ContentTypeApplicationJson                           = "application/json"
	ContentTypeApplicationLdPlusJson                     = "application/ld+json"
	ContentTypeApplicationXml                            = "application/xml"
	ContentTypeApplicationZip                            = "application/zip"
	ContentTypeApplicationXDashWwwDashFormDashUrlencoded = "application/x-www-form-urlencoded"
	ContentTypeAudioMpeg                                 = "audio/mpeg"
	ContentTypeAudioXDashMsDashWma                       = "audio/x-ms-wma"
	ContentTypeAudioVndDotRnDashRealaudio                = "audio/vnd.rn-realaudio"
	ContentTypeAudioXDashWav                             = "audio/x-wav"
	ContentTypeImageGif                                  = "image/gif"
	ContentTypeImageJpeg                                 = "image/jpeg"
	ContentTypeImagePng                                  = "image/png"
	ContentTypeImageTiff                                 = "image/tiff"
	ContentTypeImageVndDotMicrosoftDotIcon               = "image/vnd.microsoft.icon"
	ContentTypeImageXDashIcon                            = "image/x-icon"
	ContentTypeImageVndDotDjvu                           = "image/vnd.djvu"
	ContentTypeImageSvgPlusXml                           = "image/svg+xml"
	ContentTypeMultipartMixed                            = "multipart/mixed"
	ContentTypeMultipartAlternative                      = "multipart/alternative"
	ContentTypeMultipartRelated                          = "multipart/related"
	ContentTypeMultipartFormDashData                     = "multipart/form-data"
	ContentTypeTextCss                                   = "text/css"
	ContentTypeTextCsv                                   = "text/csv"
	ContentTypeTextHtml                                  = "text/html"
	ContentTypeTextJavascript                            = "text/javascript"
	ContentTypeTextPlain                                 = "text/plain"
	ContentTypeTextXml                                   = "text/xml"
	ContentTypeVideoMpeg                                 = "video/mpeg"
	ContentTypeVideoMp4                                  = "video/mp4"
	ContentTypeVideoQuicktime                            = "video/quicktime"
	ContentTypeVideoXDashMsDashWmv                       = "video/x-ms-wmv"
	ContentTypeVideoXDashMsvideo                         = "video/x-msvideo"
	ContentTypeVideoXDashFlv                             = "video/x-flv"
	ContentTypeVideoWebm                                 = "video/webm"
)
View Source
const (
	// RequestHeaderAIm
	// Acceptable instance-manipulations for the request.
	//
	//	A-IM: feed
	RequestHeaderAIm = "A-IM"

	// RequestHeaderAccept
	// Media type(s) that is/are acceptable for the response. See Content negotiation.
	//
	//	Accept: text/html
	RequestHeaderAccept = "Accept"

	// RequestHeaderAcceptCharset
	// Character sets that are acceptable.
	//
	//	Accept-Charset: utf-8
	RequestHeaderAcceptCharset = "Accept-Charset"

	// RequestHeaderAcceptDatetime
	// Acceptable version in time.
	//
	//	Accept-Datetime: Thu, 31 May 2007 20:35:00 GMT
	RequestHeaderAcceptDatetime = "Accept-Datetime"

	// RequestHeaderAcceptEncoding
	// List of acceptable encodings. See HTTP compression.
	//
	//	Accept-Encoding: gzip, deflate
	RequestHeaderAcceptEncoding = "Accept-Encoding"

	// RequestHeaderAcceptLanguage
	// List of acceptable human languages for response. See Content negotiation.
	//
	//	Accept-Language: en-US
	RequestHeaderAcceptLanguage = "Accept-Language"

	// RequestHeaderAccessControlRequestMethod
	// Initiates a request for cross-origin resource sharing with Origin (below).
	//
	//	Access-Control-Request-Method: GET
	RequestHeaderAccessControlRequestMethod = "Access-Control-Request-Method"

	// RequestHeaderAccessControlRequestHeaders
	// Initiates a request for cross-origin resource sharing with Origin (below).
	//Access-Control-Request-Method: GET
	RequestHeaderAccessControlRequestHeaders = "Access-Control-Request-Headers"

	// RequestHeaderAuthorization
	// Authentication credentials for HTTP authentication.
	//
	//	Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
	RequestHeaderAuthorization = "Authorization"

	// RequestHeaderCacheControl
	// Used to specify directives that must be obeyed by all caching mechanisms along the request-response chain.
	//
	//	Cache-Control: no-cache
	RequestHeaderCacheControl = "Cache-Control"

	// RequestHeaderConnection
	// Control options for the current connection and list of hop-by-hop request fields. Must not be used with HTTP/2.
	//
	//	Connection: keep-alive
	//	Connection: Upgrade
	RequestHeaderConnection = "Connection"

	// RequestHeaderContentEncoding
	// The type of encoding used on the data. See HTTP compression.
	//
	//	Content-Encoding: gzip
	RequestHeaderContentEncoding = "Content-Encoding"

	// RequestHeaderContentLength
	// The length of the request body in octets (8-bit bytes).
	//
	//	Content-Length: 348
	RequestHeaderContentLength = "Content-Length"

	// RequestHeaderContentMd5
	// A Base64-encoded binary MD5 sum of the content of the request body.
	//
	//	Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
	RequestHeaderContentMd5 = "Content-MD5"

	// RequestHeaderContentType
	// The Media type of the body of the request (used with POST and PUT requests).
	//
	//	Content-Type: application/x-www-form-urlencoded
	RequestHeaderContentType = "Content-Type"

	// RequestHeaderCookie
	// An HTTP cookie previously sent by the server with Set-Cookie (below).
	//
	//	Cookie: $Version=1; Skin=new;
	RequestHeaderCookie = "Cookie"

	// RequestHeaderDate
	// The date and time at which the message was originated (in "HTTP-date" bind as defined by RFC 7231 Date/Time Formats).
	//
	//	Date: Tue, 15 Nov 1994 08:12:31 GMT
	RequestHeaderDate = "Date"

	// RequestHeaderExpect
	// Indicates that particular server behaviors are required by the client.
	//
	//	Expect: 100-continue
	RequestHeaderExpect = "Expect"

	// RequestHeaderForwarded
	// Disclose original information of a client connecting to a web server through an HTTP proxy.
	//
	//	Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43
	//	Forwarded: for=192.0.2.43, for=198.51.100.17
	RequestHeaderForwarded = "Forwarded"

	// RequestHeaderFrom
	// The email address of the user making the request.
	//
	//	From: user@example.com
	RequestHeaderFrom = "From"

	// RequestHeaderHost
	// The domain name of the server (for virtual hosting), and the TCP port number on which the server is listening. The port number may be omitted if the port is the standard port for the service requested. Mandatory since HTTP/1.1. If the request is generated directly in HTTP/2, it should not be used.
	//
	//	Host: en.wikipedia.org:8080
	//	Host: en.wikipedia.org
	RequestHeaderHost = "Host"

	// RequestHeaderHttp2Settings
	// A request that upgrades from HTTP/1.1 to HTTP/2 MUST include exactly one HTTP2-Setting header field. The HTTP2-Settings header field is a connection-specific header field that includes parameters that govern the HTTP/2 connection, provided in anticipation of the server accepting the request to upgrade.
	//
	//	HTTP2-Settings: token64
	RequestHeaderHttp2Settings = "HTTP2-Settings"

	// RequestHeaderIfMatch
	// Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for methods like PUT to only update a resource if it has not been modified since the user last updated it.
	//
	//	If-Match: "737060cd8c284d8af7ad3082f209582d"
	RequestHeaderIfMatch = "If-Match"

	// RequestHeaderIfModifiedSince
	// Allows a 304 Not Modified to be returned if content is unchanged.
	//
	//	If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT
	RequestHeaderIfModifiedSince = "If-Modified-Since"

	// RequestHeaderIfNoneMatch
	// Allows a 304 Not Modified to be returned if content is unchanged, see HTTP ETag.
	//
	//	If-None-Match: "737060cd8c284d8af7ad3082f209582d"
	RequestHeaderIfNoneMatch = "If-None-Match"

	// RequestHeaderIfRange
	// If the entity is unchanged, send me the part(s) that I am missing; otherwise, send me the entire new entity.
	//
	//	If-Range: "737060cd8c284d8af7ad3082f209582d"
	RequestHeaderIfRange = "If-Range"

	// RequestHeaderIfUnmodifiedSince
	// Only send the response if the entity has not been modified since a specific time.
	//
	//	If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT
	RequestHeaderIfUnmodifiedSince = "If-Unmodified-Since"

	// RequestHeaderMaxForwards
	// Limit the number of times the message can be forwarded through proxies or gateways.
	//
	//	Max-Forwards: 10
	RequestHeaderMaxForwards = "Max-Forwards"

	// RequestHeaderOrigin
	// Initiates a request for cross-origin resource sharing (asks server for Access-Control-* response fields).
	//
	//	Origin: http://www.example-social-network.com
	RequestHeaderOrigin = "Origin"

	// RequestHeaderPragma
	// Implementation-specific fields that may have various effects anywhere along the request-response chain.
	//
	//	Pragma: no-cache
	RequestHeaderPragma = "Pragma"

	// RequestHeaderPrefer
	// Allows client to request that certain behaviors be employed by a server while processing a request.
	//
	//	Prefer: return=representation
	RequestHeaderPrefer = "Prefer"

	// RequestHeaderProxyAuthorization
	// Authorization credentials for connecting to a proxy.
	//
	//	Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
	RequestHeaderProxyAuthorization = "Proxy-Authorization"

	// RequestHeaderRange
	// Request only part of an entity.  ToBytes are numbered from 0.  See Byte serving.
	//
	//	Range: bytes=500-999
	RequestHeaderRange = "Range"

	// RequestHeaderReferer
	// This is the address of the previous web page from which a link to the currently requested page was followed. (The word "referrer" has been misspelled in the RFC as well as in most implementations to the point that it has become standard usage and is considered correct terminology)
	//
	//	Referer: http://en.wikipedia.org/wiki/Main_Page
	RequestHeaderReferer = "Referer"

	// RequestHeaderTe
	// The transfer encodings the user agent is willing to accept: the same values as for the response header field Transfer-Encoding can be used, plus the "trailers" value (related to the "chunked" transfer method) to notify the server it expects to receive additional fields in the trailer after the last, zero-sized, chunk. Only trailers is supported in HTTP/2.
	//
	//	TE: trailers, deflate
	RequestHeaderTe = "TE"

	// RequestHeaderTrailer
	// The Trailer general field value indicates that the given set of header fields is present in the trailer of a message encoded with chunked transfer coding.
	//
	//	Trailer: Max-Forwards
	RequestHeaderTrailer = "Trailer"

	// RequestHeaderTransferEncoding
	// The form of encoding used to safely transfer the entity to the user. Currently defined methods are: chunked, compress, deflate, gzip, identity. Must not be used with HTTP/2.
	//
	//	Transfer-Encoding: chunked
	RequestHeaderTransferEncoding = "Transfer-Encoding"

	// RequestHeaderUserAgent
	// The user agent string of the user agent.
	//
	//	User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0
	RequestHeaderUserAgent = "User-Agent"

	// RequestHeaderUpgrade
	// Ask the server to upgrade to another protocol. Must not be used in HTTP/2.
	//
	//	Upgrade: h2c, HTTPS/1.3, IRC/6.9, RTA/x11, websocket
	RequestHeaderUpgrade = "Upgrade"

	// RequestHeaderVia
	// Informs the server of proxies through which the request was sent.
	//
	//	Via: 1.0 fred, 1.1 example.com (Apache/1.1)
	RequestHeaderVia = "Via"

	// RequestHeaderWarning
	// A general warning about possible problems with the entity body.
	//
	//	Warning: 199 Miscellaneous warning
	RequestHeaderWarning = "Warning"
)

Request Headers https://en.wikipedia.org/wiki/List_of_HTTP_header_fields

View Source
const (

	// ResponseHeaderAcceptCh
	// Requests HTTP Client Hints
	//
	//	Accept-CH: UA, Platform
	ResponseHeaderAcceptCh = "Accept-CH"

	// ResponseHeaderAccessControlAllowOrigin
	// Specifying which web sites can participate in cross-origin resource sharing
	//
	//	Access-Control-Allow-Origin: *
	ResponseHeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin"

	// ResponseHeaderAccessControlAllowCredentials
	// Specifying which web sites can participate in cross-origin resource sharing
	//Access-Control-Allow-Origin: *
	ResponseHeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"

	// ResponseHeaderAccessControlExposeHeaders
	// Specifying which web sites can participate in cross-origin resource sharing
	//Access-Control-Allow-Origin: *
	ResponseHeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers"

	// ResponseHeaderAccessControlMaxAge
	// Specifying which web sites can participate in cross-origin resource sharing
	//Access-Control-Allow-Origin: *
	ResponseHeaderAccessControlMaxAge = "Access-Control-Max-Age"

	// ResponseHeaderAccessControlAllowMethods
	// Specifying which web sites can participate in cross-origin resource sharing
	//Access-Control-Allow-Origin: *
	ResponseHeaderAccessControlAllowMethods = "Access-Control-Allow-Methods"

	// ResponseHeaderAccessControlAllowHeaders
	// Specifying which web sites can participate in cross-origin resource sharing
	//Access-Control-Allow-Origin: *
	ResponseHeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers"

	// ResponseHeaderAcceptPatch
	// Specifies which patch document formats this server supports
	//
	//	Accept-Patch: text/example;charset=utf-8
	ResponseHeaderAcceptPatch = "Accept-Patch"

	// ResponseHeaderAcceptRanges
	// What partial content range types this server supports via byte serving
	//
	//	Accept-Ranges: bytes
	ResponseHeaderAcceptRanges = "Accept-Ranges"

	// ResponseHeaderAge
	// The age the object has been in a proxy cache in seconds
	//
	//	Age: 12
	ResponseHeaderAge = "Age"

	// ResponseHeaderAllow
	// Valid methods for a specified resource. To be used for a 405 Method not allowed
	//
	//	Allow: GET, HEAD
	ResponseHeaderAllow = "Allow"

	// ResponseHeaderAltSvc
	// A server uses "Alt-Svc" header (meaning Alternative Services) to indicate that its resources can also be accessed at a different network location (host or port) or using a different protocol When using HTTP/2, servers should instead send an ALTSVC frame.
	//
	//	Alt-Svc: http/1.1="http2.example.com:8001"; ma=7200
	ResponseHeaderAltSvc = "Alt-Svc"

	// ResponseHeaderCacheControl
	// Tells all caching mechanisms from server to client whether they may cache this object. It is measured in seconds
	//
	//	Cache-Control: max-age=3600
	ResponseHeaderCacheControl = "Cache-Control"

	// ResponseHeaderConnection
	// Control options for the current connection and list of hop-by-hop response fields. Must not be used with HTTP/2.
	//
	//	Connection: close
	ResponseHeaderConnection = "Connection"

	// ResponseHeaderContentDisposition
	// An opportunity to raise a "File Download" dialogue box for a known MIME type with binary bind or suggest a filename for dynamic content. Quotes are necessary with special characters.
	//
	//	Content-Disposition: attachment; filename="fname.ext"
	ResponseHeaderContentDisposition = "Content-Disposition"

	// ResponseHeaderContentEncoding
	// The type of encoding used on the data. See HTTP compression.
	//
	//	Content-Encoding: gzip
	ResponseHeaderContentEncoding = "Content-Encoding"

	// ResponseHeaderContentLanguage
	// The natural language or languages of the intended audience for the enclosed content
	//
	//	Content-Language: da
	ResponseHeaderContentLanguage = "Content-Language"

	// ResponseHeaderContentLength
	// The length of the response body in octets (8-bit bytes)
	//
	//	Content-Length: 348
	ResponseHeaderContentLength = "Content-Length"

	// ResponseHeaderContentLocation
	// An alternate location for the returned data
	//
	//	Content-Location: /index.htm
	ResponseHeaderContentLocation = "Content-Location"

	// ResponseHeaderContentMd5
	// A Base64-encoded binary MD5 sum of the content of the response
	//
	//	Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
	ResponseHeaderContentMd5 = "Content-MD5"

	// ResponseHeaderContentRange
	// Where in a full body message this partial message belongs
	//
	//	Content-Range: bytes 21010-47021/47022
	ResponseHeaderContentRange = "Content-Range"

	// ResponseHeaderContentType
	// The MIME type of this content
	//
	//	Content-Type: text/html; charset=utf-8
	ResponseHeaderContentType = "Content-Type"

	// ResponseHeaderDate
	// The date and time that the message was sent (in "HTTP-date" bind as defined by RFC 7231)
	//
	//	Date: Tue, 15 Nov 1994 08:12:31 GMT
	ResponseHeaderDate = "Date"

	// ResponseHeaderDeltaBase
	// Specifies the delta-encoding entity tag of the response.
	//
	//	Delta-Base: "abc"
	ResponseHeaderDeltaBase = "Delta-Base"

	// ResponseHeaderEtag
	// An identifier for a specific version of a resource, often a message digest
	//
	//	ETag: "737060cd8c284d8af7ad3082f209582d"
	ResponseHeaderEtag = "ETag"

	// ResponseHeaderExpires
	// Gives the date/time after which the response is considered stale (in "HTTP-date" bind as defined by RFC 7231)
	//
	//	Expires: Thu, 01 Dec 1994 16:00:00 GMT
	ResponseHeaderExpires = "Expires"

	// ResponseHeaderIm
	// Instance-manipulations applied to the response.
	//
	//	IM: feed
	ResponseHeaderIm = "IM"

	// ResponseHeaderLastModified
	// The last modified date for the requested object (in "HTTP-date" bind as defined by RFC 7231)
	//
	//	Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT
	ResponseHeaderLastModified = "Last-Modified"

	// ResponseHeaderLink
	// Used to express a typed relationship with another resource, where the relation type is defined by RFC 5988
	//
	//	Link: </feed>; rel="alternate"
	ResponseHeaderLink = "Link"

	// ResponseHeaderLocation
	// Used in redirection, or when a new resource has been created.
	//Example 1:
	//	Location: http://www.w3.org/pub/WWW/People.html Example 2:
	//	Location: /pub/WWW/People.html
	ResponseHeaderLocation = "Location"

	// ResponseHeaderP3p
	// This field is supposed to set P3P policy, in the form of P3P:CP="your_compact_policy". However, P3P did not take off, most browsers have never fully implemented it, a lot of websites set this field with fake policy text, that was enough to fool browsers the existence of P3P policy and grant permissions for third party cookies.
	//
	//	P3P: CP="This is not a
	//	P3P policy! See https://en.wikipedia.org/wiki/Special:CentralAutoLogin/
	//	P3P for more info."
	ResponseHeaderP3p = "P3P"

	// ResponseHeaderPragma
	// Implementation-specific fields that may have various effects anywhere along the request-response chain.
	//
	//	Pragma: no-cache
	ResponseHeaderPragma = "Pragma"

	// ResponseHeaderPreferenceApplied
	// Indicates which Prefer tokens were honored by the server and applied to the processing of the request.
	//
	//	Preference-Applied: return=representation
	ResponseHeaderPreferenceApplied = "Preference-Applied"

	// ResponseHeaderProxyAuthenticate
	// Request authentication to access the proxy.
	//
	//	Proxy-Authenticate: Basic
	ResponseHeaderProxyAuthenticate = "Proxy-Authenticate"

	// ResponseHeaderPublicKeyPins
	// HTTP Public Key Pinning, announces hash of website's authentic TLS certificate
	//
	//	Public-Key-Pins: max-age=2592000; pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=";
	ResponseHeaderPublicKeyPins = "Public-Key-Pins"

	// ResponseHeaderRetryAfter
	// If an entity is temporarily unavailable, this instructs the client to try again later. Value could be a specified period of time (in seconds) or a HTTP-date.
	//Example 1:
	//	Retry-After: 120 Example 2:
	//	Retry-After: Fri, 07 Nov 2014 23:59:59 GMT
	ResponseHeaderRetryAfter = "Retry-After"

	// ResponseHeaderServer
	// A name for the server
	//
	//	Server: Apache/2.4.1 (Unix)
	ResponseHeaderServer = "Server"

	// ResponseHeaderSetCookie
	// An HTTP cookie
	//
	//	Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1
	ResponseHeaderSetCookie = "Set-Cookie"

	// ResponseHeaderStrictTransportSecurity
	// A HSTS Policy informing the HTTP client how long to cache the HTTPS only policy and whether this applies to subdomains.
	//
	//	Strict-Transport-Security: max-age=16070400; includeSubDomains
	ResponseHeaderStrictTransportSecurity = "Strict-Transport-Security"

	// ResponseHeaderTrailer
	// The Trailer general field value indicates that the given set of header fields is present in the trailer of a message encoded with chunked transfer coding.
	//
	//	Trailer: Max-Forwards
	ResponseHeaderTrailer = "Trailer"

	// ResponseHeaderTransferEncoding
	// The form of encoding used to safely transfer the entity to the user. Currently defined methods are: chunked, compress, deflate, gzip, identity. Must not be used with HTTP/2.
	//
	//	Transfer-Encoding: chunked
	ResponseHeaderTransferEncoding = "Transfer-Encoding"

	// ResponseHeaderTk
	// Tracking Status header, value suggested to be sent in response to a DNT(do-not-track), possible values: "!" — under construction "?" — dynamic "G" — gateway to multiple parties "N" — not tracking "T" — tracking "C" — tracking with consent "P" — tracking only if consented "D" — disregarding DNT "U" — updated
	//
	//	Tk: ?
	ResponseHeaderTk = "Tk"

	// ResponseHeaderUpgrade
	// Ask the client to upgrade to another protocol. Must not be used in HTTP/2
	//
	//	Upgrade: h2c, HTTPS/1.3, IRC/6.9, RTA/x11, websocket
	ResponseHeaderUpgrade = "Upgrade"

	// ResponseHeaderVary
	// Tells downstream proxies how to match future request headers to decide whether the cached response can be used rather than requesting a fresh one from the origin server.
	//Example 1:
	//	Vary: * Example 2:
	//	Vary: Accept-Language
	ResponseHeaderVary = "Vary"

	// ResponseHeaderVia
	// Informs the client of proxies through which the response was sent.
	//
	//	Via: 1.0 fred, 1.1 example.com (Apache/1.1)
	ResponseHeaderVia = "Via"

	// ResponseHeaderWarning
	// A general warning about possible problems with the entity body.
	//
	//	Warning: 199 Miscellaneous warning
	ResponseHeaderWarning = "Warning"

	// ResponseHeaderWwwAuthenticate
	// Indicates the authentication scheme that should be used to access the requested entity.
	//
	//	WWW-Authenticate: Basic
	ResponseHeaderWwwAuthenticate = "WWW-Authenticate"

	// ResponseHeaderXFrameOptions
	// Clickjacking protection: deny - no rendering within a frame, sameorigin - no rendering if origin mismatch, allow-from - allow from specified location, allowall - non-standard, allow from any location
	//
	//	X-Frame-Options: deny
	ResponseHeaderXFrameOptions = "X-Frame-Options"
)

Response Headers

View Source
const (

	// DebugMode provides more logging information
	DebugMode = "debug"
	// ProductionMode should be used when deploying your app to production
	ProductionMode = "production"
)

Variables

Functions

func Assert

func Assert(check bool, message string)

func Bytes

func Bytes(code int, data []byte) *bytesResponse

Bytes takes a StatusCode and a series of bytes to render

func CheckArrayContains

func CheckArrayContains(slice []string, toSearch string) bool

CheckArrayContains checks if a string array contains a specific element

func CheckArraysOverlap

func CheckArraysOverlap(a []string, b []string) bool

func Empty

func Empty(code int) *emptyResponse

Empty takes a StatusCode and renders nothing

func Error

func Error(code int, err interface{}) *errorResponse

Error takes a StatusCode and err which rendering is specified by the Serializers in the RouterConfiguration

func Html

func Html(code int, file string, template interface{}) *htmlResponse

Html takes a status code, the path to the html file and a map for the template parsing

func Json

func Json(code int, data interface{}) *jsonResponse

Json takes a StatusCode and data which gets marshaled to Json

func Message

func Message(code int, message string) *jsonResponse

Message takes StatusCode and a message which will be put into a JSON object

func Msgpack

func Msgpack(code int, data interface{}) *msgpackResponse

Msgpack takes a StatusCode and data which gets marshaled to Msgpack

func Next

func Next() *nextMiddleware

Next if returned will continue to the next middleware or the response

func Redirect

func Redirect(url string) *redirectResponse

Redirect redirects to the specific URL

func StatusText

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

func String

func String(code int, data string) *stringResponse

String takes a StatusCode and renders the plain string

func WithContext added in v2.0.7

func WithContext(ctx context.Context, response HttpResponse) *contextResponse

WithContext Context wraps a response

func Xml

func Xml(code int, data interface{}) *xmlResponse

Xml takes a StatusCode and data which gets marshaled to Xml

func Yaml

func Yaml(code int, data interface{}) *yamlResponse

Yaml takes a StatusCode and data which gets marshaled to Yaml

Types

type BasicReader

type BasicReader map[string][]string

BasicReader reads http params

func (BasicReader) Get

func (reader BasicReader) Get(key string) (string, bool)

func (BasicReader) GetDefault

func (reader BasicReader) GetDefault(key, defaultValue string) string

func (BasicReader) GetSlice

func (reader BasicReader) GetSlice(key string) ([]string, bool)

func (BasicReader) Has

func (reader BasicReader) Has(key string) bool

type BodyReader

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

BodyReader reads the body and unmarshal it to the specified destination

func (BodyReader) BindJson

func (read BodyReader) BindJson(dest interface{}) error

func (BodyReader) BindMsgpack

func (read BodyReader) BindMsgpack(dest interface{}) error

func (BodyReader) BindXml

func (read BodyReader) BindXml(dest interface{}) error

func (BodyReader) BindYaml

func (read BodyReader) BindYaml(dest interface{}) error

func (BodyReader) ToBytes

func (read BodyReader) ToBytes() ([]byte, error)

func (BodyReader) ToString

func (read BodyReader) ToString() (string, error)

type CorsConfiguration

type CorsConfiguration struct {
	AccessControlAllowOrigin  string
	AccessControlAllowMethods string
	AccessControlAllowHeaders string
}

func AllowAllConfiguration

func AllowAllConfiguration() CorsConfiguration

type Endpoint

type Endpoint func(request HttpRequest) HttpResponse

type Handlers

type Handlers interface {
	RouteNotFound(request *http.Request) error
}

type HeaderWrapper

type HeaderWrapper struct {
	Values map[string][]string
	HttpResponse
}

HeaderWrapper for the fluent Header Builder

func Header(httpResponse HttpResponse) *HeaderWrapper

func (*HeaderWrapper) Set

func (h *HeaderWrapper) Set(key string, values ...string) *HeaderWrapper

func (*HeaderWrapper) SetAll

func (h *HeaderWrapper) SetAll(values map[string][]string) *HeaderWrapper

type HttpEngine

type HttpEngine interface {
	// contains filtered or unexported methods
}

type HttpRequest

type HttpRequest struct {
	Request        *http.Request
	ResponseWriter *http.ResponseWriter

	Method      string
	Body        *BodyReader
	Params      *BasicReader
	Headers     *BasicReader
	RouteParams *RouteParamReader
}

func NewHttpRequest

func NewHttpRequest(request *http.Request, responseWriter *http.ResponseWriter) HttpRequest

func (*HttpRequest) Context added in v2.0.7

func (r *HttpRequest) Context() context.Context

type HttpResponse

type HttpResponse interface {
	Header() *HeaderWrapper
	Execute(router *Router, r *http.Request, w *http.ResponseWriter) error
}

HttpResponse is the base for every return you can make in an Endpoint. Necessary to render the Response by calling Execute and for the Header Builder.

type Middleware

type Middleware func(request HttpRequest) HttpResponse

func CorsMiddleware

func CorsMiddleware(configuration CorsConfiguration) Middleware

type Mode

type Mode string

func (*Mode) IsDebug

func (mode *Mode) IsDebug() bool

func (*Mode) IsProduction

func (mode *Mode) IsProduction() bool

func (*Mode) SetDebug

func (mode *Mode) SetDebug()

func (*Mode) SetProduction

func (mode *Mode) SetProduction()

type Path

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

func ConstructPath

func ConstructPath(pathString string, ignoreCase bool) Path

func (Path) Equals

func (p Path) Equals(toCompare Path) bool

func (Path) Parse

func (p Path) Parse(route string) (map[string]string, bool)

func (Path) ToString

func (p Path) ToString() string

type PathPart

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

type Port

type Port uint16

func (Port) ToAddr

func (p Port) ToAddr() string

type Route

type Route struct {
	Endpoint    Endpoint
	Methods     []string
	Path        Path
	Middlewares []Middleware
}

Route adds attributes to an Endpoint func

func (Route) OverlapsWith

func (e Route) OverlapsWith(toCompare Route) bool

OverlapsWith checks if an Route somehow overlaps with another container. For this to be true, the path and at least one method must equal

func (Route) ToString

func (e Route) ToString() string

type RouteGroup

type RouteGroup struct {
	*Router
	// contains filtered or unexported fields
}

func NewRouteGroup

func NewRouteGroup(router *Router, route string) *RouteGroup

func (*RouteGroup) Connect

func (group *RouteGroup) Connect(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Delete

func (group *RouteGroup) Delete(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Get

func (group *RouteGroup) Get(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (RouteGroup) Group

func (group RouteGroup) Group(prefix string) *RouteGroup

func (*RouteGroup) Handle

func (group *RouteGroup) Handle(path string, endpoint Endpoint, methods ...string) *RouteRouteGroupBuilder

func (*RouteGroup) Head

func (group *RouteGroup) Head(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Options

func (group *RouteGroup) Options(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Patch

func (group *RouteGroup) Patch(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Post

func (group *RouteGroup) Post(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Put

func (group *RouteGroup) Put(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Trace

func (group *RouteGroup) Trace(route string, endpoint Endpoint) *RouteRouteGroupBuilder

type RouteManager

type RouteManager []*Route

func (*RouteManager) AddRoute

func (r *RouteManager) AddRoute(routeToAdd *Route) *Route

func (*RouteManager) FindOverlappingRoute

func (r *RouteManager) FindOverlappingRoute(routeToCheck *Route) *Route

func (*RouteManager) RemoveRoute

func (r *RouteManager) RemoveRoute(toRemove *Route)

type RouteParamReader

type RouteParamReader map[string]string

RouteParamReader reads dynamic route params

func (RouteParamReader) Get

func (reader RouteParamReader) Get(key string) (string, bool)

func (RouteParamReader) GetDefault

func (reader RouteParamReader) GetDefault(key, defaultValue string) string

func (RouteParamReader) Has

func (reader RouteParamReader) Has(key string) bool

type RouteRouteGroupBuilder

type RouteRouteGroupBuilder struct {
	*Route
	*RouteGroup
}

func (*RouteRouteGroupBuilder) IgnoreCase

func (group *RouteRouteGroupBuilder) IgnoreCase() *RouteRouteGroupBuilder

func (*RouteRouteGroupBuilder) With added in v2.0.7

func (group *RouteRouteGroupBuilder) With(middleware Middleware) *RouteRouteGroupBuilder

With adds a middleware to the handler the method is called on

type Router

type Router struct {
	GlobalMiddlewares []Middleware

	*RouteGroup

	*RouterConfiguration

	HttpEngine
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter() *Router

func (*Router) IsDebugMode

func (router *Router) IsDebugMode() bool

func (*Router) IsProductionMode

func (router *Router) IsProductionMode() bool

func (Router) Listen

func (router Router) Listen(port Port) error

func (Router) ListenToTLS

func (router Router) ListenToTLS(port Port, certFile, keyFile string) error

func (*Router) ServeHTTP

func (router *Router) ServeHTTP(rw http.ResponseWriter, request *http.Request)

func (*Router) SetDebugMode

func (router *Router) SetDebugMode() *Router

func (*Router) SetProductionMode

func (router *Router) SetProductionMode() *Router

func (*Router) Use

func (router *Router) Use(middleware Middleware) *Router

Use registers a Middleware

type RouterConfiguration

type RouterConfiguration struct {
	*Serializers
	Handlers
}

RouterConfiguration is a simple place for the user to override the behavior of the router

type Serializers

type Serializers struct {
	JsonMarshal    func(interface{}) ([]byte, error)
	XmlMarshal     func(interface{}) ([]byte, error)
	YamlMarshal    func(interface{}) ([]byte, error)
	MsgpackMarshal func(interface{}) ([]byte, error)

	ErrorMarshal            func(interface{}) []byte
	ErrorMarshalContentType string
}

Directories

Path Synopsis
examples
basic command
crud command
middleware command

Jump to

Keyboard shortcuts

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