Skip to content

Commit 2defb2d

Browse files
committed
simple http server
1 parent 359104a commit 2defb2d

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

simple-http-server/main.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"net/http"
7+
)
8+
9+
func main() {
10+
fileServer := http.FileServer(http.Dir("./static"))
11+
http.Handle("/", fileServer)
12+
http.HandleFunc("/form", formHandler)
13+
http.HandleFunc("/hello", helloHandler)
14+
15+
fmt.Printf("Starting server at port 8080\n")
16+
17+
if err := http.ListenAndServe(":8080", nil); err != nil {
18+
log.Fatal(err)
19+
}
20+
}
21+
22+
func helloHandler(w http.ResponseWriter, r *http.Request) {
23+
if r.URL.Path != "/hello" {
24+
http.Error(w, "404 not found", http.StatusNotFound)
25+
return
26+
}
27+
if r.Method != "GET" {
28+
http.Error(w, "method is not supported", http.StatusNotFound)
29+
return
30+
}
31+
fmt.Fprintf(w, "Hello")
32+
}
33+
34+
func formHandler(w http.ResponseWriter, r *http.Request) {
35+
if err := r.ParseForm(); err != nil {
36+
fmt.Fprintf(w, "ParseForm() err: %v", err)
37+
return
38+
}
39+
fmt.Fprintf(w, "POST request successful")
40+
name := r.FormValue("name")
41+
address := r.FormValue("address")
42+
fmt.Fprintf(w, "Name = %v", name)
43+
fmt.Fprintf(w, "Address = %v", address)
44+
}

simple-http-server/static/form.html

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>Static Website | Form</title>
8+
</head>
9+
<body>
10+
<div>
11+
<form action="/form" method="POST">
12+
<label for="">Name</label>
13+
<input type="text" name="name" id="">
14+
<label for="">Address</label>
15+
<input type="text" name="address" id="">
16+
17+
<input type="submit" value="submit" id="">
18+
</form>
19+
</div>
20+
</body>
21+
</html>

simple-http-server/static/index.html

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>Static Website</title>
8+
</head>
9+
<body>
10+
<h2>Static Website</h2>
11+
</body>
12+
</html>

0 commit comments

Comments
 (0)