Building Web Server with GO

WebServer

A web server comprises both software and hardware components, utilizing protocols such as HTTP (Hypertext Transfer Protocol) to address client requests on the World Wide Web. Its primary function involves presenting website content by storing, processing and delivering webpages to users.

So lets get started!!

Step 1: We will be creating a directory of the project. We have named the directory as go-serverweb.

Step 2: In the VS-CODE:

  1. Create a static folder and in the static folder create two files index.html and form.html.

  2. Create a go file as main.go outside static folder.

Step 3: Writing the Code in the files.

  • Write the following code for index.html

  • Write the following code for form.html

  • In the main.go write the following code
package main
import (
    "fmt"
    "log"    
    "net/http"
)
func formHandler(w http.ResponseWriter,r *http.Request){
    if err:=r.ParseForm(); err!=nil{
        fmt.Fprintf(w,"Parseform() err: %v",err)
        return
    }
    fmt.Fprintf(w,"POST request succesful")
    name:=r.FormValue("name")
    address:=r.FormValue("address")
    fmt.Fprintf(w,"Name=%s \n",name)
    fmt.Fprintf(w,"Address=%s \n",address)

}
func helloHandler(w http.ResponseWriter,r *http.Request){
    if r.URL.Path!="/hello"{
        http.Error(w,"404 not found",http.StatusNotFound)
        return
    }
    if r.Method!="GET"{
        http.Error(w,"method is not supported",http.StatusNotFound)
        return
    }
    fmt.Fprintf(w,"hello")
}
func main(){
    fileServer:=http.FileServer(http.Dir("./static"))
    http.Handle("/",fileServer)
    http.HandleFunc("/form",formHandler)
    http.HandleFunc("/hello",helloHandler)
    fmt.Printf("Starting port at 8080\n")
    if err:=http.ListenAndServe(":8080",nil); err!=nil{
        log.Fatal(err)
    }
}

Step 4:
In the terminal window write the following commands to run the web server.

Open the webbrowser and visit localhost:8080

The output is as follows:

  • "/hello" route responds with a simple "hello" message.

  • When navigating to the "/form" route, a basic HTML form will be presented.

Code:

This code defines three main components:

  • formHandler Function:

    • formHandler is an HTTP handler function that processes requests to the "/form" route.

    • r.ParseForm() is used to parse form data from the request.

    • If there is an error during parsing, an error message is written to the response.

    • The function then prints a success message for a POST request and extracts and prints the values of "name" and "address" form fields.

  • helloHandler Function:

    • Responds to GET requests at the "/hello" route.

    • Displays a "hello" message if the path and method conditions are met; otherwise, returns a 404 not found error.

  • Main Function:

    • Creates a file server to serve static files from the "./static" directory.

    • Registers the file server for the root ("/") path.

    • Registers formHandler for the "/form" route and helloHandler for the "/hello" route.

    • Starts the server on port 8080 and logs any errors if the server fails to start.

Conclusion:

If you want to check out the github repository,
here's the link: https://github.com/Eshaabhasin/Web-Server-GO
Do star the repo if you liked it! ⭐

I was able to build this mini project using this video tutorial.

Thanks for reading! 😻

Did you find this article valuable?

Support Eshaa Bhasin by becoming a sponsor. Any amount is appreciated!