DEV Community

Cover image for web server with plain go
Arjun Shetty
Arjun Shetty

Posted on

web server with plain go

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"))
        }

    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

RIGHT ONE!

@baseurl = http://127.0.0.1:8080
GET baseurl/product
Enter fullscreen mode Exit fullscreen mode

Image credit - Philippe Oursel

Top comments (0)