string.go 932 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package utils
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "encoding/xml"
  6. "golang.org/x/net/html/charset"
  7. "golang.org/x/text/encoding/simplifiedchinese"
  8. "golang.org/x/text/transform"
  9. "io/ioutil"
  10. )
  11. func ToJSONString(v interface{}) string {
  12. b, _ := json.Marshal(v)
  13. return string(b)
  14. }
  15. func ToPrettyString(v interface{}) string {
  16. b, _ := json.MarshalIndent(v, "", " ")
  17. return string(b)
  18. }
  19. func GbkToUtf8(s []byte) ([]byte, error) {
  20. reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewDecoder())
  21. d, e := ioutil.ReadAll(reader)
  22. if e != nil {
  23. return s, e
  24. }
  25. return d, nil
  26. }
  27. func DecodeGbk(v interface{}, body []byte) error {
  28. bodyBytes, err := GbkToUtf8(body)
  29. if err != nil {
  30. return err
  31. }
  32. decoder := xml.NewDecoder(bytes.NewReader(bodyBytes))
  33. decoder.CharsetReader = charset.NewReaderLabel
  34. err = decoder.Decode(v)
  35. return err
  36. }