idna.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package idna implements IDNA2008 (Internationalized Domain Names for
  5. // Applications), defined in RFC 5890, RFC 5891, RFC 5892, RFC 5893 and
  6. // RFC 5894.
  7. package idna // import "golang.org/x/net/idna"
  8. import (
  9. "strings"
  10. "unicode/utf8"
  11. )
  12. // TODO(nigeltao): specify when errors occur. For example, is ToASCII(".") or
  13. // ToASCII("foo\x00") an error? See also http://www.unicode.org/faq/idn.html#11
  14. // acePrefix is the ASCII Compatible Encoding prefix.
  15. const acePrefix = "xn--"
  16. // ToASCII converts a domain or domain label to its ASCII form. For example,
  17. // ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and
  18. // ToASCII("golang") is "golang".
  19. func ToASCII(s string) (string, error) {
  20. if ascii(s) {
  21. return s, nil
  22. }
  23. labels := strings.Split(s, ".")
  24. for i, label := range labels {
  25. if !ascii(label) {
  26. a, err := encode(acePrefix, label)
  27. if err != nil {
  28. return "", err
  29. }
  30. labels[i] = a
  31. }
  32. }
  33. return strings.Join(labels, "."), nil
  34. }
  35. // ToUnicode converts a domain or domain label to its Unicode form. For example,
  36. // ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and
  37. // ToUnicode("golang") is "golang".
  38. func ToUnicode(s string) (string, error) {
  39. if !strings.Contains(s, acePrefix) {
  40. return s, nil
  41. }
  42. labels := strings.Split(s, ".")
  43. for i, label := range labels {
  44. if strings.HasPrefix(label, acePrefix) {
  45. u, err := decode(label[len(acePrefix):])
  46. if err != nil {
  47. return "", err
  48. }
  49. labels[i] = u
  50. }
  51. }
  52. return strings.Join(labels, "."), nil
  53. }
  54. func ascii(s string) bool {
  55. for i := 0; i < len(s); i++ {
  56. if s[i] >= utf8.RuneSelf {
  57. return false
  58. }
  59. }
  60. return true
  61. }