Understanding the Basics of a Go HTTP Server (Quick introduction)

Before coding, let's go over some key concepts :

An HTTP server is a program that :

👉 Real-world example : When you visit http://example.com, your browser sends a request to the server, which responds with the webpage.

In Go, we use thenet/httppackage to create a server. Here are the basic components :

a- Starting a server :

A Go server starts with http.ListenAndServe(port, handler), where :

b- Creating a route :

We use http.HandleFunc("/route", myFunction) to define routes.

👉 Minimal example :


                    package main

                    import (
                        "fmt"
                        "net/http"
                    )
                    
                    func handler(w http.ResponseWriter, r *http.Request) {
                        fmt.Fprintf(w, "Welcome to my Go server!")
                    }
                    
                    func main() {
                        http.HandleFunc("/", handler)
                        http.ListenAndServe(":8080", nil)
                    }
                    

            

📌 Explanation :

We can add multiple routes like this :


package main

import (
	"fmt"
	"net/http"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcome to the homepage!")
}

func aboutHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "About this server.")
}

func main() {
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/about", aboutHandler)
	http.ListenAndServe(":8080", nil)
}

            

📌 Explanation :

Run the Go Server and Test the Endpoints

Homepage

Open "http://localhost:8080"

you should see :

Welcome to the homepage!

About Page

Open "http://localhost:8080/about"

you should see :

About this server.

f you want to serve files like index.html, style.css, etc., you can use :


fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

            

📌 Explanation :

If you want to send JSON data (used in APIs), here's how :


package main

import (
	"encoding/json"
	"net/http"
)

type Message struct {
	Text string `json:"text"`
}

func jsonHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json") // Set response type to JSON
	message := Message{Text: "Hello, JSON!"}
	json.NewEncoder(w).Encode(message)
}

func main() {
	http.HandleFunc("/api", jsonHandler)
	http.ListenAndServe(":8080", nil)
}

            

📌 Explanation :

🚀 Thank you for reading this tutorial! If you find this content valuable and want to support my work, a coffee would be greatly appreciated! ☕😊

💻 I am a freelance web developer, and I personally create and maintain this website. Any support would help me improve and expand it further! 🙌


☕ Buy me a coffee