Trying out a simple web app server in golang native library. Internet is filled with frameworks, before exploring any frameworks trying if the native is enough for the solution in hand.
func main() {
http.HandleFunc("/", rootHandler())
http.HandleFunc("/products", productHandler())
fmt.Println("Listening on 8080")
http.ListenAndServe(":8080", nil)
}
func rootHandler() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
w.Write([]byte("ROOT GET OK"))
case http.MethodPost:
w.Write([]byte("ROOT POST OK"))
}
}
}
func productHandler() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
w.Write([]byte("PRODUCT GET OK"))
case http.MethodPost:
w.Write([]byte("PRODUCT POST OK"))
}
}
}
Careful with slashes in your request url. I spent almost an hour figuring out why isn't the code working.
WRONG ONE!
@baseurl = http://127.0.0.1:8080/
GET baseurl/product
RIGHT ONE!
@baseurl = http://127.0.0.1:8080
GET baseurl/product
Image credit - Philippe Oursel
Top comments (0)