Last active
March 1, 2024 04:28
-
-
Save deepanshumehtaa/42f0afcb01d5b920c3300d7625e16e36 to your computer and use it in GitHub Desktop.
Bare Go Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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