Simple Web Server in Go

List Topics
February 18, 2025
No Comments
8 min read

This project will help you build a basic HTTPS server using Go's net/http package. The goal is to serve a simple webpage and handle both GET and POST requests, while also leveraging goroutines to handle concurrent requests.

Core Concepts:

  • HTTP Handling: Using the net/http package to handle HTTP requests and responses.
  • Goroutines: Handling requests concurrently for better performance and responsiveness.

Project Overview:

  1. Serve a Simple Webpage: We will create a basic HTML webpage that will be served by our HTTPS server.
  2. Handle GET and POST Requests: The server will handle GET requests to display the webpage and POST requests to accept data from the user.
  3. Concurrency with Goroutines: To handle multiple requests simultaneously, we will use Go's goroutines, which allow for concurrent execution.

Step-by-Step Code Implementation:

  1. Setting up an HTTPS server: We'll create a simple HTTPS server using the net/http package. For security reasons, we'll need an SSL certificate and a private key for HTTPS.
  2. Handling GET and POST Requests:
    • GET: When the user accesses the root of the server, the server will return an HTML form.
    • POST: When the form is submitted, the server will process the data and display a response.

Full Code Example:

Go
package main

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

// Struct to store form data
type FormData struct {
	Name  string
	Email string
}

// Handler for GET request
func getHandler(w http.ResponseWriter, r *http.Request) {
	// Serve a simple HTML form on GET request
	tmpl := `
		<!DOCTYPE html>
		<html>
		<head>
			<title>Simple Web Server</title>
		</head>
		<body>
			<h1>Submit Your Information</h1>
			<form action="/submit" method="POST">
				<label for="name">Name: </label><input type="text" name="name" required><br>
				<label for="email">Email: </label><input type="email" name="email" required><br>
				<input type="submit" value="Submit">
			</form>
		</body>
		</html>`
	w.Header().Set("Content-Type", "text/html")
	w.Write([]byte(tmpl))
}

// Handler for POST request
func postHandler(w http.ResponseWriter, r *http.Request) {
	// Parse the form data
	err := r.ParseForm()
	if err != nil {
		http.Error(w, "Error parsing form", http.StatusBadRequest)
		return
	}

	// Create a FormData struct and extract values
	formData := FormData{
		Name:  r.FormValue("name"),
		Email: r.FormValue("email"),
	}

	// Display the submitted data
	tmpl := `
		<!DOCTYPE html>
		<html>
		<head>
			<title>Form Submission Result</title>
		</head>
		<body>
			<h1>Thank You for Your Submission</h1>
			<p><strong>Name:</strong> {{.Name}}</p>
			<p><strong>Email:</strong> {{.Email}}</p>
		</body>
		</html>`

	// Parsing the template with the form data
	t, err := template.New("result").Parse(tmpl)
	if err != nil {
		http.Error(w, "Error parsing template", http.StatusInternalServerError)
		return
	}
	
	// Execute the template with the formData
	t.Execute(w, formData)
}

// Main function to set up the server
func main() {
	// Route to serve the HTML form (GET)
	http.HandleFunc("/", getHandler)

	// Route to handle form submissions (POST)
	http.HandleFunc("/submit", postHandler)

	// Start the server with HTTPS
	log.Println("Starting HTTPS server on :8080")
	err := http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", nil) // Path to your SSL certificate and key
	if err != nil {
		log.Fatal("Error starting server: ", err)
	}
}

Explanation:

  1. HTTP GET Handler (getHandler):
    • The getHandler function serves a simple HTML form. When the user navigates to the server's root URL (e.g., https://localhost:8080/), they will be presented with an input form where they can submit their name and email.
  2. HTTP POST Handler (postHandler):
    • The postHandler function is responsible for handling POST requests made when the user submits the form. It parses the form data, stores it in a struct (FormData), and then renders a response showing the submitted information back to the user.
  3. Template Rendering:
    • Go's html/template package is used to render dynamic HTML responses. It injects the data (name and email) submitted by the user into the HTML response.
  4. HTTPS Server Setup:
    • The http.ListenAndServeTLS function starts an HTTPS server on port 8080. This requires an SSL certificate (cert.pem) and a private key (key.pem).
    • Note: For testing purposes, you can create self-signed certificates using openssl. For production, ensure that you use a valid SSL certificate from a trusted Certificate Authority (CA).

Running the Server:

  1. Create SSL Certificates (for local testing): If you don't already have SSL certificates, you can generate a self-signed certificate using the following openssl command: openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout key.pem -out cert.pem
  2. Run the Server: Save the above Go code in a file (e.g., main.go), and run the following command in the terminal: go run main.go This will start the server at https://localhost:8080.
  3. Testing:
    • Open your browser and navigate to https://localhost:8080/. You should see the form where you can enter your name and email.
    • After submitting the form, the server will show a thank-you message with the data you submitted.

Conclusion:

This is a basic example of a web server using HTTPS in Go. It demonstrates how to handle GET and POST requests, how to serve dynamic content with templates, and how to implement a basic form submission system. You can extend this project by adding features like validation, database integration, or improving security.


সিম্পল ওয়েব সার্ভার (প্রজেক্ট)

এই প্রজেক্টে, আপনি Go এর net/http প্যাকেজ ব্যবহার করে একটি বেসিক HTTPS সার্ভার তৈরি করবেন। মূল লক্ষ্য হল একটি সাধারণ ওয়েবপেজ সার্ভ করা এবং GET এবং POST রিকোয়েস্টগুলি হ্যান্ডল করা, সেইসাথে goroutines ব্যবহার করে কনকারেন্ট রিকোয়েস্টগুলি পরিচালনা করা।

মূল কনসেপ্ট:

  • HTTP হ্যান্ডলিং: net/http প্যাকেজ ব্যবহার করে HTTP রিকোয়েস্ট এবং রেসপন্স হ্যান্ডল করা।
  • Goroutines: একাধিক রিকোয়েস্ট একসাথে (কনকারেন্টলি) হ্যান্ডল করার জন্য goroutines ব্যবহার করা।

প্রজেক্টের সারাংশ:

  1. একটি সাধারণ ওয়েবপেজ সার্ভ করা: একটি বেসিক HTML ফর্ম তৈরি করা যা আমাদের HTTPS সার্ভার দ্বারা সার্ভ করা হবে।
  2. GET এবং POST রিকোয়েস্ট হ্যান্ডলিং: সার্ভারটি GET রিকোয়েস্টের মাধ্যমে ওয়েবপেজটি প্রদর্শন করবে এবং POST রিকোয়েস্টের মাধ্যমে ব্যবহারকারীর তথ্য গ্রহণ করবে।
  3. গোরুটিন ব্যবহার করে কনকারেন্ট রিকোয়েস্ট হ্যান্ডলিং: একাধিক রিকোয়েস্ট একসাথে হ্যান্ডল করার জন্য Go এর goroutines ব্যবহার করা হবে।

কোড উদাহরণ:

  1. HTTPS সার্ভার সেটআপ: আমরা একটি সাধারণ HTTPS সার্ভার তৈরি করব net/http প্যাকেজ ব্যবহার করে। নিরাপত্তার কারণে, HTTPS ব্যবহার করার জন্য SSL সার্টিফিকেট এবং প্রাইভেট কী প্রয়োজন হবে।
  2. GET এবং POST রিকোয়েস্ট হ্যান্ডলিং:
    • GET: যখন ব্যবহারকারী সার্ভারের মূল URL এ প্রবেশ করবে, তখন একটি HTML ফর্ম প্রদর্শিত হবে।
    • POST: যখন ফর্মটি সাবমিট হবে, সার্ভারটি ডেটা প্রক্রিয়া করবে এবং একটি রেসপন্স প্রদর্শন করবে।

সম্পূর্ণ কোড উদাহরণ:

Go
package main

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

// ফর্ম ডেটা সংরক্ষণ করার জন্য স্ট্রাক্ট
type FormData struct {
	Name  string
	Email string
}

// GET রিকোয়েস্টের জন্য হ্যান্ডলার
func getHandler(w http.ResponseWriter, r *http.Request) {
	// GET রিকোয়েস্টে একটি সাধারণ HTML ফর্ম সরবরাহ করা
	tmpl := `
		<!DOCTYPE html>
		<html>
		<head>
			<title>Simple Web Server</title>
		</head>
		<body>
			<h1>Submit Your Information</h1>
			<form action="/submit" method="POST">
				<label for="name">Name: </label><input type="text" name="name" required><br>
				<label for="email">Email: </label><input type="email" name="email" required><br>
				<input type="submit" value="Submit">
			</form>
		</body>
		</html>`
	w.Header().Set("Content-Type", "text/html")
	w.Write([]byte(tmpl))
}

// POST রিকোয়েস্টের জন্য হ্যান্ডলার
func postHandler(w http.ResponseWriter, r *http.Request) {
	// ফর্ম ডেটা পার্স করা
	err := r.ParseForm()
	if err != nil {
		http.Error(w, "Error parsing form", http.StatusBadRequest)
		return
	}

	// FormData স্ট্রাক্ট তৈরি এবং মান বের করা
	formData := FormData{
		Name:  r.FormValue("name"),
		Email: r.FormValue("email"),
	}

	// সাবমিট করা ডেটা প্রদর্শন করা
	tmpl := `
		<!DOCTYPE html>
		<html>
		<head>
			<title>Form Submission Result</title>
		</head>
		<body>
			<h1>Thank You for Your Submission</h1>
			<p><strong>Name:</strong> {{.Name}}</p>
			<p><strong>Email:</strong> {{.Email}}</p>
		</body>
		</html>`

	// টেমপ্লেট পার্স করা
	t, err := template.New("result").Parse(tmpl)
	if err != nil {
		http.Error(w, "Error parsing template", http.StatusInternalServerError)
		return
	}
	
	// টেমপ্লেট এক্সিকিউট করা
	t.Execute(w, formData)
}

// মেইন ফাংশন, যেখানে সার্ভার সেটআপ করা হবে
func main() {
	// HTML ফর্ম সার্ভ করার জন্য GET রিকোয়েস্ট হ্যান্ডলার
	http.HandleFunc("/", getHandler)

	// ফর্ম সাবমিশন হ্যান্ডল করার জন্য POST রিকোয়েস্ট হ্যান্ডলার
	http.HandleFunc("/submit", postHandler)

	// HTTPS সার্ভার চালু করা
	log.Println("Starting HTTPS server on :8080")
	err := http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", nil) // SSL সার্টিফিকেট এবং কী প্রয়োজন
	if err != nil {
		log.Fatal("Error starting server: ", err)
	}
}

ব্যাখ্যা:

  1. HTTP GET হ্যান্ডলার (getHandler):
    • getHandler ফাংশন একটি সাধারণ HTML ফর্ম সরবরাহ করে। যখন ব্যবহারকারী সার্ভারের মূল URL (যেমন https://localhost:8080/) এ যাবে, তখন একটি ইনপুট ফর্ম দেখানো হবে যেখানে তারা তাদের নাম এবং ইমেইল সাবমিট করতে পারবে।
  2. HTTP POST হ্যান্ডলার (postHandler):
    • postHandler ফাংশন POST রিকোয়েস্ট হ্যান্ডল করে, যখন ব্যবহারকারী ফর্ম সাবমিট করে। এটি ফর্ম ডেটা পার্স করে এবং তা একটি স্ট্রাক্ট (FormData) এ সংরক্ষণ করে, তারপর সেই ডেটা দিয়ে একটি ধন্যবাদ বার্তা দেখায়।
  3. টেমপ্লেট রেন্ডারিং:
    • Go এর html/template প্যাকেজ ব্যবহার করা হয়েছে ডাইনামিক HTML রেসপন্স রেন্ডার করতে। এতে ব্যবহারকারীর দেওয়া নাম এবং ইমেইল ডেটা HTML রেসপন্সে ইনজেক্ট করা হয়।
  4. HTTPS সার্ভার সেটআপ:
    • http.ListenAndServeTLS ফাংশন ব্যবহার করে সার্ভারটি 8080 পোর্টে HTTPS চালু হয়। এটি একটি SSL সার্টিফিকেট (cert.pem) এবং প্রাইভেট কী (key.pem) প্রয়োজন।
    • নোট: পরীক্ষার জন্য আপনি openssl ব্যবহার করে একটি সেল্ফ-সাইনড সার্টিফিকেট তৈরি করতে পারেন।

সার্ভার চালানো:

  1. SSL সার্টিফিকেট তৈরি করা (লোকাল পরীক্ষার জন্য): যদি আপনার SSL সার্টিফিকেট না থাকে, তাহলে আপনি নিম্নলিখিত openssl কমান্ড ব্যবহার করে একটি সেল্ফ-সাইনড সার্টিফিকেট তৈরি করতে পারেন: openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout key.pem -out cert.pem
  2. সার্ভার চালানো: উপরের Go কোডটি একটি ফাইলে (যেমন main.go) সংরক্ষণ করুন, তারপর টার্মিনালে এই কমান্ডটি রান করুন: go run main.go এর ফলে সার্ভারটি https://localhost:8080 ঠিকানায় চালু হবে।
  3. টেস্টিং:
    • ব্রাউজারে গিয়ে https://localhost:8080/ এ যান। আপনি একটি ফর্ম দেখতে পাবেন যেখানে আপনি আপনার নাম এবং ইমেইল ইনপুট করতে পারবেন।
    • ফর্ম সাবমিট করার পর, সার্ভারটি ধন্যবাদ জানিয়ে একটি বার্তা প্রদর্শন করবে এবং ব্যবহারকারীর দেওয়া ডেটা দেখাবে।

উপসংহার:

এটি একটি বেসিক HTTPS সার্ভার তৈরির উদাহরণ যা Go-তে তৈরি করা হয়েছে। এখানে GET এবং POST রিকোয়েস্ট হ্যান্ডলিং, টেমপ্লেট রেন্ডারিং এবং একটি বেসিক ফর্ম সাবমিশন সিস্টেম দেখানো হয়েছে। আপনি এই প্রজেক্টটি আরও উন্নত করতে পারেন, যেমন ভ্যালিডেশন যোগ করা, ডাটাবেস সংযোগ করা, অথবা নিরাপত্তা উন্নত করা।

©2025 Linux Bangla | Developed & Maintaind by Linux Bangla.