0%

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)

type Resp struct {
Status string `json:"status"`
Message interface{} `json:"message"`
}

type Req struct {
Name string `json:"name"`
Age int `json:"age"`
}

func RequestExample(request Req) (*Resp, error) {
httpClient := &http.Client{}
httpClient.Timeout = 5 * time.Second
jsonValue, err := json.Marshal(request)
req, err := http.NewRequest("POST", "http://127.0.0.1/test", bytes.NewBuffer(jsonValue))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()

responseData, _ := ioutil.ReadAll(resp.Body)
dat := Resp{}
if err := json.Unmarshal(responseData, &dat); err != nil {
log.Println("failed to load json")
}
return &dat, nil
}

func main() {
req := Req{Name: "Bob", Age: 30}
resp, err := RequestExample(req)
if err != nil {
return
}
fmt.Println(resp)
}
阅读全文 »

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[program:xxxxx]
environment=XXXX1='111',XXXX2='222'
directory=/home/zyp/xxx/zzz
command=/home/zyp/xxx/zzz/venv/bin/uwsgi --ini xxx.ini
autostart=true
autorestart=unexpected
exitcodes=0,2
user=ymmops
startsecs=5
startretries=3
stopsignal=QUIT
redirect_stderr=true
stdout_logfile=/home/zyp/xxx/zzz/logs/xxx.log
stdout_logfile_maxbytes=100MB
stdout_logfile_backups=10
阅读全文 »

https://openresty.org/cn/

health check

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
lua_shared_dict healthcheck 2m;
lua_socket_log_errors off;

upstream backend-xxx {
ip_hash;
server 192.168.100.100:8000 weight=1 max_fails=3 fail_timeout=15s;
server 192.168.100.101:8000 weight=1 max_fails=3 fail_timeout=15s;
}

init_worker_by_lua_block {
local hc = require "resty.upstream.healthcheck"

local ok, err = hc.spawn_checker{
shm = "healthcheck", -- defined by "lua_shared_dict"
upstream = "backend-xxx", -- defined by "upstream"
type = "http",
http_req = "GET / HTTP/1.0\r\nHost: beidou.ymmoa.com\r\n\r\n",

interval = 2000, -- run the check cycle every 2 sec
timeout = 1000, -- 1 sec is the timeout for network operations
fall = 3, -- # of successive failures before turning a peer down
rise = 2, -- # of successive successes before turning a peer up
valid_statuses = {200, 302}, -- a list valid HTTP status code
concurrency = 10, -- concurrency level for test requests
}

local ok, err = hc.spawn_checker{
shm = "healthcheck", -- defined by "lua_shared_dict"
upstream = "backend-xxx", -- defined by "upstream"
type = "tcp",

interval = 2000, -- run the check cycle every 2 sec
timeout = 1000, -- 1 sec is the timeout for network operations
fall = 3, -- # of successive failures before turning a peer down
rise = 2, -- # of successive successes before turning a peer up
valid_statuses = {200, 302}, -- a list valid HTTP status code
concurrency = 10, -- concurrency level for test requests
}

if not ok then
ngx.log(ngx.ERR, "failed to spawn health checker: ", err)
return
end
}
阅读全文 »

Example1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main

import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)

func main() {
db, err := sql.Open("mysql", "user:password@/database")
if err != nil {
panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic
}
defer db.Close()

// Prepare statement for inserting data
stmtIns, err := db.Prepare("INSERT INTO squareNum VALUES( ?, ? )") // ? = placeholder
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
defer stmtIns.Close() // Close the statement when we leave main() / the program terminates

// Prepare statement for reading data
stmtOut, err := db.Prepare("SELECT squareNumber FROM squarenum WHERE number = ?")
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
defer stmtOut.Close()

// Insert square numbers for 0-24 in the database
for i := 0; i < 25; i++ {
_, err = stmtIns.Exec(i, (i * i)) // Insert tuples (i, i^2)
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
}

var squareNum int // we "scan" the result in here

// Query the square-number of 13
err = stmtOut.QueryRow(13).Scan(&squareNum) // WHERE number = 13
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
fmt.Printf("The square number of 13 is: %d", squareNum)

// Query another number.. 1 maybe?
err = stmtOut.QueryRow(1).Scan(&squareNum) // WHERE number = 1
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
fmt.Printf("The square number of 1 is: %d", squareNum)
}
阅读全文 »

Go Base Logger

Base Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main
import (
"log"
)
func init(){
log.SetPrefix("LOG: ")
log.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile)
log.Println("init started")
}
func main() {
// Println writes to the standard logger.
log.Println("main started")

// Fatalln is Println() followed by a call to os.Exit(1)
log.Fatalln("fatal message")

// Panicln is Println() followed by a call to panic()
log.Panicln("panic message")
}
阅读全文 »

ArgPrase

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

// Go provides a `flag` package supporting basic
// command-line flag parsing. We'll use this package to
// implement our example command-line program.
import "flag"
import "fmt"

func main() {
wordPtr := flag.String("word", "foo", "a string")
numbPtr := flag.Int("numb", 42, "an int")
boolPtr := flag.Bool("fork", false, "a bool")

var svar string
flag.StringVar(&svar, "svar", "bar", "a string var")

// Once all flags are declared, call `flag.Parse()`
// to execute the command-line parsing.
flag.Parse()

// Here we'll just dump out the parsed options and
// any trailing positional arguments. Note that we
// need to dereference the pointers with e.g. `*wordPtr`
// to get the actual option values.
fmt.Println("word:", *wordPtr)
fmt.Println("numb:", *numbPtr)
fmt.Println("fork:", *boolPtr)
fmt.Println("svar:", svar)
fmt.Println("tail:", flag.Args())
}
阅读全文 »

Example 1

1
2
3
4
5
6
func Task300() {
for {
time.Sleep(300 * time.Second)
run_task()
}
}

Example 2

1
2
3
4
5
6
7
8
9
10
11
func Task300() {
rand.Seed(time.Now().UnixNano())
n := rand.Intn(300)
time.Sleep(time.Duration(n) * time.Second)
ticker := time.NewTicker(time.Duration(300) * time.Second)
defer ticker.Stop()
for {
<-ticker.C
run_task()
}
}
阅读全文 »

间隔固定时间执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python

import sched
import datetime
import time

INTERVAL = 10
scheduler = sched.scheduler(time.time, time.sleep)


def main_loop(sc):
sc.enter(INTERVAL, 1, main_loop, (sc,))
print datetime.datetime.now()


def main():
scheduler.enter(INTERVAL, 1, main_loop, (scheduler,))
scheduler.run()


if __name__ == '__main__':
main()
阅读全文 »