Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Creating HTTP Servers

24. Creating HTTP Servers

Creating HTTP servers is a fundamental aspect of web development. In Go, you can easily create HTTP servers using the built-in 'net/http' package. Let's explore how to create HTTP servers in Go, handle routes, and serve static files.

Creating an HTTP Server:

To create an HTTP server in Go, you need to import the 'net/http' package. Here's a basic example:

package main

import (
"fmt"
"net/http"
)

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

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

 

In this example, when you run the program and visit 'http://localhost:8080/' in your web browser, you'll see "Hello, Go Server!" displayed.

Handling Different Routes:

You can create route handlers to handle different URLs.

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

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

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

 

Visiting 'http://localhost:8080/' displays "Welcome to the Home Page!", and visiting 'http://localhost:8080/about' displays "This is the About Page."

Serving Static Files:

You can serve static files like HTML, CSS, and JavaScript by using the 'http:FileServer'function.

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

 

In this case, create a directory named "static" in the same location as your Go code. Place your static files there, such as 'static/index.html', 'static/style.css', etc. When you visit  'http://localhost:8080/static/index.html', the contents of 'index.html' will be served.

Summary:

  • Creating an HTTP server in Go involves using the 'net/http'package.
  • Use 'http.HandleFunc' to define route handlers.
  • You can serve static files using 'http.FileServer'.
  • Go's built-in HTTP server capabilities allow you to easily create and handle web servers.

As you advance in web development, you can integrate more complex features such as handling form submissions, processing data, working with databases, and creating RESTful APIs.