Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created July 25, 2021 13:58
Show Gist options
  • Save parzibyte/b9eda3b737e0bd038da64a0173f919fb to your computer and use it in GitHub Desktop.
Save parzibyte/b9eda3b737e0bd038da64a0173f919fb to your computer and use it in GitHub Desktop.
Averiguar host de petición HTTP con Go
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"strings"
)
const PuertoEscuchaServidor = ":8080"
func main() {
/*
Leer puerto si es que lo pasaron en la línea de comandos
*/
puerto := flag.String("puerto", PuertoEscuchaServidor, "Puerto de escucha del servidor")
flag.Parse()
puertoReal := *puerto
// Agregar los dos puntos si es necesario
if strings.Index(puertoReal, ":") == -1 {
puertoReal = ":" + puertoReal
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Cors
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
responderHttpConExito(fmt.Sprintf("El Origin es: '%s'", r.Header.Get("Origin")), w)
log.Printf("El Origin es: '%s'", r.Header.Get("Origin"))
})
log.Fatal(http.ListenAndServe(puertoReal, nil))
}
func responderHttpConExito(data interface{}, w http.ResponseWriter) {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment