All Projects → DronRathore → goexpress

DronRathore / goexpress

Licence: MIT license
An Express JS Style HTTP server implementation in Golang

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to goexpress

serverless-rest-api
Building RESTful Web APIs with Firebase Cloud Function, Firestore, Express and TypeScript
Stars: ✭ 103 (+18.39%)
Mutual labels:  restful-api
software-systems-architecture
A collection of descriptions of the architecture that various systems use.
Stars: ✭ 24 (-72.41%)
Mutual labels:  restful-api
node-server-template
This is Node.js server tidy template / boilerplate with Express (with asyncified handlers, custom error handler) framework and MongoDb. The server use ES6 and above. On different branches you can see different techniques' and technologies' usage, such as Kafka, nodemailer, file download... You also can find postman collections.
Stars: ✭ 116 (+33.33%)
Mutual labels:  restful-api
vbo365-rest
Unofficial Self-Service Web Portal for Veeam Backup for Microsoft Office 365
Stars: ✭ 44 (-49.43%)
Mutual labels:  restful-api
apex-rest-route
A simple framework for building Restful API on Salesforce
Stars: ✭ 75 (-13.79%)
Mutual labels:  restful-api
SpringsScala
Sample Projects for Creating Springs Web services in Scala
Stars: ✭ 16 (-81.61%)
Mutual labels:  restful-api
wine
A lightweight and flexible framework to help build elegant web API
Stars: ✭ 39 (-55.17%)
Mutual labels:  restful-api
travels-api
API for Travels Management - UFLA Comp Jr/20 anniversary event
Stars: ✭ 22 (-74.71%)
Mutual labels:  restful-api
symfony-todo-backend
This is the result of all the videos that were created in the series that i published on the playlist. LINK BELOW
Stars: ✭ 172 (+97.7%)
Mutual labels:  restful-api
cubic
📦 Easy to scale, zero-config, real-time focused app platform for node.js
Stars: ✭ 16 (-81.61%)
Mutual labels:  restful-api
gorest
Go RESTful API starter kit with Gin, JWT, GORM (MySQL, PostgreSQL, SQLite), Redis, Mongo, 2FA, email verification, password recovery
Stars: ✭ 135 (+55.17%)
Mutual labels:  restful-api
papermerge-core
Papermerge RESTful backend structured as reusable Django app
Stars: ✭ 103 (+18.39%)
Mutual labels:  restful-api
ecommerce api
E-commerce by Django Rest Framework
Stars: ✭ 156 (+79.31%)
Mutual labels:  restful-api
swagger-brake
Swagger contract checker for breaking API changes
Stars: ✭ 49 (-43.68%)
Mutual labels:  restful-api
project-3-crm
⭐crm 客户关系管理系统模板⭐一个不错的后台管理种子项目,拥有自由设置角色自由分配权限🔑的权限管理功能,三员管理多员管理均可,前端antd vue admin后端spring-boot-api-seedling 拥有完善的功能。文档包含需求文档,设计文档和测试文档等。同时配置了travis,拥有集成测试和自动构建的功能。
Stars: ✭ 128 (+47.13%)
Mutual labels:  restful-api
HttpServerLite
TCP-based simple HTTP and HTTPS server, written in C#.
Stars: ✭ 44 (-49.43%)
Mutual labels:  restful-api
sanic-currency-exchange-rates-api
This is a self hosted, free, open source Python Currency Exchange Rate API fork.
Stars: ✭ 20 (-77.01%)
Mutual labels:  restful-api
dawn-api
A RESTful API package
Stars: ✭ 25 (-71.26%)
Mutual labels:  restful-api
grapevine
Fast, unopinionated, embeddable, minimalist web framework for .NET
Stars: ✭ 72 (-17.24%)
Mutual labels:  restful-api
mrapi
A framework for rapid development of API or DAL applications.
Stars: ✭ 20 (-77.01%)
Mutual labels:  restful-api

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. :)
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].