Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Build a Simple Web Server with Golang?

  • Last Updated : 10 Oct, 2021

Golang is a procedural programming language ideal to build simple, reliable, and efficient software. 

Creating Web Servers Using Golang: 

Initialize a project

Create a project folder with a .go file inside eg. server.go.
 

Directory structure:

The server.go file:



Go




package main
 
import (
    "fmt"
    "log"
    "net/http"
)
 
func main() {
 
    // API routes
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello world from GfG")
    })
    http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hi")
    })
 
    port := ":5000"
    fmt.Println("Server is running on port" + port)
 
    // Start server on port specified above
    log.Fatal(http.ListenAndServe(port, nil))
}

Run the server using the following command (make sure you’re in the project directory):

go run server.go

Note:  You have to stop the server with Ctrl + C and restart via the same command whenever the server.go file is changed. 
 

Console:

Open the desired web browser and any of these URLs to verify if the server is running:

http://localhost:5000/ or http://localhost:5000/hi

Output:



Serving static files:

Create a static folder with all the static files.
Example directory structure:

Example static files:

HTML




<html>
  <head>
    <title>Home</title>
  </head>
  <body>
    <h2>Home page</h2>
  </body>
</html>

 
 

  • The about.html file

 

HTML




<html>
  <head>
    <title>About</title>
  </head>
  <body>
    <h2>about page!</h2>
  </body>
</html>

Now Edit the server.go file:

Go




package main
 
import (
    "fmt"
    "log"
    "net/http"
)
 
func main() {
 
    // API routes
 
    // Serve files from static folder
    http.Handle("/", http.FileServer(http.Dir("./static")))
 
    // Serve api /hi
    http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hi")
    })
 
    port := ":5000"
    fmt.Println("Server is running on port" + port)
 
    // Start server on port specified above
    log.Fatal(http.ListenAndServe(port, nil))
 
}

Verifying if static files are served:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!