Skip to content

Commit a881f7d

Browse files
committed
Made HTML output dynamic using html/template to output variables such as origin IP, request method and destination hostname
1 parent 4d51c33 commit a881f7d

File tree

2 files changed

+45
-12
lines changed

2 files changed

+45
-12
lines changed

html/index.html

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
<!DOCTYPE html>
22
<html lang="en">
3-
<head>
4-
<meta charset="UTF-8">
5-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6-
<title>Simple HTTP Server</title>
7-
</head>
8-
<body>
9-
<h1>Welcome to Simple HTTP Server</h1>
10-
<h3>by Paresh Pawar</h3>
11-
</body>
12-
</html>
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>Simple HTTP Server</title>
7+
</head>
8+
<body>
9+
<h1>Welcome to Simple HTTP Server</h1>
10+
<h3>by Paresh Pawar</h3>
11+
<ul>
12+
<li>Origin IP: {{.Origin}}</li>
13+
<li>Request Method: {{.Type}}</li>
14+
<li>Destination: {{.Hostname}}</li>
15+
</ul>
16+
</body>
17+
</html>

simple_http_server.go

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,19 @@ package main
22

33
import (
44
"fmt"
5+
"html/template"
56
"log"
67
"net/http"
78
"os"
89
"time"
910

1011
"github.com/common-nighthawk/go-figure"
11-
1212
"pareshpawar.com/simple-http-server/utils"
1313
)
1414

1515
func main() {
1616
http.HandleFunc("/", handler)
17-
http.Handle("/html/", http.StripPrefix("/html/", http.FileServer(http.Dir("./html"))))
17+
http.HandleFunc("/html/", htmlhandler)
1818
serverBrand := figure.NewColorFigure("Simple HTTP Server", "straight", "green", true)
1919
serverBrand.Print()
2020
myBrand := figure.NewColorFigure("by PareshPawar.com", "term", "green", true)
@@ -23,6 +23,34 @@ func main() {
2323
log.Fatal(http.ListenAndServe("0.0.0.0:8081", nil))
2424
}
2525

26+
func check(err error) {
27+
if err != nil {
28+
log.Fatal(err)
29+
}
30+
}
31+
32+
func htmlhandler(w http.ResponseWriter, r *http.Request){
33+
34+
file, err := os.ReadFile("html/index.html")
35+
check(err)
36+
37+
template, err := template.New("webpage").Parse(string(file))
38+
check(err)
39+
40+
data := struct {
41+
Origin string
42+
Type string
43+
Hostname string
44+
}{
45+
Origin: r.RemoteAddr,
46+
Type: r.Method,
47+
Hostname: r.Host,
48+
}
49+
50+
err = template.Execute(w, data)
51+
check(err)
52+
}
53+
2654
func handler(w http.ResponseWriter, r *http.Request) {
2755
timestamp := time.Now()
2856
if r.Method == "GET" {

0 commit comments

Comments
 (0)