-
Notifications
You must be signed in to change notification settings - Fork 2
/
doi.go
73 lines (62 loc) · 1.95 KB
/
doi.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
// Package doi is a library for parsing and dealing with digital object identifiers.
package doi
import (
"github.com/pkg/errors"
)
// DigitalObjectIdentifier is a struct that contains the three fields of a doi:
// https://www.doi.org/doi_handbook/2_Numbering.html#2.2
type DigitalObjectIdentifier struct {
General string
DirectoryIndicator string
RegistrantCode string
}
// Parse takes a string as input and attempts to parse a valid doi
// from it. The parsing is done to conform to the standard outlined in
// https://www.doi.org/doi_handbook/2_Numbering.html#2.2.
func Parse(doi string) (DigitalObjectIdentifier, error) {
var general, directoryIndicator, registrantCode string
state := 0
for _, c := range doi {
if state == 0 && c == '.' {
state++
continue
} else if state == 1 && c == '/' {
state++
continue
}
switch state {
case 0:
general += string(c)
case 1:
directoryIndicator += string(c)
case 2:
registrantCode += string(c)
}
}
if general != "10" {
return DigitalObjectIdentifier{}, errors.New("doi does not start with 10")
} else if len(directoryIndicator) == 0 || len(registrantCode) == 0 {
return DigitalObjectIdentifier{}, errors.New("directory indicator or registrant code was empty")
}
return DigitalObjectIdentifier{
General: general,
DirectoryIndicator: directoryIndicator,
RegistrantCode: registrantCode,
}, nil
}
// IsValid checks to see if a DigitalObjectIdentifier is valid or not.
func (d DigitalObjectIdentifier) IsValid() bool {
if d.General != "10" {
return false
} else if len(d.DirectoryIndicator) == 0 || len(d.RegistrantCode) == 0 {
return false
}
return true
}
// ToString creates a string representation of a DigitalObjectIdentifier.
func (d DigitalObjectIdentifier) ToString() (string, error) {
if d.IsValid() {
return d.General + "." + d.DirectoryIndicator + "/" + d.RegistrantCode, nil
}
return "", errors.New("doi is invalid, not printable")
}