Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Build a Go Web App

Sowju
March 07, 2018

Build a Go Web App

Talks about building a basic web app in Go using net/http and goes over some of the available Go frameworks for building web apps. Finally wraps up with the necessary steps needed to build and deploy a Go Web App on the Heroku Platform.

Sowju

March 07, 2018
Tweet

More Decks by Sowju

Other Decks in Programming

Transcript

  1. BUILD YOUR WEB APP IN GO & DEPLOY IT ON

    HEROKU Naga Sowjanya Mudunuri Senior Software Engineer @heroku @gritncompassion
  2. Acknowledgements ▪ Bryan Vanderhoof (@bjvhoof) ▪ Jacob Vorreuter (@jkvor) ▪

    Dane Harrigan (@daneharrigan) ▪ Bernerd Schaefer (@bjschaefer) ▪ Ed Muller (@freeformz) @gritncompassion
  3. Agenda ▪ Build a web app with net/http ▪ Available

    web frameworks for Go ▪ Deployments on Heroku @gritncompassion
  4. net/http package ▪ provides HTTP client and server implementations ▪

    HTTP Server – ListenAndServe starts an HTTP Server with a given address and handler – Handle – HandleFunc – ServeFile @gritncompassion
  5. http.ServeMux ▪ HTTP request multiplexer ▪ matches the URL of

    each incoming request against a list of registered patterns & calls the handler for the pattern – mux := http.NewServeMux() – mux.HandleFunc("/", homeHandler) @gritncompassion
  6. Response ▪ Write: – func (r *Response) Write(w io.Writer) error

    ▪ JSON: – json.Marshal from encoding/json – w.Header().Set(“Content-type”, “application/json”) – w.write(jsonData) ▪ Static Assets: – http.Fileserver @gritncompassion
  7. Demo of skeleton net/http web app @gritncompassion Example of a

    basic web app using net/http Ø https://github.com/sowjumn/web-net-http-go
  8. Gorilla ▪ https://github.com/gorilla ▪ Web toolkit in Go ▪ Requests

    can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers. ▪ URL hosts, paths and query values can have variables with an optional regular expression. @gritncompassion
  9. Gorilla/mux ▪ Routes can be used as subrouters: nested routes

    are only tested if the parent route matches. ▪ It implements the http.Handler interface so it is compatible with the standard http.ServeMux. @gritncompassion
  10. Gorilla ▪ Routes can also be restricted to a domain

    or subdomain. – r := mux.NewRouter() – r.Host("www.foobar.com") // Only matches if domain is www.foobar.com – r.Host("{subdomain:[a-z]+}.domain.com") // Matches a dynamic subdomain @gritncompassion
  11. Upgrade to Gorilla ▪ http://www.gorillatoolkit.org/pkg/mux ▪ go get github.com/gorilla/mux –

    `r := mux.NewRouter()` – r.HandleFunc("/products/{key}", ProductHandler) @gritncompassion
  12. Routing with GIN ▪ router := gin.Default() – router.GET("/someGet", getHandler)

    – router.POST("/somePost", postHandler) – router.PUT("/somePut", putHandler) – router.DELETE("/someDelete", deleteHandler) – router.PATCH("/somePatch", patchHandler) – router.HEAD("/someHead", headHandler) @gritncompassion
  13. Params in URL using GIN Parameters in path: router.GET("/user/:name", func(c

    *gin.Context) { name := c.Param("name") c.String(http.StatusOK, "Hello %s", name) }) @gritncompassion
  14. Query Params ▪ router.GET("/welcome", func(c *gin.Context) { firstname := c.DefaultQuery("firstname",

    "Guest") lastname := c.Query("lastname") c.String(http.StatusOK, "Hello %s %s", firstname, lastname) }) ▪ router.Run(":8080") @gritncompassion
  15. Grouping Routes ▪ v1 := router.Group("/v1") – v1.POST("/login", loginEndpoint) –

    v1.POST("/submit", submitEndpoint) – v1.POST("/read", readEndpoint) @gritncompassion
  16. Sending JSON back in GIN ▪ router.POST("/form_post", func(c *gin.Context) {

    message := c.PostForm("message") nick := c.DefaultPostForm(”sowju", "anonymous") c.JSON(200, gin.H{ ”foo": ”bar", "message": “created”, }) }) @gritncompassion
  17. Serving Static Assets in GIN ▪ router.Static("/assets", "./assets") ▪ router.StaticFS("/more_static",

    http.Dir("my_file_system")) ▪ router.StaticFile("/favicon.ico", "./resources/favicon.ico") @gritncompassion
  18. Getting Started with Revel ▪ Get the executable `go get

    -u github.com/revel/cmd/revel` ▪ Create an app with Revel `revel new <app_name>` ▪ Spin up the Server `revel run <app_name>` ▪ References: – https://github.com/revel/revel – https://revel.github.io/tutorial/requestflow.html @gritncompassion
  19. Rendering Views in Revel ▪ Templating: html/template package ▪ Which

    view does revel render? – The application app/views/ directory and subdirectories. – revel core templates/ directory. – Otherwise a 500 error as template not found References: ▪ https://revel.github.io/manual/templates.html @gritncompassion
  20. Responses in Revel ▪ Actions must return a revel.Result –

    Render() – RenderJSON() – Redirect() – RenderError() @gritncompassion
  21. Validating your Model using Revel ▪ Revel has validations in

    the Model. Similar to Active Record Validations. ▪ revel.Validation has a couple of methods that could be useful to you – required – Max – Min – Range – MinSize – MaxSize – Length @gritncompassion
  22. ▪ Uses BootStrap by default ▪ i18n ▪ Supports Websockets

    ▪ Standard way to send JSON back Revel @gritncompassion
  23. Beego ▪ RESTful HTTP framework ▪ go get github.com/astaxie/beego ▪

    go get github.com/beego/bee ▪ cd $GOPATH/src/github.com/<github_username>/ ▪ bee new <project_name> ▪ cd <project_name> @gritncompassion
  24. Beego Controllers ▪ Restful Routing ▪ XSRF Filtering ▪ Easier

    parsing ▪ Form Validation @gritncompassion
  25. Beego Models ▪ Custom ORM ▪ Supports MySQL, PostgreSQL, Sqlite

    ▪ Supports RawSQL query mapping ▪ Supports transactions @gritncompassion
  26. Beego Views ▪ Uses html/template ▪ Supports Pagination ▪ Static

    Assets: Wrapper around http.ServeFile @gritncompassion
  27. More of Beego ▪ Supports Sessions ▪ Supports Memcache and

    Redis caching ▪ Logging ▪ i18n @gritncompassion
  28. Deploying on Heroku ▪ Procfile ▪ Dependency management file –

    govendor – Also supported: godep, glide, gb – dep(community supported) – https://devcenter.heroku.com/categories/managing-go-dependencies ▪ The main file shouldnot set the port . It should only set the port for local deployments @gritncompassion
  29. Deploying on Heroku: vendor.json ▪ Specify your Go version if

    you want a particular go version ▪ Install all packages ▪ The supported go versions are – https://devcenter.heroku.com/articles/go-support#go-versions ▪ References: – https://devcenter.heroku.com/articles/getting-started-with-go @gritncompassion