goyave

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2019 License: MIT Imports: 23 Imported by: 0

README

Goyave Logo

Build Status Version Go Report Coverage Status License

An Elegant Golang Web Framework

Goyave is a progressive and accessible web application framework, aimed at making development easy and enjoyable. It has a philosophy of cleanliness and conciseness to make programs more elegant, easier to maintain and more focused.

Clean Code

Goyave has an expressive, elegant syntax, a robust structure and conventions. Minimalist calls and reduced redundancy are among the Goyave's core principles.

Fast Development

Develop faster and concentrate on the business logic of your application thanks to the many helpers and built-in functions.

Powerful functionalities

Goyave is accessible, yet powerful. The framework includes routing, request parsing, validation, localization, and more!

Most golang frameworks for web development don't have a strong directory structure nor conventions to make applications have a uniform architecture and limit redundancy. This makes it difficult to work with them on different projects. In companies, having a well-defined and documented architecture helps new developers integrate projects faster, and reduces the time needed for maintaining them. For open source projects, it helps newcomers understanding the project and makes it easier to contribute.

Getting Started

Install using the template project

You can bootstrap your project using the Goyave template project. This project has a complete directory structure already set up for you.

Linux / MacOS
$ curl https://raw.githubusercontent.com/System-Glitch/goyave/master/install.sh | bash -s my-project
Windows (Powershell)
> & ([scriptblock]::Create((curl "https://raw.githubusercontent.com/System-Glitch/goyave/master/install.ps1").Content)) -projectName my-project

Run go run my-project in your project's directory to start the server, then try to request the hello route.

$ curl http://localhost:8080/hello
Hi!

Hello world from scratch

The example below shows a basic Hello world application using Goyave.

import "github.com/System-Glitch/goyave/v2"

func registerRoutes(router *goyave.Router) {
	router.Route("GET", "/hello", func(response *goyave.Response, request *goyave.Request) {
	    response.String(http.StatusOK, "Hello world!")
    }, nil)
}

func main() {
	goyave.Start(registerRoutes)
}

Learning Goyave

The Goyave framework has an extensive documentation covering in-depth subjects and teaching you how to run a project using Goyave from setup to deployment.

Read the documentation

Requirements

  • Go 1.13+
  • Go modules

Contributing

Thank you for considering contributing to the Goyave framework! You can find the contribution guide in the documentation.

I have many ideas for the future of Goyave. I would be infinitely grateful to whoever want to support me and let me continue working on Goyave and making it better and better.

You can support also me on Patreon:

Contributors

A big "Thank you" to the Goyave contributors:

License

The Goyave framework is MIT Licensed. Copyright © 2019 Jérémy LAMBERT (SystemGlitch)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearStartupHooks

func ClearStartupHooks()

ClearStartupHooks removes all startup hooks.

func IsReady

func IsReady() bool

IsReady returns true if the server has finished initializing and is ready to serve incoming requests.

func RegisterStartupHook

func RegisterStartupHook(hook func())

RegisterStartupHook to execute some code once the server is ready and running.

func Start

func Start(routeRegistrer func(*Router))

Start starts the web server. The routeRegistrer parameter is a function aimed at registering all your routes and middlewares.

 import (
     "github.com/System-Glitch/goyave/v2"
     "my-project/route"
 )

 func main() {
	    goyave.start(route.Register)
 }

Panic if the server is already running.

func Stop

func Stop()

Stop gracefully shuts down the server without interrupting any active connections.

Make sure the program doesn't exit and waits instead for Stop to return.

Stop does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Stop should separately notify such long-lived connections of shutdown and wait for them to close, if desired.

Types

type Handler

type Handler func(*Response, *Request)

Handler is a controller or middleware function

func NativeHandler

func NativeHandler(handler http.Handler) Handler

NativeHandler is an adapter function for "http.Handler". With this adapter, you can plug non-Goyave handlers to your application.

If the request is a JSON request, the native handler will not be able to read the body, as it has already been parsed by the framework and is stored in the "goyave.Request" object. However, form data can be accessed as usual. Just remember that it contains the raw data, which haven't been validated nor converted. This means that native handlers are not guaranteed to work and cannot modify the request data. Prefer implementing a Goyave handler.

This feature is a compatibility layer with the rest of the Golang web ecosystem. Prefer using Goyave handlers if possible.

type Middleware

type Middleware func(Handler) Handler

Middleware function generating middleware handler function.

Request data is available to middlewares, but bear in mind that it had not been validated yet. That means that you can modify or filter data. (Trim strings for example)

func NativeMiddleware

func NativeMiddleware(middleware mux.MiddlewareFunc) Middleware

NativeMiddleware is an adapter function "mux.MiddlewareFunc". With this adapter, you can plug Gorilla Mux middleware to your application.

Native middleware work like native handlers. See "NativeHandler" for more details.

type Request

type Request struct {
	Rules  validation.RuleSet
	Data   map[string]interface{}
	Params map[string]string
	Lang   string
	// contains filtered or unexported fields
}

Request struct represents an http request. Contains the validated body in the Data attribute if the route was defined with a request generator function

func (*Request) Bool

func (r *Request) Bool(field string) bool

Bool get a bool field from the request data. Panics if the field is not a bool.

func (*Request) ContentLength

func (r *Request) ContentLength() int64

ContentLength records the length of the associated content. The value -1 indicates that the length is unknown.

func (*Request) Cookies

func (r *Request) Cookies(name string) []*http.Cookie

Cookies returns the HTTP cookies sent with the request.

func (*Request) Date

func (r *Request) Date(field string) time.Time

Date get a date field from the request data. Panics if the field is not a date.

func (*Request) File

func (r *Request) File(field string) []filesystem.File

File get a file field from the request data. Panics if the field is not numeric.

func (*Request) Has

func (r *Request) Has(field string) bool

Has check if the given field exists in the request data.

func (*Request) Header

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

Header contains the request header fields either received by the server or to be sent by the client. Header names are case-insensitive.

If the raw request has the following header lines,

Host: example.com
accept-encoding: gzip, deflate
Accept-Language: en-us
fOO: Bar
foo: two

then the header map will look like this:

Header = map[string][]string{
	"Accept-Encoding": {"gzip, deflate"},
	"Accept-Language": {"en-us"},
	"Foo": {"Bar", "two"},
}

func (*Request) IP

func (r *Request) IP(field string) net.IP

IP get an IP field from the request data. Panics if the field is not an IP.

func (*Request) Integer

func (r *Request) Integer(field string) int

Integer get an integer field from the request data. Panics if the field is not an integer.

func (*Request) Method

func (r *Request) Method() string

Method specifies the HTTP method (GET, POST, PUT, etc.).

func (*Request) Numeric

func (r *Request) Numeric(field string) float64

Numeric get a numeric field from the request data. Panics if the field is not numeric.

func (*Request) Protocol

func (r *Request) Protocol() string

Protocol the protocol used by this request, "HTTP/1.1" for example.

func (*Request) Referrer

func (r *Request) Referrer() string

Referrer returns the referring URL, if sent in the request.

func (*Request) RemoteAddress

func (r *Request) RemoteAddress() string

RemoteAddress allows to record the network address that sent the request, usually for logging.

func (*Request) String

func (r *Request) String(field string) string

String get a string field from the request data. Panics if the field is not a string.

func (*Request) Timezone

func (r *Request) Timezone(field string) *time.Location

Timezone get a timezone field from the request data. Panics if the field is not a timezone.

func (*Request) URI

func (r *Request) URI() *url.URL

URI specifies the URI being requested. Use this if you absolutely need the raw query params, url, etc. Otherwise use the provided methods and fields of the "goyave.Request".

func (*Request) URL

func (r *Request) URL(field string) *url.URL

URL get an URL field from the request data. Panics if the field is not an URL.

func (*Request) UUID

func (r *Request) UUID(field string) uuid.UUID

UUID get a UUID field from the request data. Panics if the field is not a UUID.

func (*Request) UserAgent

func (r *Request) UserAgent() string

UserAgent returns the client's User-Agent, if sent in the request.

type Response

type Response struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

Response represents a controller response.

func CreateTestResponse

func CreateTestResponse(recorder http.ResponseWriter) *Response

CreateTestResponse create an empty response with the given response writer. This function is aimed at making it easier to unit test Responses.

writer := httptest.NewRecorder()
response := goyave.CreateTestResponse(writer)
response.Status(http.StatusNoContent)
result := writer.Result()
fmt.Println(result.StatusCode) // 204

func (*Response) Cookie

func (r *Response) Cookie(cookie *http.Cookie)

Cookie add a Set-Cookie header to the response. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Response) Download

func (r *Response) Download(file string, fileName string) error

Download write a file as an attachment element. Automatically detects the file MIME type and sets the "Content-Type" header accordingly. It is advised to call "filesystem.FileExists()" before sending a file to avoid a panic and return a 404 error if the file doesn't exist. The given path can be relative or absolute.

The "fileName" parameter defines the name the client will see. In other words, it sets the header "Content-Disposition" to "attachment; filename="${fileName}""

If you want the file to be sent as an inline element ("Content-Disposition: inline"), use the "File" function instead.

func (*Response) Error

func (r *Response) Error(err interface{}) error

Error print the error in the console and return it with an error code 500. If debugging is enabled in the config, the error is also written in the response and the stacktrace is printed in the console.

func (*Response) File

func (r *Response) File(file string) error

File write a file as an inline element. Automatically detects the file MIME type and sets the "Content-Type" header accordingly. It is advised to call "filesystem.FileExists()" before sending a file to avoid a panic and return a 404 error if the file doesn't exist. The given path can be relative or absolute.

If you want the file to be sent as a download ("Content-Disposition: attachment"), use the "Download" function instead.

func (*Response) Header

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

Header returns the header map that will be sent.

func (*Response) JSON

func (r *Response) JSON(responseCode int, data interface{}) error

JSON write json data as a response. Also sets the "Content-Type" header automatically

func (*Response) Redirect

func (r *Response) Redirect(url string)

Redirect send a permanent redirect response

func (*Response) Status

func (r *Response) Status(status int)

Status write the given status code

func (*Response) String

func (r *Response) String(responseCode int, message string) error

String write a string as a response

func (*Response) TemporaryRedirect

func (r *Response) TemporaryRedirect(url string)

TemporaryRedirect send a temporary redirect response

func (*Response) Write

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

Write writes the data as a response. See http.ResponseWriter.Write

func (*Response) WriteHeader

func (r *Response) WriteHeader(status int)

WriteHeader sends an HTTP response header with the provided status code.

type Router

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

Router registers routes to be matched and dispatches a handler.

func (*Router) Middleware

func (r *Router) Middleware(middleware ...Middleware)

Middleware apply one or more middleware(s) to the route group.

func (*Router) Route

func (r *Router) Route(methods string, uri string, handler Handler, validationRules validation.RuleSet)

Route register a new route.

Multiple methods can be passed using a pipe-separated string.

"PUT|PATCH"

The validation rules set is optional. If you don't want your route to be validated, pass "nil".

func (*Router) Static

func (r *Router) Static(uri string, directory string, download bool)

Static serve a directory and its subdirectories of static resources. Set the "download" parameter to true if you want the files to be sent as an attachment instead of an inline element.

If no file is given in the url, or if the given file is a directory, the handler will send the "index.html" file if it exists.

func (*Router) Subrouter

func (r *Router) Subrouter(prefix string) *Router

Subrouter create a new sub-router from this router. Use subrouters to create route groups and to apply middleware to multiple routes.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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