2
0

Parse versions string into struct

This commit is contained in:
Miloš Mileusnić
2023-04-14 13:24:20 +02:00
parent 6b745d3e81
commit 004f562b59
3 changed files with 83 additions and 22 deletions
+5 -10
View File
@@ -8,6 +8,8 @@ import (
// UserAgent struct containing all data extracted from parsed user-agent string
type UserAgent struct {
VersionNo VersionNo
OSVersionNo VersionNo
URL string
String string
Name string
@@ -15,16 +17,6 @@ type UserAgent struct {
OS string
OSVersion string
Device string
// VersionNo struct {
// Major int
// Minor int
// Patch int
// }
// OSVersionNo struct {
// Major int
// Minor int
// Patch int
// }
Mobile bool
Tablet bool
Desktop bool
@@ -344,6 +336,9 @@ func Parse(userAgent string) UserAgent {
}
}
parseVersion(ua.Version, &ua.VersionNo)
parseVersion(ua.OSVersion, &ua.OSVersionNo)
return ua
}
+1 -1
View File
@@ -164,7 +164,7 @@ func TestParse(t *testing.T) {
t.Error("\n", test[0], "Device should be", test[5], "not", ua.Device)
}
//fmt.Println(ua.OS, ua.OSVersion, ua.Device)
// fmt.Println(ua.Version, "==>", ua.VersionNoShort())
}
}
+66
View File
@@ -0,0 +1,66 @@
package useragent
import (
"fmt"
"strconv"
"strings"
)
type VersionNo struct {
Major int
Minor int
Patch int
}
func parseVersion(ver string, verno *VersionNo) {
var err error
parts := strings.Split(ver, ".")
if len(parts) > 0 {
if verno.Major, err = strconv.Atoi(parts[0]); err != nil {
return
}
}
if len(parts) > 1 {
if verno.Minor, err = strconv.Atoi(parts[1]); err != nil {
return
}
if len(parts) > 2 {
if verno.Patch, err = strconv.Atoi(parts[2]); err != nil {
return
}
}
}
return
}
// VersionNoShort return version string in format <Major>.<Minor>
func (ua UserAgent) VersionNoShort() string {
if ua.VersionNo.Major == 0 && ua.VersionNo.Minor == 0 && ua.VersionNo.Patch == 0 {
return ""
}
return fmt.Sprintf("%d.%d", ua.VersionNo.Major, ua.VersionNo.Minor)
}
// VersionNoFull returns version string in format <Major>.<Minor>.<Patch>
func (ua UserAgent) VersionNoFull() string {
if ua.VersionNo.Major == 0 && ua.VersionNo.Minor == 0 && ua.VersionNo.Patch == 0 {
return ""
}
return fmt.Sprintf("%d.%d.%d", ua.VersionNo.Major, ua.VersionNo.Minor, ua.VersionNo.Patch)
}
// OSVersionNoShort returns OS version string in format <Major>.<Minor>
func (ua UserAgent) OSVersionNoShort() string {
if ua.OSVersionNo.Major == 0 && ua.OSVersionNo.Minor == 0 && ua.OSVersionNo.Patch == 0 {
return ""
}
return fmt.Sprintf("%d.%d", ua.OSVersionNo.Major, ua.OSVersionNo.Minor)
}
// OSVersionNoFull returns OS version string in format <Major>.<Minor>.<Patch>
func (ua UserAgent) OSVersionNoFull() string {
if ua.OSVersionNo.Major == 0 && ua.OSVersionNo.Minor == 0 && ua.OSVersionNo.Patch == 0 {
return ""
}
return fmt.Sprintf("%d.%d.%d", ua.OSVersionNo.Major, ua.OSVersionNo.Minor, ua.OSVersionNo.Patch)
}