Instagram
youtube
Facebook
  • 1 year, 7 months ago
  • 750 Views

Creating Web Server with Golang

Yaman Birla
Table of Contents

In this Article, We will be implementing a simple basic web server to understand the net/http package in golang which provides HTTP client and server implementations. Get, Head, Post, and Post Form make HTTP (or HTTPS) requests.

In this Article, We will be implementing a simple basic web server to understand the net/http package in golang which provides HTTP client and server implementations. Get, Head, Post, and PostForm make HTTP (or HTTPS) requests. 

Web servers are usually a pretty fascinating and reasonably straightforward project to get up and running. We will also serve the static files once the client-server connection is established and also serve these files over HTTPS.

Firstly, We will be creating a Simple Basic server:

Here, is the code given below:


 

package main

import (
	"fmt"
	"html"
	"log"
	"net/http"
)

func main() {

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %q!", html.EscapeString(r.URL.Path))
	})

	http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hi")
	})

	log.Fatal(http.ListenAndServe(":8081", nil))

}

 


This code will return whatever is in the path of your URL included. It could be any string that passes into the URL and it will print on the page. So, whenever a request is made on http://localhost:8081/ the first handler will match the string pattern and responds accordingly.

 

Run this server using go run main.go and go on to http://localhost:8081/yaman once it loads you will see your added string in the “Hello, world!” fashion. 

 

 

Now that we have created our simple basic web server, Let's attempt incrementing a counter whenever a certain URL is accessed. Because the web server is asynchronous, we'll need to protect our counter using a mutex to avoid getting struck with race-condition issues.

Mutex is a locking mechanism in golang to know more about mutex click-here

 

The code for updated_main.go is given below:


 

package main

import (
	"fmt"
	"log"
	"net/http"
	"strconv"
	"sync"
)

var counter int
var mutex = &sync.Mutex{}

func echoString(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "hello stranger")
}

func incrementCounter(w http.ResponseWriter, r *http.Request) {
	mutex.Lock()
	counter++
	fmt.Fprintf(w, strconv.Itoa(counter))
	mutex.Unlock()
}

func main() {
	http.HandleFunc("/", echoString)

	http.HandleFunc("/increment", incrementCounter)

	http.HandleFunc("/yaman", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hi yaman!")
	})

	log.Fatal(http.ListenAndServe(":8081", nil))

}

 

 


Now, run this code and head on to localhost:8081/increment

Below is the screenshots attached of the server and you should see the current count which will be locked, incremented, and then unlocked every time you make a request to that page.

 


 


 


 

 

Now, that we are familiar with some of the web server golang coding, we’re gonna dive into serving static files.

First, we will create an Html file in your project directory. Once you have that, you can change your web server code to use the http.ServeFile method. Basically, this takes the URL of the request made to the server and returns the index.html file which is rendered as HTML in the browser if it contains for example index.html.

 

HTML:


<html>
  <head>
    <title>Hello web enthusiasts</title>
  </head>
  <body>
    <h2>Hello World!</h2>
  </body>
</html>

 

Golang Server Code:


package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, r.URL.Path[1:])
	})

	http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hi")
	})

	log.Fatal(http.ListenAndServe(":8081", nil))

}

 

Screenshot of running server:

 

 

GitHub: https://github.com/cosmic-weber/Golang/tree/main/Web-server

Conclusion:

I hope you understand the primary web server implementation in golang using net/http package. This is part of ongoing Golang tutorials in which we use APIs and do some development work.

 

Stay Tuned!

 

Add a comment: