Search code examples
go

How can I handle http requests of different methods to / in Go?


I'm trying to figure out the best way to handle requests to / and only / in Go and handle different methods in different ways. Here's the best I've come up with:

package main

import (
    "fmt"
    "html"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path != "/" {
            http.NotFound(w, r)
            return
        }

        if r.Method == "GET" {
            fmt.Fprintf(w, "GET, %q", html.EscapeString(r.URL.Path))
        } else if r.Method == "POST" {
            fmt.Fprintf(w, "POST, %q", html.EscapeString(r.URL.Path))
        } else {
            http.Error(w, "Invalid request method.", 405)
        }
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

Is this idiomatic Go? Is this the best I can do with the standard http lib? I'd much rather do something like http.HandleGet("/", handler) as in express or Sinatra. Is there a good framework for writing simple REST services? web.go looks attractive but appears stagnant.

Thank you for your advice.


Solution

  • From Go 1.22.0 on you can put the HTTP method before the endpoint

    package main
    
    import (
        "net/http"
    )
    
    func main() {
        router := http.NewServeMux()
        router.HandleFunc("GET /", myHandler)    
        router.HandleFunc("GET /other", myOtherHandler)
        router.HandleFunc("POST /data", myPostHandler)
        http.ListenAndServe(":8080", router)
    }
    

    https://go.dev/blog/routing-enhancements