Skip to content

Instantly share code, notes, and snippets.

@josue
Created June 30, 2017 04:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josue/598ac048f78362f593f49436680b60b7 to your computer and use it in GitHub Desktop.
Save josue/598ac048f78362f593f49436680b60b7 to your computer and use it in GitHub Desktop.
Golang - Get HTTP headers from given string, and/or the value from specific header key
package main
import (
"log"
"net/http"
"strings"
)
/*
Returns a map array of all available headers.
@param string - URL given
@return map[string]interface{}
*/
func getURLHeaders(url string) map[string]interface {} {
response, err := http.Head(url)
if err != nil {
log.Fatal("Error: Unable to download URL (", url, ") with error: ", err)
}
if response.StatusCode != http.StatusOK {
log.Fatal("Error: HTTP Status = ", response.Status)
}
headers := make(map[string]interface{})
for k, v := range response.Header {
headers[strings.ToLower(k)] = string(v[0])
}
return headers
}
/*
Returns the header value from a given header key, if available, else returns empty string.
@param string - URL given
@param string - Header key
@return string
*/
func getURLHeaderByKey(url string, key string) string {
headers := getURLHeaders(url)
key = strings.ToLower(key)
if value, ok := headers[key]; ok {
return value.(string)
}
return ""
}
func main() {
url := "https://media.kairos.com/test1.jpg"
findByKey := "Content-Type"
contentType := getURLHeaderByKey(url, findByKey)
if contentType == "" {
log.Fatal(findByKey," is unavailable")
}
log.Println(findByKey,"=", contentType)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment