Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Last active May 22, 2019 01:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/b30d03c065e20868c8874a4a5de78387 to your computer and use it in GitHub Desktop.
Save parzibyte/b30d03c065e20868c8874a4a5de78387 to your computer and use it in GitHub Desktop.
/*
Cliente HTTP en Go con net/http
Ejemplo de petición HTTP Get en Golang
@author parzibyte
*/
package main
import (
"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/get"
peticion, err := http.NewRequest("GET", url, nil)
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)
}
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)
// Aquí puedes decodificar la respuesta si es un JSON, o convertirla a cadena
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