Webserver
Project Structure¶
To run these projects, organize your files as follows:
- Shared HTML Files These are the static files used by both servers.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Static Website</title>
</head>
<body>
<h2>Static Website</h2>
<p>Welcome to the home page!</p>
</body>
</html>
form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<form method="POST" action="/form">
<label>Name</label><input name="name" type="text" value="" />
<label>Address</label><input name="address" type="text" value="" />
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
Implementation¶
main.go
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 successful\n")
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 server at port 8080\n")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
# Route for the Root (serves index.html)
@app.route('/')
def index():
return render_template('index.html')
# Route for /hello
@app.route('/hello')
def hello():
return "hello!"
# Route for /form (handles both GET to show and POST to process)
@app.route('/form', methods=['GET', 'POST'])
def form_handler():
if request.method == 'POST':
name = request.form.get('name')
address = request.form.get('address')
return f"POST request successful<br>Name = {name}<br>Address = {address}"
return render_template('form.html')
if __name__ == '__main__':
print("Starting server at port 8080")
app.run(port=8080)
How to Run¶
Go: Open your terminal in the go-server folder and run:
Python: Ensure Flask is installed (pip install flask), then run:
Both servers will be accessible at http://localhost:8080. You can visit /hello to see the greeting or /form to test the data submission