no doc
[gscan_quic.git] / util.go
blob3d15754ec2be7971739447c9a5177b558b8b9e35
1 package main
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "math/rand"
10 "os"
11 "path"
12 "strings"
15 // Gop
16 func readJsonConfig(filename string, config interface{}) error {
17 fileext := path.Ext(filename)
18 filename1 := strings.TrimSuffix(filename, fileext) + ".user" + fileext
20 cm := make(map[string]interface{})
21 for i, name := range []string{filename, filename1} {
22 f, err := os.Open(name)
23 if err != nil {
24 if i == 0 {
25 return err
26 } else {
27 continue
30 defer f.Close()
32 data, err := readJson(f)
33 if err != nil {
34 return err
37 data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
39 cm1 := make(map[string]interface{})
41 d := json.NewDecoder(bytes.NewReader(data))
42 d.UseNumber()
44 if err = d.Decode(&cm1); err != nil {
45 return err
48 if err = mergeMap(cm, cm1); err != nil {
49 return err
53 data, err := json.Marshal(cm)
54 if err != nil {
55 return err
58 d := json.NewDecoder(bytes.NewReader(data))
59 d.UseNumber()
61 return d.Decode(config)
64 func readJson(r io.Reader) ([]byte, error) {
65 s, err := ioutil.ReadAll(r)
66 if err != nil {
67 return s, err
70 lines := make([]string, 0)
71 for _, line := range strings.Split(strings.Replace(string(s), "\r\n", "\n", -1), "\n") {
72 line = strings.TrimSpace(line)
73 if line == "" || strings.HasPrefix(line, "//") {
74 continue
76 lines = append(lines, line)
79 var b bytes.Buffer
80 for i, line := range lines {
81 if i < len(lines)-1 {
82 nextLine := strings.TrimSpace(lines[i+1])
83 if nextLine == "]" ||
84 nextLine == "]," ||
85 nextLine == "}" ||
86 nextLine == "}," {
87 if strings.HasSuffix(line, ",") {
88 line = strings.TrimSuffix(line, ",")
92 b.WriteString(line)
95 return b.Bytes(), nil
98 func mergeMap(m1 map[string]interface{}, m2 map[string]interface{}) error {
99 for key, value := range m2 {
101 m1v, m1_has_key := m1[key]
102 m2v, m2v_is_map := value.(map[string]interface{})
103 m1v1, m1v_is_map := m1v.(map[string]interface{})
105 switch {
106 case !m1_has_key, !m2v_is_map:
107 m1[key] = value
108 case !m1v_is_map:
109 return fmt.Errorf("m1v=%#v is not a map, but m2v=%#v is a map", m1v, m2v)
110 default:
111 mergeMap(m1v1, m2v)
115 return nil
118 func randInt(l, u int) int {
119 return rand.Intn(u-l) + l
122 // llm.xadl
123 // unupk.bfrf.pvi
124 func randomHost() string {
125 a := make([][]byte, randInt(2, 4))
126 for i := range a {
127 m := randInt(3, 7)
128 b := make([]byte, m)
129 for j := 0; j < m; j++ {
130 b[j] = byte(randInt(97, 122))
132 a[i] = b
134 return string(bytes.Join(a, []byte{46}))