-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathquran.go
85 lines (69 loc) · 1.39 KB
/
quran.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package quran
import (
"encoding/xml"
"io/ioutil"
"math/rand"
"os"
"strings"
"time"
"github.com/airani/quran/dataset"
)
// Quran struct of xml file
type Quran struct {
Surahs []Surah `xml:"sura"`
}
// NewSimple Quran
func NewSimple() (Quran, error) {
return NewQuranByXml(dataset.Simple())
}
// NewSimpleClean Quran
func NewSimpleClean() (Quran, error) {
return NewQuranByXml(dataset.SimpleClean())
}
// NewQuranByXml read xml string of Quran and returns a Quran struct
func NewQuranByXml(xmlStr string) (q Quran, err error) {
r := strings.NewReader(xmlStr)
b, err := ioutil.ReadAll(r)
if err != nil {
return
}
err = xml.Unmarshal(b, &q)
if err != nil {
return
}
return
}
// NewQuranByXmlFile read xml file of Quran and returns a Quran struct
func NewQuranByXmlFile(file string) (q Quran, err error) {
xmlFile, err := os.Open(file)
if err != nil {
return
}
defer func() {
if ferr := xmlFile.Close(); ferr != nil {
err = ferr
}
}()
b, err := ioutil.ReadAll(xmlFile)
if err != nil {
return
}
err = xml.Unmarshal(b, &q)
if err != nil {
return
}
return
}
// Surah Returns a Surah by number
func (q Quran) Surah(n int) Surah {
if n > len(q.Surahs) || n == 0 {
return Surah{}
}
return q.Surahs[n-1]
}
// RandSurah Returns a Surah by random
func (q Quran) RandSurah() Surah {
rand.Seed(time.Now().UnixNano())
n := rand.Intn(len(q.Surahs)) + 1
return q.Surah(n)
}