rider

package module
v0.0.0-...-d5d3d2f Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2021 License: MIT Imports: 15 Imported by: 0

README

Rider

build Coverage Status

Fast and simple web framework for Go. Inspired by the most popular node.js web framework, express.js.

It implements ServeHTTP interface so you can use express style routing. It also wraps and extends the net/http Request and ResponseWriter into an easy to read and use function signature.

Get Started

Init folder and install:

mkdir app
cd app
go mod init myapp
go get github.com/fastrodev/rider

Create main.go file:

Source code: https://github.com/fastrodev/examples

package main

import "github.com/fastrodev/rider"

func handler(req rider.Request, res rider.Response) {
    res.Send("hello")
}

func createApp() rider.Router {
    app := rider.New()
    app.Get("/", handler)
    return app
}

func main() {
    createApp().Listen(9000)
}

Run webapp:

go run main.go

Cloud Function

Cloud Functions is a serverless execution environment for building and connecting cloud services. With Cloud Functions you write simple, single-purpose functions that are attached to events emitted from your cloud infrastructure and services. Your function is triggered when an event being watched is fired.

You can deploy your codes to google cloud function. With this approach, you don't call the Listen function again. You must create a new function as the entry point for standard net/http Request and ResponseWriter.

Source code: https://github.com/fastrodev/serverless

package serverless

import (
    "net/http"

    "github.com/fastrodev/rider"
)

func handler(req rider.Request, res rider.Response) {
    res.Json(`{"message":"ok"}`)
}

func createApp() rider.Router {
    app := rider.New()
    app.Get("/", handler)
    return app
}

func HelloHTTP(w http.ResponseWriter, r *http.Request) {
    createApp().ServeHTTP(w, r)
}

How to deploy:

gcloud functions deploy HelloHTTP --runtime go113 --trigger-http --allow-unauthenticated

Contributing

We appreciate your help! The main purpose of this repository is to improve performance and readability, making it faster and easier to use.

Documentation

Index

Constants

View Source
const (
	HeaderContentType   = "Content-Type"
	MimeApplicationJson = "application/json"
	MimeTextHtml        = "text/html; charset=UTF-8"
)

Variables

This section is empty.

Functions

func NewCookie

func NewCookie() httpCookie

Types

type ErrMiddleware

type ErrMiddleware struct {
	Error error
	Code  int
}

type Handler

type Handler func(Request, Response)

type HandlerFunc

type HandlerFunc func(Request, Response)

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Middleware

type Middleware func(Request, Response, Next)

type Next

type Next func(Request, Response)

type Request

type Request struct {
	Method           string
	URL              *url.URL
	Proto            string
	ProtoMajor       int
	ProtoMinor       int
	Header           http.Header
	Body             io.ReadCloser
	GetBody          func() (io.ReadCloser, error)
	ContentLength    int64
	TransferEncoding []string
	Close            bool
	Host             string
	Form             url.Values
	PostForm         url.Values
	MultipartForm    *multipart.Form
	Trailer          http.Header
	RemoteAddr       string
	RequestURI       string
	TLS              *tls.ConnectionState
	Cancel           <-chan struct{}
	Response         *http.Response
	// contains filtered or unexported fields
}

func (*Request) AddCookie

func (h *Request) AddCookie(c *http.Cookie)

func (*Request) BasicAuth

func (h *Request) BasicAuth() (username string, password string, ok bool)

func (*Request) Clone

func (h *Request) Clone(ctx context.Context) *http.Request

func (*Request) Context

func (h *Request) Context() context.Context

func (*Request) Cookie

func (h *Request) Cookie(name string) (httpCookie, error)

func (*Request) Cookies

func (h *Request) Cookies() []*http.Cookie

func (*Request) ErrorMiddleware

func (h *Request) ErrorMiddleware(e error, code int) Request

func (*Request) FormFile

func (h *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

func (*Request) FormValue

func (h *Request) FormValue(key string) string

func (*Request) MultipartReader

func (h *Request) MultipartReader() (*multipart.Reader, error)

func (*Request) ParseForm

func (h *Request) ParseForm() error

func (*Request) ParseMultipartForm

func (h *Request) ParseMultipartForm(maxMemory int64) error

func (*Request) ProtoAtLeast

func (h *Request) ProtoAtLeast(major int, minor int) bool

func (*Request) Referer

func (h *Request) Referer() string

func (*Request) UserAgent

func (h *Request) UserAgent() string

func (*Request) WithContext

func (h *Request) WithContext(ctx context.Context) Request

func (*Request) Write

func (h *Request) Write(w io.Writer) error

func (*Request) WriteProxy

func (h *Request) WriteProxy(w io.Writer) error

type Response

type Response interface {
	// Get header
	Header() http.Header
	// Write writes the data to the connection as part of an HTTP reply.
	Write([]byte) (int, error)
	// WriteHeader sends an HTTP response header with the provided status code.
	WriteHeader(statusCode int)
	// Sets the response’s HTTP header field to value
	Set(string, string) Response
	// Sets the HTTP status for the response
	Status(int) Response
	// Sets the Content-Type HTTP header to the MIME type as determined by the specified type.
	Type(string) Response
	// Sends a JSON response.
	Json(data interface{})
	// Sends the HTTP response.
	Send(data interface{})
	// Sets a created cookie.
	Cookie(httpCookie) Response
	// Clears the cookie specified by name.
	ClearCookie(cookie httpCookie) Response
	// Redirects to the URL derived from the specified path, with specified status.
	Redirect(path string, code int)
	// Sets the response Location HTTP header to the specified path parameter.
	Location(path string) Response
	// Appends the specified value to the HTTP response header field.
	Append(key string, val string) Response
	// Renders a view and sends the rendered HTML string to the client.
	Render(args ...interface{}) error
}

type Router

type Router interface {
	// Routes HTTP GET requests to the specified path with the specified callback functions.
	Get(string, Handler, ...Middleware) Router
	// Routes HTTP CONNECT requests to the specified path with the specified callback functions
	Connect(string, Handler, ...Middleware) Router
	// Routes HTTP DELETE requests to the specified path with the specified callback functions
	Delete(string, Handler, ...Middleware) Router
	// Routes HTTP HEAD requests to the specified path with the specified callback functions
	Head(string, Handler, ...Middleware) Router
	// Routes HTTP PUT requests to the specified path with the specified callback functions
	Put(string, Handler, ...Middleware) Router
	// Routes HTTP PATCH requests to the specified path with the specified callback functions
	Patch(string, Handler, ...Middleware) Router
	// Routes HTTP TRACE requests to the specified path with the specified callback functions
	Trace(string, Handler, ...Middleware) Router
	// Routes HTTP POST requests to the specified path with the specified callback functions
	Post(string, Handler, ...Middleware) Router
	// Mounts the specified middleware function
	Use(Middleware) Router
	// Sets static files
	Static(folder string, path ...string) Router
	// Sets a logger
	Log(*log.Logger) Router
	// Sets a context
	Ctx(context.Context) Router
	// Binds and listens for connections on the specified host and port.
	Listen(port int, args ...interface{}) error
	// ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL.
	ServeHTTP(w http.ResponseWriter, r *http.Request)
	// Sets a host name
	Host(string) Router
	// ParseFiles creates a new Template and parses the template definitions from the named files.
	Template(path string) Router
	// SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. By default, keep-alives are always enabled.
	// Only very resource-constrained environments or servers in the process of shutting down should disable them.
	SetKeepAlivesEnabled(v bool)
	// RegisterOnShutdown registers a function to call on Shutdown.
	// This can be used to gracefully shutdown connections that have undergone ALPN protocol upgrade or
	// that have been hijacked. This function should start protocol-specific graceful shutdown,
	// but should not wait for shutdown to complete.
	RegisterOnShutdown(f func())
	// Close immediately closes all active net.Listeners and any connections in state StateNew,
	// StateActive, or StateIdle. For a graceful shutdown, use Shutdown.
	//
	// Close does not attempt to close (and does not even know about) any hijacked connections, such as WebSockets.
	//
	// Close returns any error returned from closing the Server's underlying Listener(s).
	Close() error
	// Shutdown gracefully shuts down the server without interrupting any active connections.
	// Shutdown works by first closing all open listeners, then closing all idle connections,
	// and then waiting indefinitely for connections to return to idle and then shut down.
	// If the provided context expires before the shutdown is complete, Shutdown returns the context's error,
	// otherwise it returns any error returned from closing the Server's underlying Listener(s).
	//
	// When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return
	// ErrServerClosed. Make sure the program doesn't exit and waits instead for Shutdown to return.
	//
	// Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets.
	// The caller of Shutdown should separately notify such long-lived connections of shutdown and
	// wait for them to close, if desired. See RegisterOnShutdown for a way to register shutdown notification functions.
	//
	// Once Shutdown has been called on a server, it may not be reused; future calls to methods
	// such as Serve will return ErrServerClosed.
	Shutdown(ctx context.Context)
}

func New

func New() Router

Jump to

Keyboard shortcuts

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