Get the HTTP Method from a Request

· 209 words · 1 minute read

When working with any form of http communication in Go you’re going to come across scenarios where you need to know a request’s method - whether it’s a GET, POST, etc.

If you’re writing an API with Go you’ll most likely have the incoming request in the form of a http.Request object. This request has Method property which allows you to get the http method in the form of a string. Optionally, we can also use some constants to make working with these methods easier.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
    "net/http"
    "io"
)

func main() {
    // Create a basic http example to demonstrate example
    http.Handle("/", http.HandlerFunc(ExampleHandler))
    http.ListenAndServe(":8080", nil)
}

func ExampleHandler(w http.ResponseWriter, r *http.Request) {
    // This handler will run for all types of HTTP request, but we can use r.Method to 
    // determine which method is being used and validate the request based on this.
    if r.Method == http.MethodGet {
        io.WriteString(w, "This is a get request")
    } else if r.Method == http.MethodPost {
        io.WriteString(w, "This is a post request")
    } else {
        io.WriteString(w, "This is a " + r.Method + " request")
    }
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!