Making a simple web server using Golang

By Shivam Chawla on May 02, 2017

Golang is a programming language built by google. It is becoming popular these days and is basically recognised for its speed. Golang comes with a inbuilt webserver. Assuming you have golang setup on your system, follow the steps below.

 

Steps to create a web server in golang

 

  1. Create a new directory in your $GOPATH/src folder with the name server.
  2. Create a new file server.go in the folder you just created.
  3. Open the file and write 


    package main
    import ( "net/http" )
    func main() {
      http.HandleFunc("/",func(w http.ResponseWriter,r *http.Request) {
        w.Write([]byte("Hello World"))
      })
      http.ListenAndServe(":8000", nil)
    }

  4. Run the server by typing this command in your terminal
    go run server.go
  5. Visit http://localhost:8000 in your browser to see Hello World.

 

Explanation for the steps above

Every program in golang starts with package name. The execution of the program starts with the execution of function main. We imported the package "net/http" to be able to use the inbuilt webserver that is provided with golang.

 

The function http.HandleFunc accepts two parameter. The first one is the address and the second one is a function that tells it what to do with the request. The function has two parameters itself. First one is the http.ResponseWriter that sends the response back to the browser and the second one is a pointer to http.Request which contains information like request headers, body etc.

 

We use the Write function to write the response to the browser. The Write function accepts byte array as its parameters that is why we had to convert our string to byte array.

{{comments_count}} Comments

{{ comment.name }}

{{comment.comment}}

{{ error }}