Serving Our First Go Application

05th Mar 2024

2 mins read

 

You're wondering, we've written our first go program, but how can we see the outcome beyond the terminal or command line. I got you.

In our project file, let's add a html file and call it home.html which contains simple contents such as the title and paragraph in which we intend to serve.

Then in our main.go file

Comment out the line in which we printed Hello World.

We are going to add a function that's going to be called everytime a request is made to a certain url using the http package.The function called Handle Func which accepts two parameters, the first parameter is the url path, and the second is the function that is going to be invoked everytime a function comes in that matches the path func(w http.ResponseWriter, r *http.Request).

 
Inside HandleFunc Function, let's have another function that shows which file we are to serve. We'll have http.ServeFile(w, r, "./home.html")

Next, we have to listen in order to serve our program to a particular port. This we do inside the ListenAnd Serve Function. Here, I ve specified port 3000 and nil, being an equivalent of null in other programming language tells go to provide a default handler for our request.
http.ListenAndServe(":3000", nil)

package main

import (
  "net/http"
)

func main() {

  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./home.html")
  })

  http.ListenAndServe(":3000", nil)

}

run : go run .
Open your browser and go to http://localhost:3000/ to see your app