_id
stringlengths 2
7
| title
stringlengths 1
118
| partition
stringclasses 3
values | text
stringlengths 52
85.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q181400
|
LoadCACertFile
|
test
|
func LoadCACertFile(cert string) (*x509.CertPool, error) {
// validate caCert, and setup certpool
ca, err := ioutil.ReadFile(cert)
if err != nil {
return nil, fmt.Errorf("could not load CA Certificate: %s ", err.Error())
}
certPool := x509.NewCertPool()
if err := certPool.AppendCertsFromPEM(ca); !err {
return nil, errors.New("could not append CA Certificate to CertPool")
}
return certPool, nil
}
|
go
|
{
"resource": ""
}
|
q181401
|
NewAuth
|
test
|
func NewAuth(opts ...Options) *Auth {
o := Options{}
if len(opts) != 0 {
o = opts[0]
}
h := defaultAuthErrorHandler
if o.AuthErrorHandler != nil {
h = o.AuthErrorHandler
}
return &Auth{
opt: o,
authErrHandler: http.HandlerFunc(h),
}
}
|
go
|
{
"resource": ""
}
|
q181402
|
ValidateRequest
|
test
|
func (a *Auth) ValidateRequest(r *http.Request) error {
// ensure we can process this request
if r.TLS == nil || r.TLS.VerifiedChains == nil {
return errors.New("no cert chain detected")
}
// TODO: Figure out if having multiple validated peer leaf certs is possible. For now, only validate
// one cert, and make sure it matches the first peer certificate
if r.TLS.PeerCertificates != nil {
if !bytes.Equal(r.TLS.PeerCertificates[0].Raw, r.TLS.VerifiedChains[0][0].Raw) {
return errors.New("first peer certificate not first verified chain leaf")
}
}
return nil
}
|
go
|
{
"resource": ""
}
|
q181403
|
Process
|
test
|
func (a *Auth) Process(w http.ResponseWriter, r *http.Request) error {
if err := a.ValidateRequest(r); err != nil {
return err
}
// Validate OU
if len(a.opt.AllowedOUs) > 0 {
err := a.ValidateOU(r.TLS.VerifiedChains[0][0])
if err != nil {
a.authErrHandler.ServeHTTP(w, r)
return err
}
}
// Validate CN
if len(a.opt.AllowedCNs) > 0 {
err := a.ValidateCN(r.TLS.VerifiedChains[0][0])
if err != nil {
a.authErrHandler.ServeHTTP(w, r)
return err
}
}
return nil
}
|
go
|
{
"resource": ""
}
|
q181404
|
ValidateCN
|
test
|
func (a *Auth) ValidateCN(verifiedCert *x509.Certificate) error {
var failed []string
for _, cn := range a.opt.AllowedCNs {
if cn == verifiedCert.Subject.CommonName {
return nil
}
failed = append(failed, verifiedCert.Subject.CommonName)
}
return fmt.Errorf("cert failed CN validation for %v, Allowed: %v", failed, a.opt.AllowedCNs)
}
|
go
|
{
"resource": ""
}
|
q181405
|
ValidateOU
|
test
|
func (a *Auth) ValidateOU(verifiedCert *x509.Certificate) error {
var failed []string
for _, ou := range a.opt.AllowedOUs {
for _, clientOU := range verifiedCert.Subject.OrganizationalUnit {
if ou == clientOU {
return nil
}
failed = append(failed, clientOU)
}
}
return fmt.Errorf("cert failed OU validation for %v, Allowed: %v", failed, a.opt.AllowedOUs)
}
|
go
|
{
"resource": ""
}
|
q181406
|
KeyLen
|
test
|
func KeyLen(x uint64) int {
n := 1
if x >= 1<<32 {
x >>= 32
n += 4
}
if x >= 1<<16 {
x >>= 16
n += 2
}
if x >= 1<<8 {
x >>= 8
n += 1
}
return n
}
|
go
|
{
"resource": ""
}
|
q181407
|
DefaultConfig
|
test
|
func DefaultConfig() Config {
newClientConfig := vaultclient.DefaultConfig()
newClientConfig.Address = "http://127.0.0.1:8200"
newVaultClient, err := vaultclient.NewClient(newClientConfig)
if err != nil {
panic(err)
}
newConfig := Config{
// Dependencies.
VaultClient: newVaultClient,
}
return newConfig
}
|
go
|
{
"resource": ""
}
|
q181408
|
New
|
test
|
func New(config Config) (spec.CertSigner, error) {
newCertSigner := &certSigner{
Config: config,
}
// Dependencies.
if newCertSigner.VaultClient == nil {
return nil, microerror.Maskf(invalidConfigError, "Vault client must not be empty")
}
return newCertSigner, nil
}
|
go
|
{
"resource": ""
}
|
q181409
|
New
|
test
|
func New(config Config) (spec.VaultFactory, error) {
newVaultFactory := &vaultFactory{
Config: config,
}
// Dependencies.
if newVaultFactory.Address == "" {
return nil, microerror.Maskf(invalidConfigError, "Vault address must not be empty")
}
if newVaultFactory.AdminToken == "" {
return nil, microerror.Maskf(invalidConfigError, "Vault admin token must not be empty")
}
return newVaultFactory, nil
}
|
go
|
{
"resource": ""
}
|
q181410
|
DefaultServiceConfig
|
test
|
func DefaultServiceConfig() ServiceConfig {
newClientConfig := vaultclient.DefaultConfig()
newClientConfig.Address = "http://127.0.0.1:8200"
newVaultClient, err := vaultclient.NewClient(newClientConfig)
if err != nil {
panic(err)
}
newConfig := ServiceConfig{
// Dependencies.
VaultClient: newVaultClient,
}
return newConfig
}
|
go
|
{
"resource": ""
}
|
q181411
|
NewService
|
test
|
func NewService(config ServiceConfig) (Service, error) {
// Dependencies.
if config.VaultClient == nil {
return nil, microerror.Maskf(invalidConfigError, "Vault client must not be empty")
}
newService := &service{
ServiceConfig: config,
}
return newService, nil
}
|
go
|
{
"resource": ""
}
|
q181412
|
Delete
|
test
|
func (s *service) Delete(clusterID string) error {
// Create a client for the system backend configured with the Vault token
// used for the current cluster's PKI backend.
sysBackend := s.VaultClient.Sys()
// Unmount the PKI backend, if it exists.
mounted, err := s.IsMounted(clusterID)
if err != nil {
return microerror.Mask(err)
}
if mounted {
err = sysBackend.Unmount(s.MountPKIPath(clusterID))
if err != nil {
return microerror.Mask(err)
}
}
return nil
}
|
go
|
{
"resource": ""
}
|
q181413
|
IsNoVaultHandlerDefined
|
test
|
func IsNoVaultHandlerDefined(err error) bool {
cause := microerror.Cause(err)
if cause != nil && strings.Contains(cause.Error(), "no handler for route") {
return true
}
return false
}
|
go
|
{
"resource": ""
}
|
q181414
|
New
|
test
|
func New(config Config) (Service, error) {
// Dependencies.
if config.VaultClient == nil {
return nil, microerror.Maskf(invalidConfigError, "Vault client must not be empty")
}
if config.PKIMountpoint == "" {
return nil, microerror.Maskf(invalidConfigError, "PKIMountpoint must not be empty")
}
service := &service{
vaultClient: config.VaultClient,
pkiMountpoint: config.PKIMountpoint,
}
return service, nil
}
|
go
|
{
"resource": ""
}
|
q181415
|
Create
|
test
|
func (s *service) Create(params CreateParams) error {
logicalStore := s.vaultClient.Logical()
data := map[string]interface{}{
"allowed_domains": params.AllowedDomains,
"allow_subdomains": params.AllowSubdomains,
"ttl": params.TTL,
"allow_bare_domains": params.AllowBareDomains,
"organization": params.Organizations,
}
_, err := logicalStore.Write(fmt.Sprintf("%s/roles/%s", s.pkiMountpoint, params.Name), data)
if err != nil {
return microerror.Mask(err)
}
return nil
}
|
go
|
{
"resource": ""
}
|
q181416
|
CreateJob
|
test
|
func CreateJob() Config {
return Config{
LockProvider: nil,
RuntimeProcessor: nil,
ResultProcessor: nil,
RuntimeProcessingFrequency: 200 * time.Millisecond,
SummaryBuffer: 1,
}
}
|
go
|
{
"resource": ""
}
|
q181417
|
Run
|
test
|
func (config *Config) Run() {
err := config.ensureLock()
if err != nil {
panic(err)
}
err = config.runWorker()
if err != nil {
panic(err)
}
}
|
go
|
{
"resource": ""
}
|
q181418
|
newWatcher
|
test
|
func newWatcher(dir_notify bool, initpaths ...string) (w *Watcher) {
w = new(Watcher)
w.auto_watch = dir_notify
w.paths = make(map[string]*watchItem, 0)
var paths []string
for _, path := range initpaths {
matches, err := filepath.Glob(path)
if err != nil {
continue
}
paths = append(paths, matches...)
}
if dir_notify {
w.syncAddPaths(paths...)
} else {
for _, path := range paths {
w.paths[path] = watchPath(path)
}
}
return
}
|
go
|
{
"resource": ""
}
|
q181419
|
Start
|
test
|
func (w *Watcher) Start() <-chan *Notification {
if w.notify_chan != nil {
return w.notify_chan
}
if w.auto_watch {
w.add_chan = make(chan *watchItem, NotificationBufLen)
go w.watchItemListener()
}
w.notify_chan = make(chan *Notification, NotificationBufLen)
go w.watch(w.notify_chan)
return w.notify_chan
}
|
go
|
{
"resource": ""
}
|
q181420
|
Stop
|
test
|
func (w *Watcher) Stop() {
if w.notify_chan != nil {
close(w.notify_chan)
}
if w.add_chan != nil {
close(w.add_chan)
}
}
|
go
|
{
"resource": ""
}
|
q181421
|
Active
|
test
|
func (w *Watcher) Active() bool {
return w.paths != nil && len(w.paths) > 0
}
|
go
|
{
"resource": ""
}
|
q181422
|
Add
|
test
|
func (w *Watcher) Add(inpaths ...string) {
var paths []string
for _, path := range inpaths {
matches, err := filepath.Glob(path)
if err != nil {
continue
}
paths = append(paths, matches...)
}
if w.auto_watch && w.notify_chan != nil {
for _, path := range paths {
wi := watchPath(path)
w.addPaths(wi)
}
} else if w.auto_watch {
w.syncAddPaths(paths...)
} else {
for _, path := range paths {
w.paths[path] = watchPath(path)
}
}
}
|
go
|
{
"resource": ""
}
|
q181423
|
watch
|
test
|
func (w *Watcher) watch(sndch chan<- *Notification) {
defer func() {
recover()
}()
for {
<-time.After(WatchDelay)
for _, wi := range w.paths {
if wi.Update() && w.shouldNotify(wi) {
sndch <- wi.Notification()
}
if wi.LastEvent == NOEXIST && w.auto_watch {
delete(w.paths, wi.Path)
}
if len(w.paths) == 0 {
w.Stop()
}
}
}
}
|
go
|
{
"resource": ""
}
|
q181424
|
Watching
|
test
|
func (w *Watcher) Watching() (paths []string) {
paths = make([]string, 0)
for path, _ := range w.paths {
paths = append(paths, path)
}
return
}
|
go
|
{
"resource": ""
}
|
q181425
|
State
|
test
|
func (w *Watcher) State() (state []Notification) {
state = make([]Notification, 0)
if w.paths == nil {
return
}
for _, wi := range w.paths {
state = append(state, *wi.Notification())
}
return
}
|
go
|
{
"resource": ""
}
|
q181426
|
Store
|
test
|
func Store(r *http.Request, err error) {
errptr, ok := r.Context().Value(errorKey).(*error)
if !ok {
panic("hatpear: request not configured to store errors")
}
// check err after checking context to fail fast if unconfigured
if err != nil {
*errptr = err
}
}
|
go
|
{
"resource": ""
}
|
q181427
|
Get
|
test
|
func Get(r *http.Request) error {
errptr, ok := r.Context().Value(errorKey).(*error)
if !ok {
return nil
}
return *errptr
}
|
go
|
{
"resource": ""
}
|
q181428
|
Catch
|
test
|
func Catch(h func(w http.ResponseWriter, r *http.Request, err error)) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var err error
ctx := context.WithValue(r.Context(), errorKey, &err)
next.ServeHTTP(w, r.WithContext(ctx))
if err != nil {
h(w, r, err)
}
})
}
}
|
go
|
{
"resource": ""
}
|
q181429
|
Try
|
test
|
func Try(h Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := h.ServeHTTP(w, r)
Store(r, err)
})
}
|
go
|
{
"resource": ""
}
|
q181430
|
Recover
|
test
|
func Recover() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
Store(r, PanicError{
value: v,
stack: stack(1),
})
}
}()
next.ServeHTTP(w, r)
})
}
}
|
go
|
{
"resource": ""
}
|
q181431
|
main
|
test
|
func main() {
req, _ := http.NewRequest("GET", "http://localhost:7070/sync", nil)
req.Header.Set("Accept", "text/event-stream")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("request: %s", err)
}
r := resp.Body
i := 0
buff := make([]byte, 32*1024)
for {
n, err := r.Read(buff)
if err != nil {
break
}
i++
log.Printf("#%d: %s", i, sizestr.ToString(int64(n)))
}
r.Close()
log.Printf("closed")
}
|
go
|
{
"resource": ""
}
|
q181432
|
SyncHandler
|
test
|
func SyncHandler(gostruct interface{}) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if conn, err := Sync(gostruct, w, r); err != nil {
log.Printf("[velox] sync handler error: %s", err)
} else {
conn.Wait()
}
})
}
|
go
|
{
"resource": ""
}
|
q181433
|
connect
|
test
|
func (c *conn) connect(w http.ResponseWriter, r *http.Request) error {
//choose transport
if r.Header.Get("Accept") == "text/event-stream" {
c.transport = &eventSourceTransport{writeTimeout: c.state.WriteTimeout}
} else if r.Header.Get("Upgrade") == "websocket" {
c.transport = &websocketsTransport{writeTimeout: c.state.WriteTimeout}
} else {
return fmt.Errorf("Invalid sync request")
}
//non-blocking connect to client over set transport
if err := c.transport.connect(w, r); err != nil {
return err
}
//initial ping
if err := c.send(&update{Ping: true}); err != nil {
return fmt.Errorf("Failed to send initial event")
}
//successfully connected
c.connected = true
c.waiter.Add(1)
//while connected, ping loop (every 25s, browser timesout after 30s)
go func() {
for {
select {
case <-time.After(c.state.PingInterval):
if err := c.send(&update{Ping: true}); err != nil {
goto disconnected
}
case <-c.connectedCh:
goto disconnected
}
}
disconnected:
c.connected = false
c.Close()
//unblock waiters
c.waiter.Done()
}()
//non-blocking wait on connection
go func() {
if err := c.transport.wait(); err != nil {
//log error?
}
close(c.connectedCh)
}()
//now connected, consumer can connection.Wait()
return nil
}
|
go
|
{
"resource": ""
}
|
q181434
|
send
|
test
|
func (c *conn) send(upd *update) error {
c.sendingMut.Lock()
defer c.sendingMut.Unlock()
//send (transports responsiblity to enforce timeouts)
return c.transport.send(upd)
}
|
go
|
{
"resource": ""
}
|
q181435
|
NumConnections
|
test
|
func (s *State) NumConnections() int {
s.connMut.Lock()
n := len(s.conns)
s.connMut.Unlock()
return n
}
|
go
|
{
"resource": ""
}
|
q181436
|
Push
|
test
|
func (s *State) Push() bool {
//attempt to mark state as 'pushing'
if atomic.CompareAndSwapUint32(&s.push.ing, 0, 1) {
go s.gopush()
return true
}
//if already pushing, mark queued
atomic.StoreUint32(&s.push.queued, 1)
return false
}
|
go
|
{
"resource": ""
}
|
q181437
|
gopush
|
test
|
func (s *State) gopush() {
s.push.mut.Lock()
t0 := time.Now()
//queue cleanup
defer func() {
//measure time passed, ensure we wait at least Throttle time
tdelta := time.Now().Sub(t0)
if t := s.Throttle - tdelta; t > 0 {
time.Sleep(t)
}
//push complete
s.push.mut.Unlock()
atomic.StoreUint32(&s.push.ing, 0)
//if queued, auto-push again
if atomic.CompareAndSwapUint32(&s.push.queued, 1, 0) {
s.Push()
}
}()
//calculate new json state
l, hasLock := s.gostruct.(sync.Locker)
if hasLock {
l.Lock()
}
newBytes, err := json.Marshal(s.gostruct)
if hasLock {
l.Unlock()
}
if err != nil {
log.Printf("velox: marshal failed: %s", err)
return
}
//if changed, then calculate change set
if !bytes.Equal(s.data.bytes, newBytes) {
//calculate change set from last version
ops, _ := jsonpatch.CreatePatch(s.data.bytes, newBytes)
if len(s.data.bytes) > 0 && len(ops) > 0 {
//changes! bump version
s.data.mut.Lock()
s.data.delta, _ = json.Marshal(ops)
s.data.bytes = newBytes
s.data.version++
s.data.mut.Unlock()
}
}
//send this new change to each subscriber
s.connMut.Lock()
for _, c := range s.conns {
if c.version != s.data.version {
go c.push()
}
}
s.connMut.Unlock()
//defered cleanup()
}
|
go
|
{
"resource": ""
}
|
q181438
|
NewOutForward
|
test
|
func NewOutForward(configServers []*ConfigServer) (*OutForward, error) {
loggers := make([]*fluent.Fluent, len(configServers))
for i, server := range configServers {
logger, err := fluent.New(fluent.Config{Server: server.Address()})
if err != nil {
log.Println("[warning]", err)
} else {
log.Println("[info] Server", server.Address(), "connected")
}
loggers[i] = logger
logger.Send([]byte{})
}
return &OutForward{
loggers: loggers,
sent: 0,
}, nil
}
|
go
|
{
"resource": ""
}
|
q181439
|
Run
|
test
|
func (t *InTail) Run(c *Context) {
c.InputProcess.Add(1)
defer c.InputProcess.Done()
t.messageCh = c.MessageCh
t.monitorCh = c.MonitorCh
c.StartProcess.Done()
if t.eventCh == nil {
err := t.TailStdin(c)
if err != nil {
if _, ok := err.(Signal); ok {
log.Println("[info]", err)
} else {
log.Println("[error]", err)
}
return
}
}
log.Println("[info] Trying trail file", t.filename)
f, err := t.newTrailFile(SEEK_TAIL, c)
if err != nil {
if _, ok := err.(Signal); ok {
log.Println("[info]", err)
} else {
log.Println("[error]", err)
}
return
}
for {
for {
err := t.watchFileEvent(f, c)
if err != nil {
if _, ok := err.(Signal); ok {
log.Println("[info]", err)
return
} else {
log.Println("[warning]", err)
break
}
}
}
// re open file
var err error
f, err = t.newTrailFile(SEEK_HEAD, c)
if err != nil {
if _, ok := err.(Signal); ok {
log.Println("[info]", err)
} else {
log.Println("[error]", err)
}
return
}
}
}
|
go
|
{
"resource": ""
}
|
q181440
|
New
|
test
|
func New(config Config) (f *Fluent, err error) {
if config.Server == "" {
config.Server = defaultServer
}
if config.Timeout == 0 {
config.Timeout = defaultTimeout
}
if config.RetryWait == 0 {
config.RetryWait = defaultRetryWait
}
if config.MaxRetry == 0 {
config.MaxRetry = defaultMaxRetry
}
f = &Fluent{
Config: config,
reconnecting: false,
cancelReconnect: make(chan bool),
}
err = f.connect()
return
}
|
go
|
{
"resource": ""
}
|
q181441
|
Close
|
test
|
func (f *Fluent) Close() (err error) {
if f.conn != nil {
f.mu.Lock()
defer f.mu.Unlock()
} else {
return
}
if f.conn != nil {
f.conn.Close()
f.conn = nil
}
return
}
|
go
|
{
"resource": ""
}
|
q181442
|
IsReconnecting
|
test
|
func (f *Fluent) IsReconnecting() bool {
f.mu.Lock()
defer f.mu.Unlock()
return f.reconnecting
}
|
go
|
{
"resource": ""
}
|
q181443
|
connect
|
test
|
func (f *Fluent) connect() (err error) {
host, port, err := net.SplitHostPort(f.Server)
if err != nil {
return err
}
addrs, err := net.LookupHost(host)
if err != nil || len(addrs) == 0 {
return err
}
// for DNS round robin
n := Rand.Intn(len(addrs))
addr := addrs[n]
var format string
if strings.Contains(addr, ":") {
// v6
format = "[%s]:%s"
} else {
// v4
format = "%s:%s"
}
resolved := fmt.Sprintf(format, addr, port)
log.Printf("[info] Connect to %s (%s)", f.Server, resolved)
f.conn, err = net.DialTimeout("tcp", resolved, f.Config.Timeout)
f.recordError(err)
return
}
|
go
|
{
"resource": ""
}
|
q181444
|
Notification
|
test
|
func Notification(title, message string) GNotifier {
config := &Config{title, message, 5000, ""}
n := ¬ifier{Config: config}
return n
}
|
go
|
{
"resource": ""
}
|
q181445
|
NullNotification
|
test
|
func NullNotification(title, message string) GNotifier {
config := &Config{title, message, 5000, ""}
n := &nullNotifier{Config: config}
return n
}
|
go
|
{
"resource": ""
}
|
q181446
|
New
|
test
|
func New(opts ...Option) *Identity {
c := &configuration{}
for _, opt := range opts {
option(opt)(c)
}
return c.generate()
}
|
go
|
{
"resource": ""
}
|
q181447
|
Issue
|
test
|
func (id *Identity) Issue(opts ...Option) *Identity {
opts = append(opts, Issuer(id))
return New(opts...)
}
|
go
|
{
"resource": ""
}
|
q181448
|
Subject
|
test
|
func Subject(value pkix.Name) Option {
return func(c *configuration) {
c.subject = &value
}
}
|
go
|
{
"resource": ""
}
|
q181449
|
PrivateKey
|
test
|
func PrivateKey(value crypto.Signer) Option {
return func(c *configuration) {
c.priv = &value
}
}
|
go
|
{
"resource": ""
}
|
q181450
|
NotBefore
|
test
|
func NotBefore(value time.Time) Option {
return func(c *configuration) {
c.notBefore = &value
}
}
|
go
|
{
"resource": ""
}
|
q181451
|
NotAfter
|
test
|
func NotAfter(value time.Time) Option {
return func(c *configuration) {
c.notAfter = &value
}
}
|
go
|
{
"resource": ""
}
|
q181452
|
IssuingCertificateURL
|
test
|
func IssuingCertificateURL(value ...string) Option {
return func(c *configuration) {
c.issuingCertificateURL = append(c.issuingCertificateURL, value...)
}
}
|
go
|
{
"resource": ""
}
|
q181453
|
OCSPServer
|
test
|
func OCSPServer(value ...string) Option {
return func(c *configuration) {
c.ocspServer = append(c.ocspServer, value...)
}
}
|
go
|
{
"resource": ""
}
|
q181454
|
New
|
test
|
func New(apiKey string) (*TelegramBotAPI, error) {
toReturn := TelegramBotAPI{
Updates: make(chan BotUpdate),
baseURIs: createEndpoints(fmt.Sprintf(apiBaseURI, apiKey)),
closed: make(chan struct{}),
c: newClient(fmt.Sprintf(apiBaseURI, apiKey)),
updateC: newClient(fmt.Sprintf(apiBaseURI, apiKey)),
}
user, err := toReturn.GetMe()
if err != nil {
return nil, err
}
toReturn.ID = user.User.ID
toReturn.Name = user.User.FirstName
toReturn.Username = *user.User.Username
err = toReturn.removeWebhook()
if err != nil {
return nil, err
}
toReturn.wg.Add(1)
go toReturn.updateLoop()
return &toReturn, nil
}
|
go
|
{
"resource": ""
}
|
q181455
|
NewWithWebhook
|
test
|
func NewWithWebhook(apiKey, webhookURL, certificate string) (*TelegramBotAPI, http.HandlerFunc, error) {
toReturn := TelegramBotAPI{
Updates: make(chan BotUpdate),
baseURIs: createEndpoints(fmt.Sprintf(apiBaseURI, apiKey)),
closed: make(chan struct{}),
c: newClient(fmt.Sprintf(apiBaseURI, apiKey)),
updateC: newClient(fmt.Sprintf(apiBaseURI, apiKey)),
}
user, err := toReturn.GetMe()
if err != nil {
return nil, nil, err
}
toReturn.ID = user.User.ID
toReturn.Name = user.User.FirstName
toReturn.Username = *user.User.Username
file, err := os.Open(certificate)
if err != nil {
return nil, nil, err
}
err = toReturn.setWebhook(webhookURL, certificate, file)
if err != nil {
return nil, nil, err
}
updateFunc := func(w http.ResponseWriter, r *http.Request) {
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
toReturn.Updates <- BotUpdate{err: err}
return
}
update := &Update{}
err = json.Unmarshal(bytes, update)
if err != nil {
toReturn.Updates <- BotUpdate{err: err}
return
}
toReturn.Updates <- BotUpdate{update: *update}
}
return &toReturn, updateFunc, nil
}
|
go
|
{
"resource": ""
}
|
q181456
|
Close
|
test
|
func (api *TelegramBotAPI) Close() {
select {
case <-api.closed:
return
default:
}
close(api.closed)
api.wg.Wait()
}
|
go
|
{
"resource": ""
}
|
q181457
|
GetMe
|
test
|
func (api *TelegramBotAPI) GetMe() (*UserResponse, error) {
resp := &UserResponse{}
_, err := api.c.get(getMe, resp)
if err != nil {
return nil, err
}
err = check(&resp.baseResponse)
if err != nil {
return nil, err
}
return resp, nil
}
|
go
|
{
"resource": ""
}
|
q181458
|
RunBot
|
test
|
func RunBot(apiKey string, bot BotFunc, name, description string) {
closing := make(chan struct{})
fmt.Printf("%s: %s\n", name, description)
fmt.Println("Starting...")
api, err := tbotapi.New(apiKey)
if err != nil {
log.Fatal(err)
}
// Just to show its working.
fmt.Printf("User ID: %d\n", api.ID)
fmt.Printf("Bot Name: %s\n", api.Name)
fmt.Printf("Bot Username: %s\n", api.Username)
closed := make(chan struct{})
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-closed:
return
case update := <-api.Updates:
if update.Error() != nil {
// TODO handle this properly
fmt.Printf("Update error: %s\n", update.Error())
continue
}
bot(update.Update(), api)
}
}
}()
// Ensure a clean shutdown.
shutdown := make(chan os.Signal)
signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-shutdown
close(closing)
}()
fmt.Println("Bot started. Press CTRL-C to close...")
// Wait for the signal.
<-closing
fmt.Println("Closing...")
// Always close the API first, let it clean up the update loop.
// This might take a while.
api.Close()
close(closed)
wg.Wait()
}
|
go
|
{
"resource": ""
}
|
q181459
|
RunBotOnWebhook
|
test
|
func RunBotOnWebhook(apiKey string, bot BotFunc, name, description, webhookHost string, webhookPort uint16, pubkey, privkey string) {
closing := make(chan struct{})
fmt.Printf("%s: %s\n", name, description)
fmt.Println("Starting...")
u := url.URL{
Host: webhookHost + ":" + fmt.Sprint(webhookPort),
Scheme: "https",
Path: apiKey,
}
api, handler, err := tbotapi.NewWithWebhook(apiKey, u.String(), pubkey)
if err != nil {
log.Fatal(err)
}
// Just to show its working.
fmt.Printf("User ID: %d\n", api.ID)
fmt.Printf("Bot Name: %s\n", api.Name)
fmt.Printf("Bot Username: %s\n", api.Username)
closed := make(chan struct{})
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-closed:
return
case update := <-api.Updates:
if update.Error() != nil {
// TODO handle this properly
fmt.Printf("Update error: %s\n", update.Error())
continue
}
bot(update.Update(), api)
}
}
}()
http.HandleFunc("/"+apiKey, handler)
fmt.Println("Starting webhook...")
go func() {
log.Fatal(http.ListenAndServeTLS("0.0.0.0:"+fmt.Sprint(webhookPort), pubkey, privkey, nil))
}()
// Ensure a clean shutdown.
shutdown := make(chan os.Signal)
signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-shutdown
close(closing)
}()
fmt.Println("Bot started. Press CTRL-C to close...")
// Wait for the signal.
<-closing
fmt.Println("Closing...")
// Always close the API first.
api.Close()
close(closed)
wg.Wait()
}
|
go
|
{
"resource": ""
}
|
q181460
|
NewOutgoingMessage
|
test
|
func (api *TelegramBotAPI) NewOutgoingMessage(recipient Recipient, text string) *OutgoingMessage {
return &OutgoingMessage{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
Text: text,
ParseMode: ModeDefault,
}
}
|
go
|
{
"resource": ""
}
|
q181461
|
NewOutgoingLocation
|
test
|
func (api *TelegramBotAPI) NewOutgoingLocation(recipient Recipient, latitude, longitude float32) *OutgoingLocation {
return &OutgoingLocation{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
Latitude: latitude,
Longitude: longitude,
}
}
|
go
|
{
"resource": ""
}
|
q181462
|
NewOutgoingVenue
|
test
|
func (api *TelegramBotAPI) NewOutgoingVenue(recipient Recipient, latitude, longitude float32, title, address string) *OutgoingVenue {
return &OutgoingVenue{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
Latitude: latitude,
Longitude: longitude,
Title: title,
Address: address,
}
}
|
go
|
{
"resource": ""
}
|
q181463
|
NewOutgoingVideo
|
test
|
func (api *TelegramBotAPI) NewOutgoingVideo(recipient Recipient, fileName string, reader io.Reader) *OutgoingVideo {
return &OutgoingVideo{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileName: fileName,
r: reader,
},
}
}
|
go
|
{
"resource": ""
}
|
q181464
|
NewOutgoingVideoResend
|
test
|
func (api *TelegramBotAPI) NewOutgoingVideoResend(recipient Recipient, fileID string) *OutgoingVideo {
return &OutgoingVideo{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileID: fileID,
},
}
}
|
go
|
{
"resource": ""
}
|
q181465
|
NewOutgoingPhoto
|
test
|
func (api *TelegramBotAPI) NewOutgoingPhoto(recipient Recipient, fileName string, reader io.Reader) *OutgoingPhoto {
return &OutgoingPhoto{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileName: fileName,
r: reader,
},
}
}
|
go
|
{
"resource": ""
}
|
q181466
|
NewOutgoingPhotoResend
|
test
|
func (api *TelegramBotAPI) NewOutgoingPhotoResend(recipient Recipient, fileID string) *OutgoingPhoto {
return &OutgoingPhoto{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileID: fileID,
},
}
}
|
go
|
{
"resource": ""
}
|
q181467
|
NewOutgoingSticker
|
test
|
func (api *TelegramBotAPI) NewOutgoingSticker(recipient Recipient, fileName string, reader io.Reader) *OutgoingSticker {
return &OutgoingSticker{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileName: fileName,
r: reader,
},
}
}
|
go
|
{
"resource": ""
}
|
q181468
|
NewOutgoingStickerResend
|
test
|
func (api *TelegramBotAPI) NewOutgoingStickerResend(recipient Recipient, fileID string) *OutgoingSticker {
return &OutgoingSticker{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileID: fileID,
},
}
}
|
go
|
{
"resource": ""
}
|
q181469
|
NewOutgoingVoice
|
test
|
func (api *TelegramBotAPI) NewOutgoingVoice(recipient Recipient, fileName string, reader io.Reader) *OutgoingVoice {
return &OutgoingVoice{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileName: fileName,
r: reader,
},
}
}
|
go
|
{
"resource": ""
}
|
q181470
|
NewOutgoingVoiceResend
|
test
|
func (api *TelegramBotAPI) NewOutgoingVoiceResend(recipient Recipient, fileID string) *OutgoingVoice {
return &OutgoingVoice{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileID: fileID,
},
}
}
|
go
|
{
"resource": ""
}
|
q181471
|
NewOutgoingAudio
|
test
|
func (api *TelegramBotAPI) NewOutgoingAudio(recipient Recipient, fileName string, reader io.Reader) *OutgoingAudio {
return &OutgoingAudio{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileName: fileName,
r: reader,
},
}
}
|
go
|
{
"resource": ""
}
|
q181472
|
NewOutgoingAudioResend
|
test
|
func (api *TelegramBotAPI) NewOutgoingAudioResend(recipient Recipient, fileID string) *OutgoingAudio {
return &OutgoingAudio{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileID: fileID,
},
}
}
|
go
|
{
"resource": ""
}
|
q181473
|
NewOutgoingDocument
|
test
|
func (api *TelegramBotAPI) NewOutgoingDocument(recipient Recipient, fileName string, reader io.Reader) *OutgoingDocument {
return &OutgoingDocument{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileName: fileName,
r: reader,
},
}
}
|
go
|
{
"resource": ""
}
|
q181474
|
NewOutgoingDocumentResend
|
test
|
func (api *TelegramBotAPI) NewOutgoingDocumentResend(recipient Recipient, fileID string) *OutgoingDocument {
return &OutgoingDocument{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileID: fileID,
},
}
}
|
go
|
{
"resource": ""
}
|
q181475
|
NewOutgoingForward
|
test
|
func (api *TelegramBotAPI) NewOutgoingForward(recipient Recipient, origin Chat, messageID int) *OutgoingForward {
return &OutgoingForward{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
FromChatID: NewRecipientFromChat(origin),
MessageID: messageID,
}
}
|
go
|
{
"resource": ""
}
|
q181476
|
NewOutgoingChatAction
|
test
|
func (api *TelegramBotAPI) NewOutgoingChatAction(recipient Recipient, action ChatAction) *OutgoingChatAction {
return &OutgoingChatAction{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
Action: action,
}
}
|
go
|
{
"resource": ""
}
|
q181477
|
NewOutgoingUserProfilePhotosRequest
|
test
|
func (api *TelegramBotAPI) NewOutgoingUserProfilePhotosRequest(userID int) *OutgoingUserProfilePhotosRequest {
return &OutgoingUserProfilePhotosRequest{
api: api,
UserID: userID,
}
}
|
go
|
{
"resource": ""
}
|
q181478
|
NewOutgoingKickChatMember
|
test
|
func (api *TelegramBotAPI) NewOutgoingKickChatMember(chat Recipient, userID int) *OutgoingKickChatMember {
return &OutgoingKickChatMember{
api: api,
Recipient: chat,
UserID: userID,
}
}
|
go
|
{
"resource": ""
}
|
q181479
|
NewOutgoingUnbanChatMember
|
test
|
func (api *TelegramBotAPI) NewOutgoingUnbanChatMember(chat Recipient, userID int) *OutgoingUnbanChatMember {
return &OutgoingUnbanChatMember{
api: api,
Recipient: chat,
UserID: userID,
}
}
|
go
|
{
"resource": ""
}
|
q181480
|
NewOutgoingCallbackQueryResponse
|
test
|
func (api *TelegramBotAPI) NewOutgoingCallbackQueryResponse(queryID string) *OutgoingCallbackQueryResponse {
return &OutgoingCallbackQueryResponse{
api: api,
CallbackQueryID: queryID,
}
}
|
go
|
{
"resource": ""
}
|
q181481
|
NewInlineQueryAnswer
|
test
|
func (api *TelegramBotAPI) NewInlineQueryAnswer(queryID string, results []InlineQueryResult) *InlineQueryAnswer {
return &InlineQueryAnswer{
api: api,
QueryID: queryID,
Results: results,
}
}
|
go
|
{
"resource": ""
}
|
q181482
|
Type
|
test
|
func (m *Message) Type() MessageType {
if m.Text != nil {
return TextMessage
} else if m.Audio != nil {
return AudioMessage
} else if m.Document != nil {
return DocumentMessage
} else if m.Photo != nil {
return PhotoMessage
} else if m.Sticker != nil {
return StickerMessage
} else if m.Video != nil {
return VideoMessage
} else if m.Voice != nil {
return VoiceMessage
} else if m.Contact != nil {
return ContactMessage
} else if m.Location != nil {
return LocationMessage
} else if m.NewChatMember != nil {
return NewChatMember
} else if m.LeftChatMember != nil {
return LeftChatMember
} else if m.NewChatTitle != nil {
return NewChatTitle
} else if m.NewChatPhoto != nil {
return NewChatPhoto
} else if m.DeleteChatPhoto {
return DeletedChatPhoto
} else if m.GroupChatCreated {
return GroupChatCreated
} else if m.SupergroupChatCreated {
return SupergroupChatCreated
} else if m.ChannelChatCreated {
return ChannelChatCreated
} else if m.MigrateToChatID != nil {
return MigrationToSupergroup
} else if m.MigrateFromChatID != nil {
return MigrationFromGroup
} else if m.Venue != nil {
return VenueMessage
} else if m.PinnedMessage != nil {
return PinnedMessage
}
return UnknownMessage
}
|
go
|
{
"resource": ""
}
|
q181483
|
Type
|
test
|
func (u *Update) Type() UpdateType {
if u.Message != nil {
return MessageUpdate
} else if u.InlineQuery != nil {
return InlineQueryUpdate
} else if u.ChosenInlineResult != nil {
return ChosenInlineResultUpdate
}
return UnknownUpdate
}
|
go
|
{
"resource": ""
}
|
q181484
|
MarshalJSON
|
test
|
func (r Recipient) MarshalJSON() ([]byte, error) {
toReturn := ""
if r.isChannel() {
toReturn = fmt.Sprintf("\"%s\"", *r.ChannelID)
} else {
toReturn = fmt.Sprintf("%d", *r.ChatID)
}
return []byte(toReturn), nil
}
|
go
|
{
"resource": ""
}
|
q181485
|
querystring
|
test
|
func (ow *outgoingSetWebhook) querystring() querystring {
toReturn := make(map[string]string)
if ow.URL != "" {
toReturn["url"] = ow.URL
}
return querystring(toReturn)
}
|
go
|
{
"resource": ""
}
|
q181486
|
getBaseQueryString
|
test
|
func (op *outgoingBase) getBaseQueryString() querystring {
toReturn := map[string]string{}
if op.Recipient.isChannel() {
//Channel
toReturn["chat_id"] = fmt.Sprint(*op.Recipient.ChannelID)
} else {
toReturn["chat_id"] = fmt.Sprint(*op.Recipient.ChatID)
}
return querystring(toReturn)
}
|
go
|
{
"resource": ""
}
|
q181487
|
getBaseQueryString
|
test
|
func (op *outgoingMessageBase) getBaseQueryString() querystring {
toReturn := map[string]string{}
if op.Recipient.isChannel() {
//Channel.
toReturn["chat_id"] = fmt.Sprint(*op.Recipient.ChannelID)
} else {
toReturn["chat_id"] = fmt.Sprint(*op.Recipient.ChatID)
}
if op.replyToMessageIDSet {
toReturn["reply_to_message_id"] = fmt.Sprint(op.ReplyToMessageID)
}
if op.replyMarkupSet {
b, err := json.Marshal(op.ReplyMarkup)
if err != nil {
panic(err)
}
toReturn["reply_markup"] = string(b)
}
if op.DisableNotification {
toReturn["disable_notification"] = fmt.Sprint(op.DisableNotification)
}
return querystring(toReturn)
}
|
go
|
{
"resource": ""
}
|
q181488
|
querystring
|
test
|
func (oa *OutgoingAudio) querystring() querystring {
toReturn := map[string]string(oa.getBaseQueryString())
if oa.Duration != 0 {
toReturn["duration"] = fmt.Sprint(oa.Duration)
}
if oa.Performer != "" {
toReturn["performer"] = oa.Performer
}
if oa.Title != "" {
toReturn["title"] = oa.Title
}
return querystring(toReturn)
}
|
go
|
{
"resource": ""
}
|
q181489
|
querystring
|
test
|
func (op *OutgoingPhoto) querystring() querystring {
toReturn := map[string]string(op.getBaseQueryString())
if op.Caption != "" {
toReturn["caption"] = op.Caption
}
return querystring(toReturn)
}
|
go
|
{
"resource": ""
}
|
q181490
|
querystring
|
test
|
func (op *OutgoingUserProfilePhotosRequest) querystring() querystring {
toReturn := map[string]string{}
toReturn["user_id"] = fmt.Sprint(op.UserID)
if op.Offset != 0 {
toReturn["offset"] = fmt.Sprint(op.Offset)
}
if op.Limit != 0 {
toReturn["limit"] = fmt.Sprint(op.Limit)
}
return querystring(toReturn)
}
|
go
|
{
"resource": ""
}
|
q181491
|
querystring
|
test
|
func (ov *OutgoingVideo) querystring() querystring {
toReturn := map[string]string(ov.getBaseQueryString())
if ov.Caption != "" {
toReturn["caption"] = ov.Caption
}
if ov.Duration != 0 {
toReturn["duration"] = fmt.Sprint(ov.Duration)
}
return querystring(toReturn)
}
|
go
|
{
"resource": ""
}
|
q181492
|
querystring
|
test
|
func (ov *OutgoingVoice) querystring() querystring {
toReturn := map[string]string(ov.getBaseQueryString())
if ov.Duration != 0 {
toReturn["duration"] = fmt.Sprint(ov.Duration)
}
return querystring(toReturn)
}
|
go
|
{
"resource": ""
}
|
q181493
|
NewInlineQueryResultArticle
|
test
|
func NewInlineQueryResultArticle(id, title, text string) *InlineQueryResultArticle {
return &InlineQueryResultArticle{
InlineQueryResultBase: InlineQueryResultBase{
Type: ArticleResult,
ID: id,
},
Title: title,
Text: text,
}
}
|
go
|
{
"resource": ""
}
|
q181494
|
NewInlineQueryResultPhoto
|
test
|
func NewInlineQueryResultPhoto(id, photoURL, thumbURL string) *InlineQueryResultPhoto {
return &InlineQueryResultPhoto{
InlineQueryResultBase: InlineQueryResultBase{
Type: PhotoResult,
ID: id,
},
PhotoURL: photoURL,
ThumbURL: thumbURL,
}
}
|
go
|
{
"resource": ""
}
|
q181495
|
NewInlineQueryResultGif
|
test
|
func NewInlineQueryResultGif(id, gifURL, thumbURL string) *InlineQueryResultGif {
return &InlineQueryResultGif{
InlineQueryResultBase: InlineQueryResultBase{
Type: GifResult,
ID: id,
},
GifURL: gifURL,
ThumbURL: thumbURL,
}
}
|
go
|
{
"resource": ""
}
|
q181496
|
NewInlineQueryResultMpeg4Gif
|
test
|
func NewInlineQueryResultMpeg4Gif(id, mpeg4URL, thumbURL string) *InlineQueryResultMpeg4Gif {
return &InlineQueryResultMpeg4Gif{
InlineQueryResultBase: InlineQueryResultBase{
Type: PhotoResult,
ID: id,
},
Mpeg4URL: mpeg4URL,
ThumbURL: thumbURL,
}
}
|
go
|
{
"resource": ""
}
|
q181497
|
NewInlineQueryResultVideo
|
test
|
func NewInlineQueryResultVideo(id, videoURL, thumbURL, title, text string, mimeType MIMEType) *InlineQueryResultVideo {
return &InlineQueryResultVideo{
InlineQueryResultBase: InlineQueryResultBase{
Type: PhotoResult,
ID: id,
},
VideoURL: videoURL,
MIMEType: mimeType,
ThumbURL: thumbURL,
Title: title,
Text: text,
}
}
|
go
|
{
"resource": ""
}
|
q181498
|
Send
|
test
|
func (op *OutgoingUserProfilePhotosRequest) Send() (*UserProfilePhotosResponse, error) {
resp := &UserProfilePhotosResponse{}
_, err := op.api.c.postJSON(getUserProfilePhotos, resp, op)
if err != nil {
return nil, err
}
err = check(&resp.baseResponse)
if err != nil {
return nil, err
}
return resp, nil
}
|
go
|
{
"resource": ""
}
|
q181499
|
Send
|
test
|
func (oc *OutgoingChatAction) Send() error {
resp := &baseResponse{}
_, err := oc.api.c.postJSON(sendChatAction, resp, oc)
if err != nil {
return err
}
return check(resp)
}
|
go
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.