0
0
GoHow-ToBeginner · 3 min read

How to Create HTTP Server in Go: Simple Guide

To create an HTTP server in Go, use the net/http package and call http.ListenAndServe with an address and a handler. Define handler functions to respond to requests, then start the server to listen for incoming connections.
📐

Syntax

The basic syntax to create an HTTP server in Go involves importing the net/http package, defining handler functions, and starting the server with http.ListenAndServe.

  • http.HandleFunc(pattern, handler): Registers a handler function for a URL pattern.
  • http.ListenAndServe(address, handler): Starts the server on the given address (e.g., ":8080") and uses the handler to respond to requests.
go
http.HandleFunc("/", handlerFunction)
http.ListenAndServe(":8080", nil)
💻

Example

This example shows a simple HTTP server that listens on port 8080 and responds with "Hello, World!" to any request.

go
package main

import (
	"fmt"
	"net/http"
)

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

func main() {
	http.HandleFunc("/", helloHandler)
	fmt.Println("Starting server at :8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic(err)
	}
}
Output
Starting server at :8080
⚠️

Common Pitfalls

Common mistakes when creating an HTTP server in Go include:

  • Not handling errors returned by http.ListenAndServe, which can hide server startup problems.
  • Using nil as the handler but forgetting to register any handlers, causing 404 errors.
  • Not specifying the port correctly (e.g., missing the colon ":" before the port number).
go
package main

import (
	"fmt"
	"net/http"
)

// Wrong: No handler registered, server will return 404 for all requests
func main() {
	fmt.Println("Starting server at :8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic(err)
	}
}

// Right: Register a handler to respond to requests
func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello, fixed server!")
}

func mainFixed() {
	http.HandleFunc("/", helloHandler)
	fmt.Println("Starting server at :8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic(err)
	}
}
📊

Quick Reference

  • http.HandleFunc(pattern, handler): Register handler for URL pattern.
  • http.ListenAndServe(address, handler): Start server on address.
  • Handler function: func(w http.ResponseWriter, r *http.Request) to handle requests.
  • Address format: ":port" (e.g., ":8080") to listen on all interfaces.

Key Takeaways

Use net/http package and http.ListenAndServe to create an HTTP server in Go.
Register handler functions with http.HandleFunc to respond to requests.
Always check and handle errors from ListenAndServe to catch startup issues.
Specify the port with a colon prefix, like ":8080", to listen correctly.
Without registered handlers, the server returns 404 for all requests.