4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Golang で URL から charset を取得するのを書いたのですが、他にもっとよい方法があるとおもうのです...

Posted at

他によい方法がある気がするのですが...わからないので、書いてみました。

URL から、その charset を取得する。

main.go
package main

import (
	"fmt"
	"net/http"
	"regexp"
	"github.com/PuerkitoBio/goquery"
)


func getCharset(url string) (charset string) {
	res, err := http.Get(url)
	if err != nil {
		// handle error
	}
	defer res.Body.Close()

	doc, _ := goquery.NewDocument(url)
	doc.Find("meta").Each(func(_ int, s *goquery.Selection) {

		// <meta charset="utf-8"> の場合
		charsetAttr, _ := s.Attr("charset")
		if charsetAttr != "" {
			charset = charsetAttr
		}

		// <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> の場合
		httpEquiv, _ := s.Attr("http-equiv")
		if httpEquiv == "Content-Type" {
			content, _ := s.Attr("content")
			rep := regexp.MustCompile(`.*charset=(.+)`)
			charsetStr := rep.ReplaceAllString(content, "$1")
			if charsetStr != "" {
				charset = charsetStr
			}
		}
	})
	return charset
}

func main() {
	url := "https://qiita.com/trend"
	a := getCharset(url)
	fmt.Printf("%v", a)
}
$ go run main.go
UTF-8%
4
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?