aboutsummaryrefslogtreecommitdiff
path: root/feed/score.go
blob: 724e8f00ced14550b604085df7a12f9c8e1c59f6 (plain)
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
package feed

import (
  "encoding/json"
  "fmt"
  "math"
  "strconv"
)

// CVSS score
type Score uint8

// Unmarshal CVSS score from JSON.
func (me *Score) UnmarshalJSON(b []byte) error {
  // decode float, check for error
  var v float64
  if err := json.Unmarshal(b, &v); err != nil {
    return err
  }

  // check score
  if v < 0.0 || v > 10.0 {
    return fmt.Errorf("CVSS score out of bounds: %2.1f", v)
  }

  // save result, return success
  *me = Score(uint8(math.Trunc(10.0 * v)))
  return nil
}

// Convert to string.
func (me Score) String() string {
  val := float64(me) / 10.0
  return strconv.FormatFloat(val, 'f', 1, 64)
}