pure

package module
v0.0.0-...-900990e Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2017 License: MIT Imports: 16 Imported by: 0

README

Pure

A small-yet-beautiful pure JSON API Web Framework, 1.0.1.

小而美的纯JSON API Web开发框架,版本1.0.1

GitHub stars GitHub license GoDoc

Features

  1. Small yet beautiful, pure JSON API support by default;

    小而美,默认支持纯JSON API

  2. Using Web middlewares to extend its funcionality;

    使用Web中间件扩展框架功能

  3. Extremely light-weight, easy to use, write less, behave more elegant;

    超轻量级,容易使用,写更少的代码,表现更加优雅

  4. Supporting TLS;

    支持TLS

Requirements

Installation

go get -u -v github.com/leesper/pure

Example

1. A simple "hello, world" example:
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/leesper/holmes"
	"github.com/leesper/pure"
)

func main() {
	defer holmes.Start().Stop()
	pure.API("greeting").Version("apiv1").Class("hello").Get().Post().Handle(hello{}).With(
		pure.JSONMiddle,
		pure.LoggerMiddle,
	).Done()
	holmes.Errorln(pure.Run(5050))
}

type hello struct {
	Name string `json:"name"`
}

func (h hello) Handle(ctx context.Context) interface{} {
	switch pure.HTTPMethod(ctx) {
	case http.MethodGet:
		return helloRsp{fmt.Sprintf("hi, guest")}
	case http.MethodPost:
		return helloRsp{fmt.Sprintf("hello, %s", h.Name)}
	}
	return helloRsp{fmt.Sprintf("Sorry, I don't know your %s", pure.HTTPMethod(ctx))}
}

type helloRsp struct {
	Greeting string `json:"greeting"`
}

Use curl -H "Content-Type: application/json" -X POST -d '{"name": "Fiona"}' http://localhost:5050/apiv1/hello/greeting to get a {"greeting":"hello, Fiona"} back.

Use curl -H "Content-Type: application/json" -X GET http://localhost:5050/apiv1/hello/greeting to get a {"greeting":"hi, guest"} back.

2. Web middlewares supported
  • JSONMiddle: A Content-Type checker for application/json
  • MultipartFormMiddle: For multipart/form-data requests
  • CORSMiddle: Cross-origin resource sharing
  • RecoverPanicMiddle: Recover from server panic
  • LoggerMiddle: logging about HTTP request details

License

MIT

Changelog

1.0.1
  1. Replace Use(...) with With(...)
  2. One can now declare an API which can handle both GET and POST request
  3. Make the framework depending on the official log package
  4. Add utility functions for retrieving HTTP method or multi-part form from context
  5. Add functions for closing server gracefully

More Documentation

Pure - 小而美的JSON Web API框架

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

Documentation

Index

Constants

View Source
const (
	ContentType       = "Content-Type"
	ApplicationJSON   = "application/json"
	MultipartFormData = "multipart/form-data"
	AcceptLanguage    = "Accept-Language"
	Authorization     = "Authorization"
	UserAgent         = "User-Agent"
	AllowOrigin       = "Access-Control-Allow-Origin"
)

definitions for HTTP headers.

Variables

View Source
var (
	// JSONMiddle checks whether it is a JSON request.
	JSONMiddle = negroni.HandlerFunc(jsonMiddleware)
	// MultipartFormMiddle checks whether it is a multipart/form-data request.
	MultipartFormMiddle = negroni.HandlerFunc(multipartFormMiddleware)
	// CORSMiddle handle CORS request, see https://github.com/rs/cors
	CORSMiddle = negroni.HandlerFunc(corsMiddleware)
	// RecoverPanicMiddle recovers and records the stack info when panic occurred.
	// This prevents web server from crashing.
	RecoverPanicMiddle = negroni.HandlerFunc(recoverPanicMiddleWare)
	// LoggerMiddle adds statistic information for every request.
	LoggerMiddle = negroni.HandlerFunc(loggerMiddleware)
)

Functions

func HTTPMethod

func HTTPMethod(ctx context.Context) string

HTTPMethod returns the HTTP method of request associated in Context.

func MultipartForm

func MultipartForm(ctx context.Context) *multipart.Form

MultipartForm returns the multipart form data associated in Context.

func Run

func Run(port int) error

Run starts a web server.

func RunElegant

func RunElegant(port int, timeout time.Duration) error

RunElegant starts a web server which can be shutdown gracefully with a timout.

func RunTLS

func RunTLS(port int, cert, key string) error

RunTLS starts a TLS-based web server.

func RunTLSElegant

func RunTLSElegant(port int, timeout time.Duration, cert, key string) error

RunTLSElegant starts a TLS-based web server which can be shutdown gracefully with a timeout.

func ServeFile

func ServeFile(path, dir string)

ServeFile serves HTTP requests with the contents of the filesystem rooted at dir.

Types

type APIBuilder

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

APIBuilder is responsible for building APIs. Please don't operate it directly, use chaining calls instead.

func API

func API(name string) *APIBuilder

API returns a new APIBuilder for buiding API.

func (*APIBuilder) Class

func (b *APIBuilder) Class(c string) *APIBuilder

Class defines the API class.

func (*APIBuilder) Done

func (b *APIBuilder) Done()

Done triggers APIBuilder to build and register an API.

func (*APIBuilder) Get

func (b *APIBuilder) Get() *APIBuilder

Get marks API an HTTP GET request.

func (*APIBuilder) Handle

func (b *APIBuilder) Handle(h Handler) *APIBuilder

Handle defines the handler of request.

func (*APIBuilder) HandleFunc

func (b *APIBuilder) HandleFunc(f func(ctx context.Context) interface{}) *APIBuilder

HandleFunc defines the handler function of request.

func (*APIBuilder) Post

func (b *APIBuilder) Post() *APIBuilder

Post marks API an HTTP POST request.

func (*APIBuilder) Version

func (b *APIBuilder) Version(v string) *APIBuilder

Version defines the API version.

func (*APIBuilder) With

func (b *APIBuilder) With(handlers ...negroni.Handler) *APIBuilder

With adds a series of middleware plugins to the API.

type ContextKey

type ContextKey string

ContextKey is a type wrapper for context key

type Handler

type Handler interface {
	Handle(ctx context.Context) interface{}
}

Handler defines the interface of JSON request handler.

type HandlerFunc

type HandlerFunc func(ctx context.Context) interface{}

HandlerFunc is an adapter to allow the use of ordinary functions as handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler object that calls f.

func (HandlerFunc) Handle

func (hf HandlerFunc) Handle(ctx context.Context) interface{}

Handle calls HandlerFunc itself.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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