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"])
}
rows, err := conn.Queryx("SELECT id, name FROM users")
if err != nil {
log.Fatalln(err)
}
defer rows.Close()
users := []User{}
for rows.Next() {
if rows.StructScan(&user) != nil {
log.Fatalln(err)
}
users = append(users, user)
}
ctx.HTML(http.StatusOK, "users/index.tmpl", gin.H{"values": users})
go func(idx int) {
...
}(i)
package main
import (
"sync"
)
const N = 10
func main() {
m := make(map[int]int)
wg := &sync.WaitGroup{}
mu := &sync.Mutex{}
wg.Add(N)
for i := 0; i < N; i++ {
k := 5
go func(idx int) {
defer wg.Done()
mu.Lock()
println(idx, k)
m[idx] = k
mu.Unlock()
}(i)
}
wg.Wait()
println(len(m))
println(m[0])
}
package main
import "log"
func f() {
defer func() {
if r := recover(); r != nil {
log.Printf("recover:%#v", r)
}
}()
log.Println("Start first panic")
panic(1)
log.Println("After first panic")
panic(2)
log.Println("After second panic")
}
func main() {
f()
log.Println("After f()")
}
2020/07/20 23:14:07 Start first panic
2020/07/20 23:14:07 recover:1
2020/07/20 23:14:07 After f()
func InitEfaceType() interface{} {
var s *S
return s
}
...
fmt.Println(InitEfaceType() == (*S)(nil))
for i, a := range t.array
в `a` - создаётся копия value.type Test struct {
array []*Array
}