~moody/ninep

ref: d394458419b1bc3ea43eb8426ccecfc427352ab9 ninep/srv_example_test.go -rw-r--r-- 1.6 KiB
d3944584 — Jacob Moody Rework api 2 months ago
                                                                                
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 ninep_test

import (
	"errors"
	"fmt"
	"log"

	"git.sr.ht/~moody/ninep"
)

//Embed NopFS to cover message types we dont plan
//to support.
type myfs struct {
	ninep.NopFS
	i     int
	msg   []byte
	rootD ninep.Dir
	fileD ninep.Dir
}

func (e *myfs) Attach(t *ninep.Tattach) {
	e.msg = []byte(fmt.Sprintf("You are lucky number %d\n", e.i))
	e.fileD = ninep.Dir{
		Qid:  ninep.Qid{1, 0, 0},
		Mode: 0x4,
		Len:  uint64(len(e.msg)),
		Name: "test",
		Uid:  "moody",
		Gid:  "moody",
		Muid: "moody",
	}
	e.rootD = ninep.Dir{
		Qid:  ninep.Qid{0, 0, ninep.QTDir},
		Name: "/",
		Mode: ninep.DMDir | 0777,
		Uid:  "moody",
		Gid:  "moody",
		Muid: "moody",
	}
	t.Respond(&e.rootD.Qid)
}

func (e *myfs) Walk(cur *ninep.Qid, next string) *ninep.Qid {
	if cur.Path == 0 && next == "test" {
		return &e.fileD.Qid
	}
	return nil
}

func (e *myfs) Open(t *ninep.Topen, q *ninep.Qid) {
	t.Respond(q, 8192)
}

var errNoFile = errors.New("no such file or directory")

func (e *myfs) Read(t *ninep.Tread, q *ninep.Qid) {
	switch q.Path {
	case 0:
		ninep.ReadDir(t, []ninep.Dir{e.fileD})
	case 1:
		ninep.ReadBuf(t, e.msg)
	default:
		t.Err(errNoFile)
	}
}

func (e *myfs) Stat(t *ninep.Tstat, q *ninep.Qid) {
	switch q.Path {
	case 0:
		t.Respond(&e.rootD)
	case 1:
		t.Respond(&e.fileD)
	default:
		t.Err(errNoFile)
	}
}

func Example() {
	i := 0
	//Create a new srv, where each new session is given an instance
	//of myfs. For each session i will be incremented.
	srv := ninep.NewSrv(func() ninep.FS { i++; return &myfs{i: i} })
	srv.Chatty9P = true
	log.Fatal(srv.ListenAndServe(":9999"))
}