napnap

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2020 License: MIT Imports: 21 Imported by: 17

README

NapNap

install

  1. Download and install it:

    $ go get github.com/jasonsoft/napnap
    
  2. Import it in your code:

    import "github.com/jasonsoft/napnap"
    

Getting Started

hello world example
package main

import (
	"net/http"
	"github.com/jasonsoft/napnap"
)

func main() {
	nap := napnap.New()

	nap.Get("/", func(c *napnap.Context) error {
		return c.String(200, "Hello World")
	})

	http.ListenAndServe("127.0.0.1:10080", nap)
}
Using GET, POST, PUT, PATCH, DELETE and OPTIONS
package main

import (
	"github.com/jasonsoft/napnap"
)

func main() {
	nap := napnap.New()

	nap.Get("/my-get", myHeadEndpoint)
	nap.Post("/my-post", myPostEndpoint)
	nap.Put("/my-put", myPutEndpoint)
	nap.Delete("/my-delete", myDeleteEndpoint)
	nap.Patch("/my-patch", myPatchEndpoint)
	nap.Options("/my-options", myOptionsEndpoint)
	nap.Head("/my-head", myHeadEndpoint)

	http.ListenAndServe("127.0.0.1:10080", nap)
}
Parameters in path
package main

import (
	"github.com/jasonsoft/napnap"
)

func main() {
	nap := napnap.New()

	nap.Get("/users/:name", func(c *napnap.Context) error {
		name := c.Param("name")
		return c.String(200, "Hello, "+name)
	})

	// /videos/sports/basketball/1.mp4
	// /videos/2.mp4
	// both path will route to the endpoint
	nap.Get("/videos/*video_id", func(c *napnap.Context) error {
		id := c.Param("video_id")
		return c.String(200, "video id is, "+id)
	})

	http.ListenAndServe("127.0.0.1:10080", nap)
}
Get querystring value
package main

import (
	"github.com/jasonsoft/napnap"
)

func main() {
	nap := napnap.New()

	nap.Get("/test?page=1", func(c *napnap.Context) error {
		page := c.Query("page") //get query string value
		return c.String(200, page)
	})

	http.ListenAndServe("127.0.0.1:10080", nap)
}
Get post form value (Multipart/Urlencoded Form)
package main

import (
	"github.com/jasonsoft/napnap"
)

func main() {
	nap := napnap.New()

	nap.Post("/post-form-value", func(c *napnap.Context) error {
		userId := c.Form("user_id") //get post form value
		return c.String(200, userId)
	})

	http.ListenAndServe("127.0.0.1:10080", nap)
}
JSON binding
package main

import "github.com/jasonsoft/napnap"

func main() {
	nap := napnap.New()

	nap.Post("/json-binding", func(c *napnap.Context) error {
		var person struct {
			Name string `json: name`
			Age  int    `json: age`
		}
        err := c.BindJSON(&person)
        if err != nil {
            return err
        }
		c.String(200, person.Name)
        return nil
	})

	http.ListenAndServe("127.0.0.1:10080", nap)
}
JSON rendering
package main

import "github.com/jasonsoft/napnap"

func main() {
	nap := napnap.New()

	nap.Get("/json-rendering", func(c *napnap.Context) error {
		var person struct {
			Name string `json: name`
			Age  int    `json: age`
		}

		person.Name = "napnap"
		person.Age = 18

		return c.JSON(200, person)
	})

	http.ListenAndServe("127.0.0.1:10080", nap) 
}
Http/2 Server
package main

import "github.com/jasonsoft/napnap"

func main() {
	router := napnap.NewRouter()

	router.Get("/hello-world", func(c *napnap.Context) {
		c.String(200, "Hello, World")
	})

	nap := napnap.New()
	nap.Use(router)
	nap.RunTLS(":443", "cert.crt", "key.pem") // nap will use http/2 server as default
}
combine with autocert

Let's Encrypt disable tls challenge, so we can only use http challenge with autocert(dns challenge not implemented)

notes:

we need to bind http service on 80 port, https service on 443 port. First time, you need to wait a short time for creating and downloading certificate .

package main

import "github.com/jasonsoft/napnap"

func main() {
	router := napnap.NewRouter()

	projRoot, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err.Error())
	}

	config := napnap.Config{
		Domain:        "exmaple.com", // multi domain support ex. "abc.com, 123.com"
		CertCachePath: path.Join(projRoot, ".certCache"),
	}
	server := napnap.NewHttpEngineWithConfig(&config)

	nap := napnap.New()
	nap.Use(router)

	nap.RunAutoTLS(server)
}

Roadmap

We are planning to add those features in the future.

  • logging middleware

We support the following features

  • golang standard context
  • routing features (static, parameterized, any)
  • custom middleware
  • http/2 (https only)
  • rendering
  • json binding

Documentation

Index

Constants

View Source
const (
	// CONNECT HTTP method
	CONNECT = "CONNECT"
	// DELETE HTTP method
	DELETE = "DELETE"
	// GET HTTP method
	GET = "GET"
	// HEAD HTTP method
	HEAD = "HEAD"
	// OPTIONS HTTP method
	OPTIONS = "OPTIONS"
	// PATCH HTTP method
	PATCH = "PATCH"
	// POST HTTP method
	POST = "POST"
	// PUT HTTP method
	PUT = "PUT"
	// TRACE HTTP method
	TRACE = "TRACE"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Addr          string
	Domain        string // abc123.com, abc456.com
	CertCachePath string
	TLSCertFile   string
	TLSKeyFile    string
	ReadTimeout   time.Duration
	WriteTimeout  time.Duration
}

Config ...

type Context

type Context struct {
	NapNap  *NapNap
	Request *http.Request
	Writer  ResponseWriter
	// contains filtered or unexported fields
}

Context represents the context of the current HTTP request. It holds request and response objects, path, path parameters, data and registered handler.

func FromContext

func FromContext(ctx gcontext.Context) (*Context, bool)

FromContext return a napnap context from the standard context

func NewContext

func NewContext(napnap *NapNap, req *http.Request, writer ResponseWriter) *Context

NewContext returns a new context instance

func (*Context) BindJSON

func (c *Context) BindJSON(obj interface{}) error

BindJSON binds the request body into provided type `obj`. The default binder does it based on Content-Type header.

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP implements a best effort algorithm to return the real client IP, it parses X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy. Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.

func (*Context) ContentType

func (c *Context) ContentType() string

ContentType returns the Content-Type header of the request.

func (*Context) Cookie

func (c *Context) Cookie(name string) (string, error)

Cookie returns cookie value

func (*Context) DeviceType

func (c *Context) DeviceType() string

DeviceType returns user's device type which includes web, mobile, tab, tv

func (*Context) Form

func (c *Context) Form(key string) string

Form returns form parameter by key.

func (*Context) FormFile

func (c *Context) FormFile(key string) (*multipart.FileHeader, error)

FormFile returns file.

func (*Context) Get

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

Get retrieves data from the context.

func (*Context) JSON

func (c *Context) JSON(code int, i interface{}) error

JSON returns json format

func (*Context) MustGet

func (c *Context) MustGet(key string) interface{}

MustGet returns the value for the given key if it exists, otherwise it panics.

func (*Context) Param

func (c *Context) Param(name string) string

Param returns form values by parameter

func (*Context) ParamInt

func (c *Context) ParamInt(key string) (int, error)

ParamInt returns parameter by key and cast the value to int.

func (*Context) Query

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

Query returns query parameter by key.

func (*Context) QueryInt

func (c *Context) QueryInt(key string) (int, error)

QueryInt returns query parameter by key and cast the value to int.

func (*Context) QueryIntWithDefault

func (c *Context) QueryIntWithDefault(key string, defaultValue int) (int, error)

QueryIntWithDefault returns query parameter by key and cast the value to int. If the value doesn't exist, the default value will be used.

func (*Context) Redirect

func (c *Context) Redirect(code int, location string) error

Redirect returns a HTTP redirect to the specific location.

func (*Context) Render

func (c *Context) Render(code int, viewName string, data interface{}) error

Render returns html format

func (*Context) RequestHeader

func (c *Context) RequestHeader(key string) string

RequestHeader is a intelligent shortcut for c.Request.Header.Get(key)

func (*Context) RespHeader

func (c *Context) RespHeader(key, value string)

RespHeader is a intelligent shortcut for c.Writer.Header().Set(key, value) It writes a header in the response. If value == "", this method removes the header `c.Writer.Header().Del(key)`

func (*Context) SaveUploadedFile

func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) (err error)

SaveUploadedFile uploads the form file to specific dst.

func (*Context) Set

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

Set saves data in the context. It also lazy initializes c.Keys if it was not used previously.

func (*Context) SetCookie

func (c *Context) SetCookie(
	name string,
	value string,
	maxAge int,
	path string,
	domain string,
	secure bool,
	httpOnly bool,
)

SetCookie allows us to create an cookie

func (*Context) SetStatus

func (c *Context) SetStatus(code int)

SetStatus is a intelligent shortcut for c.Writer.WriteHeader(code)

func (*Context) SetStdContext

func (c *Context) SetStdContext(ctx context.Context)

SetStdContext allow us to save the golang context to request

func (*Context) Status

func (c *Context) Status() int

Status is a intelligent shortcut for c.Writer.Status()

func (*Context) StdContext

func (c *Context) StdContext() context.Context

StdContext return golang standard context

func (*Context) String

func (c *Context) String(code int, s string) error

String returns string format

type ErrorHandler added in v1.1.0

type ErrorHandler func(c *Context, err error)

ErrorHandler defines a function to handle HTTP errors

type HandlerFunc

type HandlerFunc func(c *Context) error

HandlerFunc defines a function to server HTTP requests

func WrapHandler

func WrapHandler(h http.Handler) HandlerFunc

WrapHandler wraps `http.Handler` into `napnap.HandlerFunc`.

type MiddlewareFunc

type MiddlewareFunc func(c *Context, next HandlerFunc)

MiddlewareFunc is an adapter to allow the use of ordinary functions as NapNap handlers.

func (MiddlewareFunc) Invoke

func (m MiddlewareFunc) Invoke(c *Context, next HandlerFunc)

Invoke function is a middleware entry

type MiddlewareHandler

type MiddlewareHandler interface {
	Invoke(c *Context, next HandlerFunc)
}

MiddlewareHandler is an interface that objects can implement to be registered to serve as middleware in the NapNap middleware stack.

type NapNap

type NapNap struct {
	MaxRequestBodySize int64
	ErrorHandler       ErrorHandler
	NotFoundHandler    HandlerFunc
	// contains filtered or unexported fields
}

NapNap is root level of framework instance

func New

func New(mHandlers ...MiddlewareHandler) *NapNap

New returns a new NapNap instance

func (*NapNap) All added in v1.1.0

func (nap *NapNap) All(path string, handler HandlerFunc)

All is a shortcut for adding all methods

func (*NapNap) Delete added in v1.1.0

func (nap *NapNap) Delete(path string, handler HandlerFunc)

Delete is a shortcut for router.Add("DELETE", path, handle)

func (*NapNap) Get added in v1.1.0

func (nap *NapNap) Get(path string, handler HandlerFunc)

Get is a shortcut for router.Add("GET", path, handle)

func (*NapNap) Head added in v1.1.0

func (nap *NapNap) Head(path string, handler HandlerFunc)

Head is a shortcut for router.Add("HEAD", path, handle)

func (*NapNap) Options added in v1.1.0

func (nap *NapNap) Options(path string, handler HandlerFunc)

Options is a shortcut for router.Add("OPTIONS", path, handle)

func (*NapNap) Patch added in v1.1.0

func (nap *NapNap) Patch(path string, handler HandlerFunc)

Patch is a shortcut for router.Add("PATCH", path, handle)

func (*NapNap) Post added in v1.1.0

func (nap *NapNap) Post(path string, handler HandlerFunc)

Post is a shortcut for router.Add("POST", path, handle)

func (*NapNap) Put added in v1.1.0

func (nap *NapNap) Put(path string, handler HandlerFunc)

Put is a shortcut for router.Add("PUT", path, handle)

func (*NapNap) Run

func (nap *NapNap) Run(engine *Server) error

Run will run http server

func (*NapNap) RunAll

func (nap *NapNap) RunAll(addrs []string) error

RunAll will listen on multiple port

func (*NapNap) RunAutoTLS

func (nap *NapNap) RunAutoTLS(engine *Server) error

RunAutoTLS will run http/2 server

func (*NapNap) RunTLS

func (nap *NapNap) RunTLS(engine *Server) error

RunTLS will run http/2 server

func (*NapNap) ServeHTTP

func (nap *NapNap) ServeHTTP(w http.ResponseWriter, req *http.Request)

Conforms to the http.Handler interface.

func (*NapNap) SetRender

func (nap *NapNap) SetRender(templateRootPath string)

SetRender function allows user to set template location.

func (*NapNap) SetTemplate

func (nap *NapNap) SetTemplate(t *template.Template)

SetTemplate function allows user to set their own template instance.

func (*NapNap) Use

func (nap *NapNap) Use(mHandler MiddlewareHandler)

Use adds a Handler onto the middleware stack. Handlers are invoked in the order they are added to a NapNap.

func (*NapNap) UseFunc

func (nap *NapNap) UseFunc(aFunc func(c *Context, next HandlerFunc))

UseFunc adds an anonymous function onto middleware stack.

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	ContentLength() int
	Status() int
	// contains filtered or unexported methods
}

ResponseWriter wraps the original http.ResponseWriter

func NewResponseWriter

func NewResponseWriter() ResponseWriter

NewResponseWriter returns a ResponseWriter which wraps the writer

type Server

type Server struct {
	*http.Server
	Config *Config
}

Server ...

func NewHTTPEngine added in v1.1.0

func NewHTTPEngine(addr string) *Server

NewHTTPEngine ...

func NewHTTPEngineWithConfig added in v1.1.0

func NewHTTPEngineWithConfig(c *Config) *Server

NewHTTPEngineWithConfig ...

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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