Files
sam3/config.go

76 lines
1.6 KiB
Go
Raw Normal View History

2015-12-14 09:00:11 -05:00
package sam3
import (
2016-02-10 17:54:17 -05:00
"fmt"
"net"
"strconv"
"github.com/eyedeekay/sam3/i2pkeys"
2015-12-14 09:00:11 -05:00
)
// sam config
// options map
type Options map[string]string
// obtain sam options as list of strings
func (opts Options) AsList() (ls []string) {
2016-02-10 17:54:17 -05:00
for k, v := range opts {
ls = append(ls, fmt.Sprintf("%s=%s", k, v))
}
return
2015-12-14 09:00:11 -05:00
}
// Config is the config type for the sam connector api for i2p which allows applications to 'speak' with i2p
type Config struct {
2016-02-10 17:54:17 -05:00
Addr string
Opts Options
Session string
Keyfile string
2015-12-14 09:00:11 -05:00
}
// create new sam connector from config with a stream session
func (cfg *Config) StreamSession() (session *StreamSession, err error) {
2016-02-10 17:54:17 -05:00
// connect
var s *SAM
s, err = NewSAM(cfg.Addr)
if err == nil {
// ensure keys exist
var keys i2pkeys.I2PKeys
2016-02-10 17:54:17 -05:00
keys, err = s.EnsureKeyfile(cfg.Keyfile)
if err == nil {
// create session
session, err = s.NewStreamSession(cfg.Session, keys, cfg.Opts.AsList())
}
}
return
2015-12-14 09:00:11 -05:00
}
// create new sam datagram session from config
func (cfg *Config) DatagramSession() (session *DatagramSession, err error) {
2016-02-10 17:54:17 -05:00
// connect
var s *SAM
s, err = NewSAM(cfg.Addr)
if err == nil {
// ensure keys exist
var keys i2pkeys.I2PKeys
2016-02-10 17:54:17 -05:00
keys, err = s.EnsureKeyfile(cfg.Keyfile)
if err == nil {
// determine udp port
var portstr string
_, portstr, err = net.SplitHostPort(cfg.Addr)
if err == nil {
var port int
port, err = strconv.Atoi(portstr)
if err == nil && port > 0 {
// udp port is 1 lower
port--
// create session
session, err = s.NewDatagramSession(cfg.Session, keys, cfg.Opts.AsList(), port)
}
}
}
}
return
2015-12-14 09:00:11 -05:00
}