Go HTTP Server

Introduction

Go provides a built-in net/http package that makes it easy to build web servers. A web server is a program that listens for requests from a browser and returns a response, such as a webpage or JSON data.

1. Creating a Basic HTTP Server

The simplest way to create a web server in Go is by using http.ListenAndServe(). Below is an example of a basic Go web server that listens on port 8080 and responds with "Hello, Welcome to my Go server!".

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, Welcome to my Go server!")
}

func main() {
    http.HandleFunc("/", handler)
    fmt.Println("Server is running on http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

Explanation:

  • The handler function handles incoming HTTP requests.
  • http.HandleFunc("/", handler) registers this function for the root URL (/).
  • http.ListenAndServe(":8080", nil) starts the server on port 8080.

Test it: Run this program and visit http://localhost:8080 in your browser.

2. Handling Multiple Routes

Web servers often have multiple pages, each with different content. We can define multiple routes like / (Home Page) and /about (About Page).

package main

import (
    "fmt"
    "net/http"
)

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

func aboutHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "This is the About Page.")
}

func main() {
    http.HandleFunc("/", homeHandler)
    http.HandleFunc("/about", aboutHandler)
    
    fmt.Println("Server is running on http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

Now, visiting http://localhost:8080/about will display the About Page.

3. Serving Static Files (HTML, CSS, Images)

Sometimes, you need to serve static files like images, stylesheets, or JavaScript files. You can do this using http.FileServer().

package main

import (
    "net/http"
)

func main() {
    fs := http.FileServer(http.Dir("./static"))
    http.Handle("/", fs)

    http.ListenAndServe(":8080", nil)
}

Place your HTML, CSS, and image files inside a folder named static, and the server will serve them.

4. Using Query Parameters

Query parameters allow users to pass data through the URL. Below is an example where the server greets the user based on the provided name.

package main

import (
    "fmt"
    "net/http"
)

func greetHandler(w http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("name")
    if name == "" {
        name = "Guest"
    }
    fmt.Fprintf(w, "Hello, %s!", name)
}

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

Test it: Open http://localhost:8080/greet?name=Mahendra in your browser.

5. Handling Form Submissions (POST Requests)

To handle user input from forms, we use the r.ParseForm() method. Here’s an example:

package main

import (
    "fmt"
    "net/http"
)

func formHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        r.ParseForm()
        name := r.FormValue("name")
        fmt.Fprintf(w, "Form submitted! Name: %s", name)
    }
}

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

To test, create an HTML form that submits data to /submit.

Conclusion

In this tutorial, we covered:

  • How to create a basic HTTP server in Go
  • Handling multiple routes
  • Serving static files
  • Using query parameters
  • Handling form submissions (POST requests)