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 Go server starts with http.ListenAndServe(port, handler), where :
We use http.HandleFunc("/route", myFunction) to define routes.
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)
}
handler()that writes a response message.http.HandleFunc("/") .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)
}
http.HandleFunc("/")→ Main route (/).http.HandleFunc("/about")→ Route /about.Open "http://localhost:8080"
you should see :
Open "http://localhost:8080/about"
you should see :
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))
http.FileServer(http.Dir("./static")) → Tells Go that the files are inside the static/ folder.http.StripPrefix("/static/", fs) → Removes /static/ from the path to find files correctly.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)
}
Messageis a Go struct converted into JSON.w.Header().Set("Content-Type", "application/json") → Tells the client we're sending JSON.json.NewEncoder(w).Encode(message) → Encodes and sends the response.🚀 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! 🙌