Averiguar host de petición HTTP con Go
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
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