-
-
Save parzibyte/1c8893b51b3667ae1a4cf9ccd1a1fb42 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Cliente HTTP en Go con net/http | |
Ejemplo de petición HTTP PUT enviando datos JSON | |
en Golang | |
@author parzibyte | |
*/ | |
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"io/ioutil" | |
"log" | |
"net/http" | |
) | |
func main() { | |
clienteHttp := &http.Client{} | |
// Si quieres agregar parámetros a la URL simplemente haz una | |
// concatenación :) | |
url := "https://httpbin.org/put" | |
type Usuario struct { | |
Nombre string | |
Edad int | |
} | |
usuario := Usuario{ | |
Nombre: "Luis", | |
Edad: 22, | |
} | |
usuarioComoJson, err := json.Marshal(usuario) | |
if err != nil { | |
// Maneja el error de acuerdo a tu situación | |
log.Fatalf("Error codificando usuario como JSON: %v", err) | |
} | |
peticion, err := http.NewRequest("PUT", url, bytes.NewBuffer(usuarioComoJson)) | |
if err != nil { | |
// Maneja el error de acuerdo a tu situación | |
log.Fatalf("Error creando petición: %v", err) | |
} | |
// Podemos agregar encabezados | |
peticion.Header.Add("Content-Type", "application/json") | |
peticion.Header.Add("X-Hola-Mundo", "Ejemplo") | |
respuesta, err := clienteHttp.Do(peticion) | |
if err != nil { | |
// Maneja el error de acuerdo a tu situación | |
log.Fatalf("Error haciendo petición: %v", err) | |
} | |
// No olvides cerrar el cuerpo al terminar | |
defer respuesta.Body.Close() | |
cuerpoRespuesta, err := ioutil.ReadAll(respuesta.Body) | |
if err != nil { | |
log.Fatalf("Error leyendo respuesta: %v", err) | |
} | |
// Aquí puedes decodificar la respuesta si es un JSON, o convertirla a cadena | |
respuestaString := string(cuerpoRespuesta) | |
log.Printf("Código de respuesta: %d", respuesta.StatusCode) | |
log.Printf("Encabezados: '%q'", respuesta.Header) | |
contentType := respuesta.Header.Get("Content-Type") | |
log.Printf("El tipo de contenido: '%s'", contentType) | |
log.Printf("Cuerpo de respuesta del servidor: '%s'", respuestaString) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment