web

package
v0.0.0-...-37e343e Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2023 License: Apache-2.0 Imports: 17 Imported by: 3

README

Web

Examples

hello world
package main

import (
	"github.com/nite-coder/blackbear/pkg/web"
)

func main() {
	s := web.NewServer()

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

	s.Run(":10080")
}
Using GET, POST, PUT, PATCH, DELETE and OPTIONS
package main

import (
	"github.com/nite-coder/blackbear/pkg/web"
)

func main() {
	s := web.NewServer()

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

    s.Run(":10080")
}
Parameters in path
package main

import (
	"github.com/nite-coder/blackbear/pkg/web"
)

func main() {
	s := web.NewServer()

	s.Get("/users/:name", func(c *web.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
	s.Get("/videos/*video_id", func(c *web.Context) error {
		id := c.Param("video_id")
		return c.String(200, "video id is, "+id)
	})

	s.Run(":10080")
}
Get querystring value
package main

import (
	"github.com/nite-coder/blackbear/pkg/web"
)

func main() {
	s := web.NewServer()

	// http://localhost:10080/test?page=3
	s.Get("/test", func(c *web.Context) error {
		page := c.Query("page") //get query string value
		return c.String(200, page)
	})

	err := s.Run(":10080")
	if err != nil {
		panic(err)
	}
}
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)
}

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 Context

type Context struct {
	WebServer *WebServer
	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 context.Context) (*Context, bool)

FromContext return a web context from the standard context

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) 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

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 `web.HandlerFunc`.

type MiddlewareFunc

type MiddlewareFunc func(c *Context, next HandlerFunc)

MiddlewareFunc is an adapter to allow the use of ordinary functions as WebServer 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 WebServer 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

type ServerOptions

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

type WebServer

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

WebServer is root level of framework instance

func NewServer

func NewServer(mHandlers ...MiddlewareHandler) *WebServer

NewServer returns a new WebServer instance

func (*WebServer) All

func (s *WebServer) All(path string, handler HandlerFunc)

All is a shortcut for adding all methods

func (*WebServer) Delete

func (s *WebServer) Delete(path string, handler HandlerFunc)

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

func (*WebServer) Get

func (s *WebServer) Get(path string, handler HandlerFunc)

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

func (*WebServer) Head

func (s *WebServer) Head(path string, handler HandlerFunc)

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

func (*WebServer) Options

func (s *WebServer) Options(path string, handler HandlerFunc)

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

func (*WebServer) Patch

func (s *WebServer) Patch(path string, handler HandlerFunc)

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

func (*WebServer) Post

func (s *WebServer) Post(path string, handler HandlerFunc)

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

func (*WebServer) Put

func (s *WebServer) Put(path string, handler HandlerFunc)

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

func (*WebServer) Run

func (s *WebServer) Run(addr string) error

Run will start to run a http server TODO: allow multiple ports and addrs

func (*WebServer) RunTLS

func (s *WebServer) RunTLS(addr, cert, key string) error

RunTLS will run http/2 server

func (*WebServer) ServeHTTP

func (s *WebServer) ServeHTTP(w http.ResponseWriter, req *http.Request)

Conforms to the http.Handler interface.

func (*WebServer) SetRender

func (s *WebServer) SetRender(templateRootPath string)

SetRender function allows user to set template location.

func (*WebServer) SetTemplate

func (s *WebServer) SetTemplate(t *template.Template)

SetTemplate function allows user to set their own template instance.

func (*WebServer) Shutdown

func (s *WebServer) Shutdown(ctx context.Context) error

func (*WebServer) Use

func (s *WebServer) Use(mHandler MiddlewareHandler)

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

func (*WebServer) UseFunc

func (s *WebServer) UseFunc(aFunc func(c *Context, next HandlerFunc))

UseFunc adds an anonymous function onto middleware stack.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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