DEV Community

loading...

Build a Simple Web App using Go

heerthees profile image Heertheeswaran V ・Updated on ・2 min read

Hello everyone, Today I would like to discuss building a simple hello world web app with Golang. Go is already has a web server built-in. The "net/http" package from the standard library contains all the things we need to do with the HTTP protocol. In this example, we will see how easy it is to run a web server that we can see in our browser.

For creating a webserver in go, we need to understand two main functions.

Request Handler

As the name suggests, the Request Handler is the one which receives all the http connections from the browser. The syntax of the Request Handler function is

func (w http.ResponseWriter, r *http.Request)

The handler function receives two arguments:

  1. http.Request - contains all details about the HTTP request including things like the URL, header or body fields.

  2. http.ResponseWriter - where we write out a response to.

So first, we need to register a Handler function.

Request Listener

The Request Handler function can only receive the http connections. Along with that, we need a Request Listener which listens on a port and passes the connection to the Handler function.

The syntax of a listner function is

http.ListenAndServe(":3000", nil)

The listener function receives two arguments:

  1. port - The port to listen for the http connections.
  2. handler - the handler to send all the connection. Typically the handler is nil.

Hello World Web App

By understanding the above function, it is simple to create a web server. The code for a simple hello world web server looks like this

// main.go
package main

import (
    "fmt"
    "net/http"
)
func main() {
  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!") 
  })
  http.ListenAndServe(":3000", nil)
}

Run the main.go using the command

go run main.go

Alt Text

So, if we now go to the browser and open http://localhost:3000/ we can see the "Hello, World!" text which we are returning.

Alt Text

In this example, the handler function is mapper to the root path which is "/". Likewise, we can create multiple routes and register them to their corresponding handlers.

All done! πŸŽ‰

That’s it for now guys. Will meet you guys again with another interesting topic.

Discussion (0)

Forem Open with the Forem app