How to Run HTTP Server in Go

Published on January 24, 2020 55 sec read

Go has a built-in webserver. In this tutorial, I’m going to show how to run the HTTP server in Go.

Table of Contents

  1. Create Project & Import Packages
  2. Create Request Handler
  3. Listen HTTP Connections
  4. The Full Code

Step 1 : Create Project & Import Packages

At first, create a project and under the project create a file called http-server.go. We need to import fmt and net/http packages:

import (
    "fmt"
    "net/http"
)

Step 2 : Create Request Handler

After that, we need to create an HTTP request handler function. The syntax:

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

The http.ResponseWriter contains text/html & http.Request contains all HTTP requests such as headers/URL.

Let’s create a function called hello as an HTTP handler function:

func hello(w http.ResponseWriter, req *http.Request)  {
    fmt.Fprintf(w, "Hello world, Welcome to MyNotePaper!")
}

From the main() function we need to call this function like:

http.HandleFunc("/", hello)

Step 3 : Listen HTTP Connections

Using ListenAndServe() function, we’re able to open port to listen HTTP. We need to write this function in main() function. Let’s run this project on 80 port:

http.ListenAndServe(":80", nil)

Now run go run http-server.go command and go to the browser & visit http://localhost/ to see the contents.

Step 4 : The Full Code

The final code of this simple project:

http-server.go
package main

import (
    "fmt"
    "net/http"
)

func hello(w http.ResponseWriter, req *http.Request)  {
    fmt.Fprintf(w, "Hello world, Welcome to MyNotePaper!")
}

func main() {
    // route
    http.HandleFunc("/", hello)

    // listen port 80
    http.ListenAndServe(":80", nil)
}

We’re done. I hope this article will help you. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Buy me a coffeeBuy me a coffee Follow

Leave a Reply

Your email address will not be published. Required fields are marked *