Post

Building a Simple Web Server Using Golang

Building a Simple Web Server Using Golang

In this post, I will guide you through the process of building a simple web server using Go. Go, also known as Golang, is a statically typed, compiled programming language designed for simplicity and efficiency. It is widely used for building web servers, networking tools, and cloud-based applications.

Prerequisites

Before we start, make sure you have the following installed on your machine:

  • Go (version 1.15 or later)
  • A code editor (e.g., Visual Studio Code, GoLand, or any text editor of your choice)
  • Basic knowledge of Go programming language
  • Familiarity with HTTP and web servers

Step 1: Create a New Go Project

Create a new directory for your Go project and navigate to it in your terminal:

1
2
mkdir simple-web-server
cd simple-web-server

Step 2: Initialize a Go Module

Initialize a new Go module by running the following command:

1
go mod init simple-web-server

This command creates a go.mod file that will manage your project’s dependencies.

Step 3: Create the Main Go File

Create a new file named main.go in your project directory:

1
touch main.go

Open main.go in your code editor and add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main
import (
  "fmt"
  "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Hello, World!")
}

func main() {
  http.HandleFunc("/", helloHandler)
  fmt.Println("Starting server on :8080...")
  if err := http.ListenAndServe(":8080", nil); err != nil {
    fmt.Println("Error starting server:", err)
  }
}

Step 4: Run the Web Server

To run the web server, execute the following command in your terminal:

1
go run main.go

You should see the message “Starting server on :8080…” in your terminal.

Step 5: Test the Web Server

Open your web browser and navigate to http://localhost:8080. You should see the message “Hello, World!” displayed in your browser.

Step 6: Customize the Web Server

You can customize the web server by adding more routes and handlers. For example, you can create a new handler for a different route:

1
2
3
4
func goodbyeHandler(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Goodbye, World!")
}

Then, register the new handler in the main function:

1
http.HandleFunc("/goodbye", goodbyeHandler)

Restart the server by running go run main.go again. Now, if you navigate to http://localhost:8080/goodbye, you should see the message “Goodbye, World!” displayed in your browser.

Conclusion

Congratulations! You have successfully built a simple web server using Go. This is just the beginning, and you can explore more advanced features such as routing, middleware, and database integration to enhance your web server.

This post is licensed under CC BY 4.0 by the author.