package main
import (
"encoding/json"
"fmt"
"log"
)
type Params struct {
NativeId string `json:"nativeId"`
Source string `json:"source"`
Url string `json:"url"`
Title string `json:"title"`
Price string `json:"price"`
}
func main() {
jsonDataBytes := []byte(`{
"test_2407811386": {"nativeId":"2407811386","source":"test","url":"https://test.ru/123","title":"TEST»","price":"123"},
"test_2415474304": {"nativeId":"2415474304","source":"test","url":"https://test/234","title":"TEST2»","price":"234"}
}`)
objects := map[string]Params{}
err := json.Unmarshal(jsonDataBytes, &objects)
if err != nil {
log.Fatalf("unmarshal error: %s\n", err.Error())
}
fmt.Printf("%v\n", objects)
}
func someFunc(numbers NumberInterface) {
numbers.Sum()
}
formData := url.Values{}
formData.Set("user_forms[0][name]", authDate.fName)
...
resp, err := http.PostForm(postUrl, formData)
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "hello\n")
}
func main() {
http.HandleFunc("/hello", helloHandler)
http.ListenAndServe(":8081", nil)
}
const req = new XMLHttpRequest();
const url='http://127.0.0.1:8081/hello';
req.open("GET", url);
req.send();
req.onreadystatechange=(e)=>{
console.log(req.responseText)
}
someFunc1(players)
someFunc2(players)
someFunc3(players)
func main() {
var players[] *Player
players = append(players, &Player{Id: 1, Name: "Bob"})
...
players = append(players, &Player{Id: 100, Name: "Bob"})
for i := range players {
someFunc1(players[i])
someFunc2(players[i])
someFunc3(players[i])
someFunc4(players[i])
// или одна из someFunc вызывает еще какие то функции и передаёт players туда
}
}
package pkg2
import "fmt"
type Pkg2 struct {
str2 []string
}
func New() *Pkg2 {
return &Pkg2{
str2: []string{},
}
}
func (p *Pkg2) Test(str string){
p.str2 = append(p.str2, str)
fmt.Printf("str:%v %v \n", str, p.str2)
}
package main
import (
"sync"
"pkg2"
)
var wg sync.WaitGroup
func main() {
text:=[]string{"a1", "a2", "a3", "a4", "a5"}
for i,str:=range text{
wg.Add(1)
p := pkg2.New()
go start(str, p)
}
wg.Wait()
}
func start(str string, p *pkg2.Pkg2){
p.Test(str)
wg.Done()
}
package main
import (
"log"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
func main() {
bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
if err != nil {
log.Panic(err)
}
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates := bot.GetUpdatesChan(u)
for update := range updates {
if update.Message == nil { // не обрабатываем если нет сообщения
continue
}
// ID сообщения, int
log.Printf("message id: %s\n", update.Message.MessageID)
// так вы можете получить текст сообщения полный (тип string)
log.Printf("message: %s\n", update.Message.Text)
if update.Message.IsCommand() {
// так вы получаете команду
log.Printf("command: %s\n", update.Message.Command())
// так вы получаете аргументы (параметры) команды, string
log.Printf("command: %s\n", update.Message.CommandArguments())
}
}
}
}
package main
import (
"fmt"
"runtime"
"sync"
)
var wg sync.WaitGroup
func main() {
runtime.GOMAXPROCS(8)
arr := []int{1343434, 1343434300, 234343400, 334343434000, 400434340, 203434340, 4232, 23545, 15535, 353535, 33434434, 5334345, 3533434345, 3535}
for idx, el := range arr {
wg.Add(1)
go test(el, idx)
}
wg.Wait()
}
func test(el int, idx int) {
fmt.Printf("%d started: %d\n", idx, el)
for i := 0; i < el; i++ {
el = el - 1
}
fmt.Printf("%d completed: %d\n", idx, el)
defer wg.Done()
}
4 started: 400434340
8 started: 15535
8 completed: 7767
13 started: 3535
13 completed: 1767
6 started: 4232
6 completed: 2116
10 started: 33434434
3 started: 334343434000
7 started: 23545
7 completed: 11772
5 started: 203434340
12 started: 3533434345
11 started: 5334345
2 started: 234343400
1 started: 1343434300
11 completed: 2667172
9 started: 353535
9 completed: 176767
0 started: 1343434
0 completed: 671717
10 completed: 16717217
5 completed: 101717170
4 completed: 200217170
2 completed: 117171700
1 completed: 671717150
12 completed: 1766717172
arr := []int{1343434, 1343434300, 234343400, 334343434000, 334343434000, 334343434000, 4232, 23545, 15535, 353535, 33434434, 5334345, 3533434345, 3535}
%Cpu0 : 0.3 us, 1.0 sy, 0.0 ni, 98.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu1 :100.0 us, 0.0 sy, 0.0 ni, 0.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu2 : 1.7 us, 0.7 sy, 0.0 ni, 97.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu3 : 1.6 us, 2.9 sy, 0.0 ni, 95.5 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu4 :100.0 us, 0.0 sy, 0.0 ni, 0.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu5 : 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu6 :100.0 us, 0.0 sy, 0.0 ni, 0.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu7 : 5.6 us, 1.0 sy, 0.0 ni, 93.4 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
ab -n 10000 -c 1000 http://localhost:8080/
Server Software:
Server Hostname: localhost
Server Port: 8080
Document Path: /
Document Length: 5 bytes
Concurrency Level: 1000
Time taken for tests: 0.509 seconds
Complete requests: 10000
Failed requests: 0
Write errors: 0
Total transferred: 1210000 bytes
HTML transferred: 50000 bytes
Requests per second: 19627.39 [#/sec] (mean)
Time per request: 50.949 [ms] (mean)
Time per request: 0.051 [ms] (mean, across all concurrent requests)
Transfer rate: 2319.25 [Kbytes/sec] received
func DomainRedirect() gin.HandlerFunc {
return func(c *gin.Context) {
if ваше_условие {
c.Redirect(302, "https://wifer-test.ru/" + c.Request.URL.String())
return
}
c.Next()
}
}
....
r := gin.New()
r.Use(DomainRedirect())
func (m *LoggingMiddleware) LogBody(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
wRecorder := httptest.NewRecorder()
next.ServeHTTP(wRecorder, r)
resp := wRecorder.Result()
body, _ := io.ReadAll(resp.Body)
// не забыть записать ответ в w
}
return http.HandlerFunc(fn)
}
func (m *LoggingMiddleware) LogBody(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
var buf bytes.Buffer
logWriter := NewLogToConsoleResponseWriter(&b)
next.ServeHTTP(logWriter, r)
// тут у вас в buf будет ответ сервера, с которым можно работать
// главное потом не забыть записать его в `w`
}
return http.HandlerFunc(fn)
}
package main
import (
"fmt"
"io/ioutil"
"gopkg.in/yaml.v3"
)
func main() {
fmt.Println("start")
c, err := readYaml("./tets.yml")
if err != nil {
panic(err.Error())
}
fmt.Println(c.Master, c.Kibana, c.Data, c.Pass, c.User)
}
type ClusterEnv struct {
Master []string `yaml:"master,flow"`
Data []string `yaml:"data,flow"`
Kibana []string `yaml:"kibana,flow"`
User string `yaml:"user"`
Pass string `yaml:"pass"`
}
func readYaml(filename string) (*ClusterEnv, error) {
buf, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
c := &ClusterEnv{}
err = yaml.Unmarshal(buf, c)
if err != nil {
return nil, fmt.Errorf("in file %q: %v", filename, err)
}
return c, nil
}