Skip to content

Instantly share code, notes, and snippets.

@SoftwareDevPro
Created June 19, 2020 01:46
Show Gist options
  • Select an option

  • Save SoftwareDevPro/b6d413fe1085e52accc72f3e67d41226 to your computer and use it in GitHub Desktop.

Select an option

Save SoftwareDevPro/b6d413fe1085e52accc72f3e67d41226 to your computer and use it in GitHub Desktop.
A web server with Go
<!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>
<!DOCTYPE html>
<html>
<head>
<title>Static Website</title>
</head>
<body>
<h2>Static Website</h2>
</body>
</html>
package main
import (
"fmt"
"log"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
// Make sure the request path is correct.
if r.URL.Path != "/helloworld" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
// Make sure the request method is correct.
if r.Method != "GET" {
http.Error(w, "Method is not supported.", http.StatusNotFound)
return
}
// Send back the response.
fmt.Fprintf(w, "Hello World!")
}
func formHandler(w http.ResponseWriter, r *http.Request) {
// Parse the incoming request form.
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
// Print out the request, name and address values.
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 main() {
// Create a file server, and use static as the root directory
fileServer := http.FileServer(http.Dir("./static"))
http.Handle("/", fileServer)
// Handle the form endpoint
http.HandleFunc("/form", formHandler)
// Handle the basic hello world endpoint
http.HandleFunc("/helloworld", helloHandler)
// Start the server on port 8080
fmt.Printf("Starting server at port 8080\n")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment