goexpress

package module
v2.0.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2019 License: MIT Imports: 23 Imported by: 0

README

goexpress

GoDoc An Express JS Style HTTP server implementation in Golang with safe cleanup exit. The package make use of similar framework convention as there are in express-js. People switching from NodeJS to Golang often end up in a bad learning curve to start building their webapps, this project is meant to ease things up, its a light weight framework which can be extended to do any number of functionality.

Hello World

package main
import (
  express "github.com/DronRathore/goexpress"
)

func main (){
  var app = express.Express()
  app.Get("/", func(req express.Request, res express.Response){
    res.Write("Hello World")
    // you can skip closing connection
  })
  app.Start("8080")
}

Router

The router works in the similar way as it does in the express-js. You can have named parameters in the URL or named + regex combo.

func main (){
  var app = express.Express()
  app.Get("/:service/:object([0-9]+)", func(req express.Request, res express.Response){
    res.JSON(req.Params().Get("service"))
  })
  app.Start("8080")
}

Note: You can also adhoc an express.Router() instance too much like it is done in expressjs

package main
import (
  express "github.com/DronRathore/goexpress"
)
var LibRoutes = func (){
  // create a new Router instance which works in similar way as app.Get/Post etc
  var LibRouter = express.NewRouter()
  LibRouter.Get("/lib/:api_version", func(req express.Request, res express.Response){
    res.Json(req.Params.Get("api_version"))
  })
  return *LibRoutes
}() // immediate invocation
func main(){
  var app = express.Express()
  app.Use(LibRoutes) // attaches the Library Routes
  app.Start("8080")
}

Middleware

You can write custom middlewares, wrappers in the similar fashion. Middlewares can be used to add websocket upgradation lib, session handling lib, static assets server handler

func main (){
  var app = express.Express()
  app.Use(func(req *express.Request, res *express.Response){
    req.Params.Set("I-Am-Adding-Something", "something")
  })
  app.Get("/:service/:object([0-9]+)", func(req express.Request, res express.Response){
    // json will have the key added
    res.JSON(req.Params.Get("service"))
  })
  app.Start("8080")
}

ExpressInterface

You can pass around the instance of express struct across packages using this interface.

func main(){
  var app = express.Express()
  attachHandlers(app)
}
func attachHandlers(instance express.ExpressInterface){
  instance.Use(someMiddleware)
  instance.Set("logging", true)
}

Cookies

import (
  express "github.com/DronRathore/goexpress"
  http "net/http"
  Time "time"
)
func main (){
  var app = express.Express()
  app.Use(func(req express.Request, res express.Response){
    var cookie = &http.Cookie{
      Name: "name",
      Value: "value",
      Expires: Time.Unix(0, 0)
    }
    res.Cookie.Add(cookie)
    req.Params.Set("session_id", req.Cookies.Get("session_id"))
  })
  app.Get("/", func(req express.Request, res express.Response){
    res.Write("Hello World")
  })
  app.Start("8080")
}

Sending File

You can send a file by using the helper res.SendFile(url string, doNotSendCachedData bool)

func main (){
  var app = express.Express()

  app.Get("/public/:filename", func(req express.Request, res express.Response){
  res.SendFile(filename, false)
  })
  app.Start("8080")
}

Note: You can now also send an auto downloadable file too using res.Download api

/*
  @params:
    path: Full path to the file in local machine
    filename: The name to be sent to the client
*/
res.Download(path string, filename string)

Post Body

func main (){
  var app = express.Express()
  app.Use(func(req *express.Request, res *express.Response){
    res.Params.Set("I-Am-Adding-Something", "something")
  })
  app.Post("/user/new", func(req express.Request, res express.Response){
    type User struct {
      Name string `json:"name"`
      Email string `json:"email"`
    }
    var list = &User{Name: req.Body("name")[0], Email: req.Body("email")[0]}
    res.JSON(list)
  })
  app.Start("8080")
}

JSON Post

JSON Post data manipulation in golang is slightly different from JS. You have to pass a filler to the decoder, the decoder assumes the data to be in the same format as the filler, if it is not, it throws an error.

func main (){
  var app = express.Express()
  app.Use(func(req express.Request, res express.Response){
    res.Params["I-Am-Adding-Something"] = "something"
  })
  app.Post("/user/new", func(req express.Request, res express.Response){
    type User struct {
      Name string `json:"name"`
      Email string `json:"email"`
    }
    var list User
    err := req.JSON().Decode(&list)
    if err != nil {
      res.Error(400, "Invalid JSON")
    } else {
      res.JSON(list)
    }
  })
  app.Start("8080")
}

File Uploading

Form Data Post

If a request has content-type form-data with a valid bounday param than goexpress will automatically parse and load all the files in express.Files() array. It will also populate req.Body() if the post/put request contains any text key values.

func(req *express.Request, res *express.Response){
  if len(req.Files) > 0 {
    // do something
    for _, file := range req.Files() {
      name := file.FormName
      type := file.Mime["Content-Type"]
      res.Header().Set("Content-Type", type)
      content, err := ioutil.ReadAll(file.File)
      // save content or throw error
    }
  }
}

HTML Template

Use standard Golang http templates to render response page.

For example, you have a template file index.html in templates directory:

<h1>{{.Name}}</h1>

Fill the context and provide a path to the template file:

func(req *express.Request, res *express.Response){
  type TmplContext struct{
    Name string
  }
  data := TmplContext{"Rob"}
  res.Render("template.html", &data)
}

Safe Cleanup on exit

Newer version of goexpress provides three new methods namely express.ShutdownTimeout, express.BeforeShutdown and express.Shutdown, these methods can be utilised to do cleanup before the server shuts down.

  • BeforeShutdown: This method takes a function as input which will be triggered before shutdown of the server is called
  • ShutdownTimeout: This defines the time.Duration to spend while shutting down the server
  • Shutdown: An explicit immediate shutdown call that can be made, this will not trigger shutdown hook at all

Testing

There are no testing added to this package yet, I am hoping to get my hands dirty in testing, if anyone can help me out with this, feel free to open a PR.

Contribution

  • If you want some common must have middlewares support, please open an issue, will add them.
  • Feel free to contribute. :)

Documentation

Overview

Package goexpress helps reading and setting the cookie The cookie struct's instance is availaible to both goexpress.Request and goexpress.Response

Package goexpress provides the actual hook that enables you to start building your application.

The basic Express() functions returns an instance for the express which can be further be used as an express hook.

app.Use(), app.Get(), app.Post(), app.Delete(), app.Push() app.Put() are the top level functions that can be used in the same fashion as the express-js ones are.

Package goexpress header handles the Response & Request Header The package is responsible for setting Response headers and pushing the same on the transport buffer

Package goexpress provides the request structure The package provides access to Headers, Cookies Query Params, Post Body and Upload Files

Package goexpress package provides the core functionality of handling the client connection, chunked response and other features

Package goexpress /router returns instance for express Router Functions defined here are extended by express.go itself

Express Router takes the url regex as similar to the js one Router.Get("/:param") will return the param in Response.Params["param"]

Index

Constants

View Source
const MaxBufferSize int64 = 1024 * 1024

MaxBufferSize is a const type

Variables

This section is empty.

Functions

func CompileRegex

func CompileRegex(url string) *regexp.Regexp

CompileRegex is a Helper which returns a golang RegExp for a given express route string

Types

type Cookie interface {
	Add(cookie *http.Cookie) Cookie
	Del(name string) Cookie
	Get(name string) string
	GetAll() map[string]*http.Cookie
}

Cookie defines HTTP Cookie interface

type EntrySet

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

EntrySet defines a map entry set

func (*EntrySet) Get

func (e *EntrySet) Get(key string) string

Get returns a value from the entry set

func (*EntrySet) Set

func (e *EntrySet) Set(key string, v string)

Set a value to the entry set

type ExpressInterface added in v1.0.2

type ExpressInterface interface {
	Use(interface{}) ExpressInterface
	Get(string, Middleware) ExpressInterface
	Post(string, Middleware) ExpressInterface
	Put(string, Middleware) ExpressInterface
	Patch(string, Middleware) ExpressInterface
	Delete(string, Middleware) ExpressInterface
	SetProp(string, interface{}) ExpressInterface
	GetProp(string, interface{}) interface{}
	Start(string) ExpressInterface
	ShutdownTimeout(t time.Duration) ExpressInterface
	BeforeShutdown(func(e ExpressInterface)) ExpressInterface
	Shutdown(ctx context.Context) error
}

ExpressInterface is the Public Interface to allow access to express struct's member functions

func Express

func Express() ExpressInterface

Express returns a new instance of express

type File

type File struct {
	Name     string
	FormName string
	Mime     textproto.MIMEHeader
	File     multipart.File
	Reader   *multipart.Part
}

File contains the reader to read the buffer content of uploading file

type Header interface {
	Set(key string, value string) Header
	Get(key string) string
	Del(key string) Header
	SetStatus(code int)
	BasicSent() bool
	CanSendHeader() bool
	FlushHeaders() bool
}

Header defines HTTP header interface

type Middleware

type Middleware func(request Request, response Response)

Middleware function singature type

type NextFunc

type NextFunc func(NextFunc)

NextFunc is an extension type to help loop of lookup in express.go

type Request

type Request interface {
	// IsMultipart takes header value and boundary string and returns true if its a multipart
	IsMultipart(header string, boundary *string) bool
	// GetRaw returns the raw http Request
	GetRaw() *http.Request
	// URL returns the http URL
	URL() *url.URL
	// Cookie returns a cookie object to read from
	Cookie() Cookie
	// Header returns header set to read from
	Header() *EntrySet
	// Params returns a params set
	Params() *EntrySet
	// Method defines the HTTP request method
	Method() string
	// Body returns form key value list
	Body(key string) []string
	// Query returns query key value list
	Query(key string) []string
	// JSON returns json decoder for a json input body
	JSON() *json.Decoder
	// IsJSON tells if a request has json body
	IsJSON() bool
	// Files returns all the files attached with the request
	Files() []*File
}

Request defines the HTTP request interface

type Response

type Response interface {
	Cookie() Cookie
	Header() Header
	JSON(content interface{})
	Error(status int, str string)
	GetBuffer() *bufio.ReadWriter
	GetConnection() net.Conn
	GetRaw() http.ResponseWriter
	Redirect(url string) Response
	End()
	Download(path string, fileName string) bool
	SendFile(url string, noCache bool) bool
	WriteBytes(bytes []byte) error
	Write(content string) Response
	Render(path string, data interface{})
}

Response defines HTTP response wrapper interface

type Route

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

A Route contains a regexp and a Router.Middleware type handler

type Router

type Router interface {
	Get(url string, middleware Middleware) Router
	Post(url string, middleware Middleware) Router
	Put(url string, middleware Middleware) Router
	Patch(url string, middleware Middleware) Router
	Delete(url string, middleware Middleware) Router
	Use(middleware interface{}) Router
	GetRoutes() map[string][]*Route
}

Router is an interface wrapper

func NewRouter

func NewRouter() Router

NewRouter returns a new instance of express Router

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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