DEV Community

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

Posted on

3

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs