Skip to content

Commit

Permalink
Merge pull request #25 from jayeshmann/more-endpoints
Browse files Browse the repository at this point in the history
More endpoints for Go Web Server
  • Loading branch information
Anadee11 authored Oct 11, 2022
2 parents fbae904 + 20f3052 commit d1b453c
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
3 changes: 3 additions & 0 deletions go-web-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ to start http server on [`localhost:8080`](http://localhost:8080)
## Endpoints

- `GET /` - displays [`index.html`](static/index.html) inside [`static`](static/) directory
- `GET /hello` - displays a greeting
- `GET /form.html` - displays [`form.html`](static/form.html) inside [`static`](static/) directory
- `POST /form` - displays post request successful with form values

## Contributors

Expand Down
34 changes: 34 additions & 0 deletions go-web-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,43 @@ import (
"net/http"
)

func formHandler(w http.ResponseWriter, r *http.Request) {

if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}

if r.URL.Path != "/form" {
http.Error(w, "404 not found", http.StatusNotFound)
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.StatusMethodNotAllowed)
return
}
fmt.Fprintf(w, "Hello from /hello endpoint!")
}

func main() {
fileServer := http.FileServer(http.Dir("./static"))
http.Handle("/", fileServer)
http.HandleFunc("/hello", helloHandler)
http.HandleFunc("/form", formHandler)

fmt.Printf("Starting server at port 8080\n")
if err := http.ListenAndServe(":8080", nil); err != nil {
Expand Down
19 changes: 19 additions & 0 deletions go-web-server/static/form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</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>

0 comments on commit d1b453c

Please sign in to comment.