Servidores Web, Tipos de Peticiones

¿Qué tipos de peticiones web existen?

De igual forma como es posible responder a diferentes tipos de contenido (content types), es posible responder a diferentes tipos de peticiones (type requests). Estos pueden ser GET, POST, PUT y DELETE. Para crear un servidor en Go que detecte responda en base al tipo de petición realizada podemos echar mano del valor Method* del objeto http.Request.

package main

import "net/http"

func Home(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        http.NotFound(w, r)
        return
    }
    switch r.Method {
    case "GET":
        w.Write([]byte("Se realizó una petición GET"))
    case "POST":
        w.Write([]byte("Se realizó una petición POST"))
    case "PUT":
        w.Write([]byte("Se realizó una petición PUT"))
    case "DELETE":
        w.Write([]byte("Se realizó una petición DELETE"))
    default:
        w.Write([]byte("Se realizó una petición " + r.Method))
    }
}

func main() {
    http.HandleFunc("/", Home)
    http.ListenAndServe(":8000", nil)
}

Al igual que en el ejemplo en el que determinamos el content type, ahora hemos utilizado un switch para determinar el tipo de petición o request method.

En curl para especificar el tipo de petición se usa el parámetro -X GET.

¿Cómo realizar una petición GET con curl?

$ curl -is http://localhost:8000 -X GET
HTTP/1.1 200 OK
Date: Sun, 21 Apr 2019 02:07:43 GMT
Content-Length: 29
Content-Type: text/plain; charset=utf-8

Se realizó una petición GET

¿Cómo realizar una petición tipo POST con curl?

$ curl -is http://localhost:8000 -X POST
HTTP/1.1 200 OK
Date: Sun, 21 Apr 2019 02:08:19 GMT
Content-Length: 30
Content-Type: text/plain; charset=utf-8

Se realizó una petición POST

¿Cómo realizar una petición tipo PUT con curl?

$ curl -is http://localhost:8000 -X PUT
HTTP/1.1 200 OK
Date: Sun, 21 Apr 2019 02:09:26 GMT
Content-Length: 29
Content-Type: text/plain; charset=utf-8

Se realizó una petición PUT

¿Cómo realizar una petición tipo DELETE con curl?

$ curl -is http://localhost:8000 -X DELETE
HTTP/1.1 200 OK
Date: Sun, 21 Apr 2019 02:09:54 GMT
Content-Length: 32
Content-Type: text/plain; charset=utf-8

Se realizó una petición DELETE

VPN

  • Ir a la oferta de NordVPN

Moda

Accesorios