dolphin

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2021 License: MIT Imports: 13 Imported by: 0

README

Dolphin

test Codacy Badge Version Badge License Badge Go Reference

Dolphin is a simple web framework for Golang.

Installation

  1. Install dolphin by Go cli tool:

    go get -u github.com/ghosind/dolphin
    
  2. Import dolphin in your code:

    import "github.com/ghosind/dolphin"
    

Getting Started

  1. The following example shows how to implement a simple web service, and it'll reads parameter name from request query and return the message as a JSON object.

    package main
    
    import (
      "fmt"
    
      "github.com/ghosind/dolphin"
    )
    
    func handler(ctx *dolphin.Context) {
      name := ctx.Query("name")
    
      ctx.JSON(ctx.O{
        "message": fmt.Sprintf("Hello, %s", name),
      })
    }
    
    func main() {
      app := dolphin.Default()
    
      app.Use(handler)
    
      app.Run()
    }
    
  2. Save the above code as app.go and run it with the following command:

    go run app.go
    # Server running at :8080.
    
  3. Visit http://locahost:8080?name=dolphin by your browser or other tools to see the result.

Examples

Parameters in query string
func handler(ctx *dolphin.Context) {
  firstName := ctx.Query("firstName")
  lastName := ctx.QueryDefault("lastName", "Doe")

  ctx.JSON(ctx.O{
    "message": fmt.Sprintf("Hello, %s ", firstName, lastName),
  })
}
Parsed request body
type Payload struct {
  Name string `json:"name"`
}

func handler(ctx *dolphin.Context) {
  var payload Payload

  if err := ctx.PostJSON(&payload); err != nil {
    // Return 400 Bad Request
    ctx.Fail(ctx.O{
      "message": "Invalid payload",
    })
    return
  }

  ctx.JSON(ctx.O{
    "message": fmt.Sprintf("Hello, %s ", payload.Name),
  })
}
Custom middleware
func CustomMiddleware() {
  // Do something

  return func (ctx *dolphin.Context) {
    // Do something before following handlers

    ctx.Next()

    // Do something after following handlers
  }
}

func main() {
  app := dolphin.Default()

  app.Use(CustomMiddleware())

  // ...
}

License

Distributed under the MIT License. See LICENSE file for more information.

Documentation

Index

Constants

View Source
const (
	// HeaderContentType is the "Content-Type" header.
	HeaderContentType = "Content-Type"
	// Host is the "Host" header.
	HeaderHost = "Host"
	// HeaderLocation is the "Location" header.
	HeaderLocation = "Location"
	// HeaderReferrer is the "Referer" header.
	HeaderReferrer = "Referrer"
	// HeaderSetCookie is the "Set-Cookie" header.
	HeaderSetCookie = "Set-Cookie"
)

HTTP header names.

View Source
const (
	// MIMETypeJSON indicates the "application/json" MIME type.
	MIMETypeJSON = "application/json"
	// MIMETypeHTML indicates the "text/html" MIME type.
	MIMETypeHTML = "text/html"
	// MIMETypeText indicates the "text/plain" MIME type.
	MIMETypeText = "text/plain"
)

MIME types for HTTP content type.

Variables

View Source
var DebugWriter io.Writer = os.Stdout

DebugWriter is the writter used to print debug messages, default `os.Stdout`.

View Source
var ErrInvalidStatusCode = errors.New("invalid status code")

ErrInvalidStatusCode is returned by the response status code is not valid.

View Source
var ErrNoTLSCert = errors.New("no TLS certificate file")

ErrNoTLSCert is returned by the TLS server when no certificate file is provided.

View Source
var ErrNoTLSKey = errors.New("no TLS key file")

ErrNoTLSKey is returned by the TLS server when no private key file is provided.

View Source
var Version = "v0.1.2"

Version is the current dolphin framework version.

Functions

This section is empty.

Types

type App

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

App is the dolphin web server engine.

func Default

func Default() *App

Default creates a new App instance with default configuration.

func New

func New(config *Config) *App

New creates a new App instance.

func (*App) Run

func (app *App) Run()

Run starts the app and listens on the given port.

func (*App) RunTLS added in v0.1.1

func (app *App) RunTLS() error

RunTLS starts the app to provide HTTPS service and listens on the given port.

func (*App) ServeHTTP

func (app *App) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface.

func (*App) Shutdown

func (app *App) Shutdown(ctx ...context.Context) error

Shutdown tries to close active connections and stops the server.

func (*App) Use

func (app *App) Use(handlers ...HandlerFunc)

Use registers one or more middlewares or request handlers to the app.

type Config

type Config struct {
	// CertFile is the TLS certificate file.
	CertFile *string
	// KeyFile is the TLS private key file.
	KeyFile *string
	// Logger is the logger used by the app, dolphin will use log.Printf if this
	// have not set.
	Logger *log.Logger
	// Port is the port to listen on.
	Port int
}

Config is the configuration for the dolphin web application.

type Context

type Context struct {
	// Request is the wrapped HTTP request.
	Request *Request
	// Response is the wrapped HTTP response.
	Response *Response
	// contains filtered or unexported fields
}

Context is the context instance for the request.

func (*Context) Abort

func (ctx *Context) Abort()

Abort stops the current handler chain.

func (*Context) AddCookies

func (ctx *Context) AddCookies(cookies ...*http.Cookie)

AddCookies adds one or more given cookies to the response.

func (*Context) AddHeader

func (ctx *Context) AddHeader(key, val string)

AddHeader appends the given header pair to the response.

func (*Context) Cookie

func (ctx *Context) Cookie(key string) (*http.Cookie, error)

Cookie returns the named cookie provided in the request.

func (*Context) Fail

func (ctx *Context) Fail(data interface{}) error

Fail writes the given data to the response body as JSON, and set the status code to 400 (Bad Request).

func (*Context) File

func (ctx *Context) File(key string) (multipart.File, *multipart.FileHeader, error)

File returns the named file provided in the request.

func (*Context) Get

func (ctx *Context) Get(key string) (interface{}, bool)

Get retrieves the value of the given key from the context state.

func (*Context) HTML

func (ctx *Context) HTML(html string, statusCode ...int) error

HTML writes the given data to the response body as HTML, and set the content type to "text/html".

func (*Context) Has added in v0.1.1

func (ctx *Context) Has(key string) bool

Has returns true if the given key exists in the context state.

func (*Context) Header

func (ctx *Context) Header(key string) string

Header returns the header value from the request by the given key.

func (*Context) IP

func (ctx *Context) IP() string

IP returns the request client IP address.

func (*Context) JSON

func (ctx *Context) JSON(data interface{}, statusCode ...int) error

JSON stringifies and writes the given data to the response body, and set the content type to "application/json".

func (*Context) Log

func (ctx *Context) Log(fmt string, args ...interface{})

Log call the app logger with the given format and args.

func (*Context) Method

func (ctx *Context) Method() string

Method returns the request method.

func (*Context) MultiValuesHeader

func (ctx *Context) MultiValuesHeader(key string) []string

MultiValuesHeader returns a string array value for the given key from the request header.

func (*Context) MultiValuesQuery

func (ctx *Context) MultiValuesQuery(key string) []string

MultiValuesQuery returns a string array value for the given key from the request query.

func (*Context) MultiValuesQueryDefault

func (ctx *Context) MultiValuesQueryDefault(key string, defaultValues []string) []string

MultiValuesQueryDefault returns a string array value for the given key from the request query string, and returns the default values if the key is not exists.

func (*Context) Next

func (ctx *Context) Next()

Next calls the next handler in the handler chain.

func (*Context) Path

func (ctx *Context) Path() string

Path returns the request path.

func (*Context) Post

func (ctx *Context) Post() string

Post returns the request post data.

func (*Context) PostForm

func (ctx *Context) PostForm(key string) string

PostForm returns the request form data.

func (*Context) PostJSON

func (ctx *Context) PostJSON(payload interface{}) error

PostJSON gets request body and parses to the given struct.

func (*Context) Query

func (ctx *Context) Query(key string) string

Query returns the query value from the request by the given key.

func (*Context) QueryDefault

func (ctx *Context) QueryDefault(key, defaultValue string) string

QueryDefault returns the query value from the request by the given key, and returns the default value if the key is not found.

func (*Context) Redirect

func (ctx *Context) Redirect(url string, statusCode ...int)

Redirect redirects the request to the given URL, it'll set status code to 302 (Found) as default status code if it isn't set.

func (*Context) Set

func (ctx *Context) Set(key string, val interface{}) interface{}

Set sets the value of the given key to the context state.

func (*Context) SetContentType

func (ctx *Context) SetContentType(contentType string)

SetContentType sets the response HTTP header "Content-Type" field to the specific MIME type value.

func (*Context) SetHeader

func (ctx *Context) SetHeader(key, val string)

SetHeader sets the value of the given header key.

func (*Context) SetStatusCode

func (ctx *Context) SetStatusCode(code int) error

SetStatusCode sets the status code of the response.

func (*Context) String

func (ctx *Context) String(data string, statusCode ...int) error

String writes the given string to the response body, and sets the context type to "text/plain".

func (*Context) Success

func (ctx *Context) Success(data interface{}) error

Success writes the given data to the response body as JSON, and set the status code to 200 (OK).

func (*Context) Use

func (ctx *Context) Use(handlers ...HandlerFunc)

Use registers one or more middlewares or request handlers to the context.

func (*Context) Write added in v0.1.1

func (ctx *Context) Write(data []byte) (int, error)

Write writes the given data to the response body.

type HandlerChain

type HandlerChain []HandlerFunc

HandlerChain is a chain of handlers.

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc is the function that register as a handler to the app.

type O

type O map[string]interface{}

O is an alias for map that contains string key and interface{} value.

type Request

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

Request is the wrapped HTTP request object.

func (*Request) Cookie

func (req *Request) Cookie(key string) (*http.Cookie, error)

Cookie returns the cookie by the specific name.

func (*Request) File

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

File returns the file from multipart form by the specific key.

func (*Request) Header

func (req *Request) Header(key string) string

Header returns the value from the request header by the specific key.

func (*Request) Host

func (req *Request) Host() string

Host reads and returns the request "Host" header.

func (*Request) IP

func (req *Request) IP() string

IP returns the request client ip.

func (*Request) Method

func (req *Request) Method() string

Method returns the request method.

func (*Request) MultiValuesHeader

func (req *Request) MultiValuesHeader(key string) []string

MultiValuesHeader returns the string array type values from the request header by the specific key.

func (*Request) MultiValuesQuery

func (req *Request) MultiValuesQuery(key string) []string

MultiValuesQuery returns the string array type values from the request query string by the specific key.

func (*Request) Path

func (req *Request) Path() string

Path returns the request path.

func (*Request) Post

func (req *Request) Post() string

Post returns the body of the request.

func (*Request) PostForm

func (req *Request) PostForm(key string) string

PostForm returns the form data from the request by the specific key.

func (*Request) Query

func (req *Request) Query(key string) string

Query returns the query string value from the request by the specific key.

type Response

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

Response is the HTTP response wrapper.

func (*Response) AddCookies

func (resp *Response) AddCookies(cookies ...*http.Cookie)

AddCookies adds cookies setting to response, it will set response HTTP header "Set-Cookie" field.

func (*Response) AddHeader

func (resp *Response) AddHeader(key, val string)

AddHeader adds value to the specific response HTTP header field.

func (*Response) SetBody

func (resp *Response) SetBody(data []byte) (int, error)

SetBody sets response body.

func (*Response) SetHeader

func (resp *Response) SetHeader(key, val string)

SetHeader sets the specific response HTTP header field.

func (*Response) SetStatusCode

func (resp *Response) SetStatusCode(code int) error

SetStatusCode sets the status code of the response.

func (*Response) StatusCode

func (resp *Response) StatusCode() int

StatusCode gets the response status code.

Jump to

Keyboard shortcuts

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