How to Build a Simple Web Server with Golang?
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() {
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)
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 >
|
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() {
http.Handle( "/" , http.FileServer(http.Dir( "./static" )))
http.HandleFunc( "/hi" , func (w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi" )
})
port := ":5000"
fmt.Println( "Server is running on port" + port)
log.Fatal(http.ListenAndServe(port, nil))
}
|
Verifying if static files are served:
Last Updated :
10 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...