Simple HTTP Server Examples in Go

Explore practical examples of creating a simple HTTP server in Go, perfect for beginners and enthusiasts.
By Taylor

Introduction

Creating a simple HTTP server in Go is an excellent way to grasp the basics of web development with this powerful language. In this article, we will go through three diverse examples that illustrate the process of setting up a simple HTTP server. Each example will showcase different functionalities, helping you understand how to build and customize your server for various use cases.

Example 1: Basic HTTP Server

Context

This example demonstrates how to set up a basic HTTP server that responds with a simple message. It’s perfect for beginners looking to understand the fundamentals of HTTP handling in Go.

package main

import (
    "fmt"
    "net/http"
)

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

func main() {
    http.HandleFunc("/", handler)
    fmt.Println("Starting server at :8080")
    http.ListenAndServe(":8080", nil)
}

Notes

  • In this example, we define a function handler that writes “Hello, World!” to the response writer. The http.HandleFunc function maps the root URL (/) to this handler.
  • You can run this server by executing the code and then visiting http://localhost:8080 in your web browser.

Example 2: JSON Response Server

Context

In this example, we will create an HTTP server that responds with a JSON object. This is useful when building APIs or services that need to send structured data.

package main

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

type Message struct {
    Status  string `json:"status"`
    Message string `json:"message"`
}

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

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

Notes

  • Here, we define a Message struct to represent the JSON response. The jsonHandler function sets the Content-Type header to application/json and encodes the Message struct into JSON format.
  • You can test this by navigating to http://localhost:8080/json in your web browser, which should display the JSON response.

Example 3: Serving Static Files

Context

This example shows how to create an HTTP server that serves static files from a directory. This is commonly used for web projects that include HTML, CSS, and JavaScript files.

package main

import (
    "net/http"
)

func main() {
    fs := http.FileServer(http.Dir("./static"))
    http.Handle("/static/", http.StripPrefix("/static/", fs))
    http.ListenAndServe(":8080", nil)
}

Notes

  • In this example, we use http.FileServer to serve files from the ./static directory. The http.StripPrefix function ensures that the URL path does not include the /static/ prefix when accessing files.
  • To test this, create a static folder in the same directory as your Go file and add some files (like HTML or images). You can access them via http://localhost:8080/static/yourfile.html.

Conclusion

These examples of creating a simple HTTP server in Go provide a solid foundation for building web applications and services. Whether you are responding with plain text, JSON, or serving static files, Go makes it straightforward to set up a functional server. Happy coding!