Skip to content

Instantly share code, notes, and snippets.

@deepanshumehtaa
Last active March 1, 2024 04:28
Show Gist options
  • Select an option

  • Save deepanshumehtaa/42f0afcb01d5b920c3300d7625e16e36 to your computer and use it in GitHub Desktop.

Select an option

Save deepanshumehtaa/42f0afcb01d5b920c3300d7625e16e36 to your computer and use it in GitHub Desktop.
Bare Go Server
// go run main.go
// create a static folder and create `static.html`
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, address := r.FormValue("name"), 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) {
fmt.Printf("URL: %s\n", r.URL.Path)
fmt.Printf("Method: %s\n", r.Method)
if r.Method != "GET" {
http.Error(w, "method is not supported", http.StatusNotFound)
return
}
fmt.Fprintf(w, "hello!")
}
func iqhandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "method is not supported", http.StatusNotFound)
return
}
// `Fprintf` used to format and write text to an output stream, such as a file or a network connection
fmt.Fprintf(w, "IQ is high ...!")
}
func main() {
fileServer := http.FileServer(http.Dir("./static"))
http.Handle("/", fileServer)
http.HandleFunc("/form", formHandler)
http.HandleFunc("/hello", helloHandler)
http.HandleFunc("/iq", iqhandler)
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