go test -v ./driver_test.go ./driver.go
go test -v -run ^Test_Deposit$
var c *client.Client
mbox, err := c.Select("INBOX", false)
if err != nil {
log.Fatal(err)
}
if mbox.Messages == 0 {
log.Fatal("No message in mailbox")
}
seqset := new(imap.SeqSet)
for _, message := range mbox.Messages {
// если сообщение должно быть удалено - тогда вызываете AddNum
// используем именно message.Uid а не message.SeqNum потому, что ниже мы будем вызывать UidStore, а не Store, так будет явно надёжнее
seqset.AddNum(message.Uid)
}
// отмечаем сообщения как удалённые
item := imap.FormatFlagsOp(imap.AddFlags, true)
flags := []interface{}{imap.DeletedFlag}
if err := c.UidStore(seqset, item, flags, nil); err != nil {
log.Fatal(err)
}
// удаляем сообщение
if err := c.Expunge(nil); err != nil {
log.Fatal(err)
}
log.Println("Last message has been deleted")
var dateStart = time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 9, 0, 0, 0, time.UTC)
var dateEnd = time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 17, 0, 0, 0, time.UTC)
if dateStart.Before(time.Now().UTC() ){
println("star ok")
}
if dateEnd.After(time.Now().UTC()) {
println("end ok")
}
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"os/exec"
)
type Executor struct {
wr io.Writer
}
func (e *Executor) SetStdout(w io.Writer) {
e.wr = w
}
func (e *Executor) Exec() error {
cmd := exec.Command("ls", "/etc")
cmd.Stdout = e.wr
err := cmd.Run()
return err
}
type BufferedBrokerWriter struct {
buffer bytes.Buffer
scanner *bufio.Scanner
}
func NewBufferedBrokerWriter() *BufferedBrokerWriter {
bw := &BufferedBrokerWriter{}
bw.scanner = bufio.NewScanner(&bw.buffer)
return bw
}
func (bw *BufferedBrokerWriter) Write(p []byte) (int, error) {
return bw.buffer.Write(p)
}
func (bw *BufferedBrokerWriter) ReadLines(cnt uint) ([]string, error) {
lines := make([]string, 0, cnt)
linesCnt := uint(0)
for bw.scanner.Scan() {
line := bw.scanner.Text()
err := bw.scanner.Err()
if err != nil || line == `` {
return lines, err
}
lines = append(lines, line)
linesCnt++
if linesCnt >= cnt {
return lines, nil
}
}
return nil, io.EOF
}
func main() {
// подключаетесь к вашему брокеру сообщений,
bw := NewBufferedBrokerWriter()
e := &Executor{}
e.SetStdout(bw)
err := e.Exec()
if err != nil {
log.Fatal(err)
}
for {
lines, err := bw.ReadLines(2)
if err == io.EOF {
break
}
fmt.Printf("Lines:\n%+v\n\n", lines)
}
}
package main
import (
"fmt"
"reflect"
)
func modify(input *[]int, newLen int) {
val := reflect.Indirect(reflect.ValueOf(input))
val.SetLen(newLen)
}
func main() {
input := []int{1, 2, 3}
fmt.Printf("Before: %p, value: %v\n", &input, input)
modify(&input, len(input) - 1)
fmt.Printf("After: %p, value: %v\n", &input, input)
}
Before: 0xc00000c060, value: [1 2 3]
After: 0xc00000c060, value: [1 2]
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
}
type LoginResponse struct {
Response
Token string
}
response := LoginResponse{
Response : Response {
Code: 10,
Message: `error / success message`,
},
Token: `token`,
}
package main
import (
"log"
"time"
)
func add(ch chan<- string) {
for {
time.Sleep(time.Second * 2)
ch <- "hi"
}
}
func exit(ch chan<- string) {
time.Sleep(time.Second * 5)
ch <- "close"
}
func main() {
ch := make(chan string, 1000)
go add(ch)
go exit(ch)
LOOP:
for {
select {
case val := <- ch:
switch val {
case "close":
log.Println("Close")
break LOOP
case "hi":
log.Println("Hi")
}
default:
log.Println("Default")
time.Sleep(time.Second * 1)
}
}
}
func NewPostFromIncomingPost(incomingPost map[string]string) (*Post, error) {
post := &Post{}
if title, exists := incomingPost[`name`]; exists {
post.Title = title
} else if title, exists := incomingPost[`title`]; exists {
post.Title = title
} else {
return nil, errors.New(`title not found`)
}
if text, exists := incomingPost[`text`]; exists {
post.Text = text
} else if text, exists := incomingPost[`description`]; exists {
post.Text = text
} else {
return nil, errors.New(`text not found`)
}
return post, nil
}
package main
import (
"encoding/json"
"fmt"
"errors"
)
type Post struct {
Title string
Text string
}
func NewPostFromIncomingPost(incomingPost map[string]string) (*Post, error) {
post := &Post{}
if title, exists := incomingPost[`name`]; exists {
post.Title = title
} else if title, exists := incomingPost[`title`]; exists {
post.Title = title
} else {
return nil, errors.New(`title not found`)
}
if text, exists := incomingPost[`text`]; exists {
post.Text = text
} else if text, exists := incomingPost[`description`]; exists {
post.Text = text
} else {
return nil, errors.New(`text not found`)
}
return post, nil
}
func main() {
jsonSource1 := []byte(`{"title": "Title", "text": "Text"}`)
jsonSource2 := []byte(`{"name": "Title", "description": "Text"}`)
var incomingPost1 map[string]string
if err := json.Unmarshal(jsonSource1, &incomingPost1); err != nil {
panic(err)
}
post1, err := NewPostFromIncomingPost(incomingPost1)
fmt.Printf("post1: %+v\nerr: %+v\n\n", post1, err)
var incomingPost2 map[string]string
if err := json.Unmarshal(jsonSource2, &incomingPost2); err != nil {
panic(err)
}
post2, err := NewPostFromIncomingPost(incomingPost2)
fmt.Printf("post2: %+v\nerr: %+v\n\n", post2, err)
}
log.Printf("entity: %+v\n", entity.Header)
log.Printf("entity: %+v\n", entity.Header.Get("From"))
log.Printf("entity: %+v\n", entity.Header.Values("To"))
ffmpeg file1.mp3 file2.mp3 silence1sec.mp3 silence1sec.mp3 output.mp3
package main
import (
"io"
"io/ioutil"
"log"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/client"
"github.com/emersion/go-message"
)
func main() {
log.Println("Connecting to server...")
c, err := client.DialTLS("xxxxxxxxx", nil)
if err != nil {
log.Fatal(err)
}
log.Println("Connected")
defer c.Logout()
if err := c.Login("xxxxxxxxxxxxx", "xxxxxxxxxx"); err != nil {
log.Fatal(err)
}
log.Println("Logged in")
mbox, err := c.Select("INBOX", false)
if err != nil {
log.Fatal(err)
}
seqset := new(imap.SeqSet)
seqset.AddRange(1, mbox.Messages)
messages := make(chan *imap.Message, 10)
done := make(chan error, 1)
go func() {
done <- c.Fetch(seqset, []imap.FetchItem{imap.FetchRFC822}, messages)
}()
for msg := range messages {
for _, r := range msg.Body {
entity, err := message.Read(r)
if err != nil {
log.Fatal(err)
}
multiPartReader := entity.MultipartReader()
for e, err := multiPartReader.NextPart(); err != io.EOF; e, err = multiPartReader.NextPart() {
kind, params, cErr := e.Header.ContentType()
if cErr != nil {
log.Fatal(cErr)
}
if kind != "image/png" && kind != "image/gif" {
continue
}
c, rErr := ioutil.ReadAll(e.Body)
if rErr != nil {
log.Fatal(rErr)
}
log.Printf("Dump file %s", params["name"])
if fErr := ioutil.WriteFile("/tmp/"+params["name"], c, 0777); ferr != nil {
log.Fatal(fErr)
}
}
}
}
if err := <-done; err != nil {
log.Fatal(err)
}
log.Println("Done")
}
package main
import (
"fmt"
"strings"
)
func main() {
url := `https://site.com/regLink?$2a$10$/VTT.GtRslGWLhZL5d`
result := strings.SplitN(url, `?`, 2)
fmt.Printf("token: %s\n", result[1])
}
package main
import "fmt"
func main() {
var myLink = `https://site.com/Link?`
var tokenString = string(`hash....`)
var dataRespon = fmt.Sprintf(`Данные сохранены. Нажмите <a href="%s%s">ссылку</a>.`, myLink, tokenString)
fmt.Printf(dataRespon)
}
server {
listen *:80;
server_name тут_ваш_домен;
location / {
proxy_pass http://тут_ip_вашего_сервиса:1234;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
}
}
./main &
- тогда при завершении ssh сессии отвалится и сам демон.nohup ./main > error.log 2>&1 &
[Unit]
Description=YourServie
After=network.target
After=syslog.target
[Service]
User=nobody # user ID под которым должен работать ваш демон
Group=nobody
Type=simple
WorkingDirectory=/opt/yourservice
ExecStart=/opt/yourservice/yourservice >> /var/log/yourservice.log 2>&1
Restart=always
[Install]
WantedBy=multi-user.target
package localization
var L = map[string]string{
"start_message": "Привет. Я - Бот",
}
package main
import (
"fmt"
local "./localization"
)
func main() {
fmt.Printf(local.L["start_message"])
}