Skip to content

Commit

Permalink
Merge pull request #1 from jiangjinyuan/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
jiangjinyuan authored Sep 27, 2021
2 parents c1f6dba + fe6267c commit 49180a3
Show file tree
Hide file tree
Showing 47 changed files with 1,726 additions and 1,334 deletions.
44 changes: 44 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: Go
on: [push]
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Set up Go 1.14
uses: actions/setup-go@v2
with:
go-version: 1.14
id: go
- run: go version
- name: Get dependencies And Test
run: |
go get -v -t -d ./...
if [ -f Gopkg.toml ]; then
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
dep ensure
fi
go test -gcflags=-l -v -cover -timeout=5s ./...
- name: Golangci Lint
uses: golangci/golangci-lint-action@v2
with:
version: v1.40
args: ./...
skip-go-installation: true
skip-pkg-cache: true
skip-build-cache: true
- run: mkdir bin
- name: Build Module
run: |
go build -v -o ./bin/command ./main.go
# - name: Slack
# uses: 8398a7/action-slack@v3
# with:
# status: ${{ job.status }}
# fields: repo,message,commit,author,action,ref
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: always()
18 changes: 18 additions & 0 deletions .github/workflows/reviewdog.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: Reviewdog
on: [pull_request]
jobs:
golangci-lint:
name: runner / golangci-lint
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: reviewdog-golangci-lint
uses: reviewdog/action-golangci-lint@v1
with:
golangci_lint_flags: "--timeout=5m"
- name: golangci-lint
uses: golangci/golangci-lint-action@v2
with:
version: v1.29
args: ./...
140 changes: 140 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
linters-settings:
depguard:
list-type: blacklist
packages:
packages-with-error-message:
dupl:
threshold: 100
exhaustive:
default-signifies-exhaustive: false
funlen:
lines: 200
statements: 100
gci:
local-prefixes: github.com/golangci/golangci-lint
goconst:
min-len: 2
min-occurrences: 2
gocritic:
enabled-tags:
- diagnostic
- experimental
- opinionated
- performance
- style
disabled-checks:
- dupImport # https://github.com/go-critic/go-critic/issues/845
- ifElseChain
- octalLiteral
- whyNoLint
- wrapperFunc
- commentedOutCode # commentedOutCode: may want to remove commented-out code (gocritic)
gocyclo:
min-complexity: 15
goimports:
local-prefixes: github.com/golangci/golangci-lint
golint:
min-confidence: 0
gomnd:
settings:
mnd:
# don't include the "operation" and "assign"
checks: argument,case,condition,return
govet:
check-shadowing: true
settings:
printf:
funcs:
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
lll:
line-length: 160
maligned:
suggest-new: true
misspell:
locale: US
nolintlint:
allow-leading-space: true # don't require machine-readable nolint directives (i.e. with no leading space)
allow-unused: false # report any unused nolint directives
require-explanation: false # don't require an explanation for nolint directives
require-specific: false # don't require nolint directives to be specific about which linter is being skipped

linters:
# please, do not use `enable-all`: it's deprecated and will be removed soon.
# inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint
disable-all: true
enable:
- bodyclose
- deadcode
- depguard
- dogsled
- errcheck
- exhaustive
- goconst
- gocritic
- gofmt
- goimports
- goprintffuncname
- gosimple
- govet
- ineffassign
- lll
- misspell
- nolintlint
- rowserrcheck
- exportloopref
- staticcheck
- structcheck
- stylecheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- whitespace
- funlen

# don't enable:
# - asciicheck
# - gochecknoinits
# - gochecknoglobals
# - gocognit
# - godot
# - godox
# - goerr113
# - maligned
# - nestif
# - prealloc
# - testpackage
# - wsl
# - gomnd
# - gosec
# - noctx
# - gocyclo
# - dupl
# - revive
# - nakedret

issues:
exclude:
- Using the variable on range scope `tt` in function literal
- File is not `goimports`-ed with -local github.com/golangci/golangci-lint
# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
- path: _test\.go
linters:
- gomnd
# https://github.com/go-critic/go-critic/issues/926
- linters:
- gocritic
text: "unnecessaryDefer:"
- linters:
- lll
source: "var Nolll"

run:
timeout: 5m
skip-dirs:
- docs/*
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# explorerBlockHeightMonitor

The monitor use for blcokchain explorer, include block height...
The monitor for different coin's BlockChain explorer, include block height...

## 用途

* 浏览器块高监控报警
* 节点块高监控报警
173 changes: 173 additions & 0 deletions client/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package client

import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"strings"
"time"
)

type HTTPClient struct {
client http.Client
Debug bool
}

var Client *HTTPClient

// NewHTTPTLSClient 初始化 http tls 客户端
func NewHTTPTLSClient() *HTTPClient {
pool := x509.NewCertPool()
caCertPath := "xxx.cer"
caCrt, err := ioutil.ReadFile(caCertPath)
if err != nil {
fmt.Println("ReadFile err:", err)
}
pool.AppendCertsFromPEM(caCrt)

// 本地证书
cliCrt, err := tls.LoadX509KeyPair("cert.cer", "cert.key")
if err != nil {
fmt.Println("Loadx509keypair err:", err)
}

tr := &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: pool,
Certificates: []tls.Certificate{cliCrt},
// 忽略服务器端证书校验,仅测试
// 这里为了测试方便忽略了验证
InsecureSkipVerify: true,
},
}
client := http.Client{Transport: tr}
return &HTTPClient{client: client}
}

// NewHTTPClient 初始化 http 客户端
func NewHTTPClient() *HTTPClient {
// 跳过证书验证
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
MaxIdleConnsPerHost: 100,
MaxIdleConns: 0,
MaxConnsPerHost: 0,
}
client := http.Client{
Timeout: 10 * time.Second,
Transport: tr,
}
return &HTTPClient{client: client}
}

// SetTimeout 重置超时时间
func (c *HTTPClient) SetTimeout(t time.Duration) {
c.client.Timeout = t
}

// MakeGetURL : 拼接 url
func (c *HTTPClient) MakeGetURL(endpoint string, args map[string]string) string {
url := endpoint
first := true
if strings.Contains(url, "?") {
first = false
}
for k, v := range args {
if first {
url = fmt.Sprintf("%s?%s=%s", url, k, v)
first = false
} else {
url = fmt.Sprintf("%s&%s=%s", url, k, v)
}
}
return url
}

// MakeRequest : 构造请求
func (c *HTTPClient) MakeRequest(ctx context.Context, method, endpoint string, data io.Reader, vs []interface{}) (*http.Request, error) {
// https://www.v2ex.com/t/622953
// ctx, cancel := context.WithTimeout(req.Context(), 1*time.Millisecond)
req, err := http.NewRequestWithContext(ctx, method, endpoint, data)
if err != nil {
return nil, err
}
for _, v := range vs {
switch vv := v.(type) {
case http.Header:
for key, values := range vv {
for _, value := range values {
req.Header.Add(key, value)
}
}
case map[string]string:
for key, value := range vv {
req.Header[key] = []string{value}
}
}
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
return req, err
}

// Get : get 方法, 之后可以增加重试
func (c *HTTPClient) Get(endpoint string, vs ...interface{}) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := c.MakeRequest(ctx, "GET", endpoint, nil, vs)
if err != nil {
return nil, err
}
if c.Debug {
byts, _ := httputil.DumpRequest(req, true)
fmt.Println(string(byts))
}
res, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if c.Debug {
dump, _ := httputil.DumpResponse(res, true)
fmt.Println(string(dump))
}
return body, nil
}

// Post : post 方法
func (c *HTTPClient) Post(endpoint string, data io.Reader, vs ...interface{}) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := c.MakeRequest(ctx, "POST", endpoint, data, vs)
if err != nil {
return nil, err
}
// 输出到 log
if c.Debug {
byts, _ := httputil.DumpRequest(req, true)
fmt.Println(string(byts))
}
res, err := c.client.Do(req)
if err != nil {
return nil, err
}
if c.Debug {
dump, _ := httputil.DumpResponse(res, true)
fmt.Println(string(dump))
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return body, err
}
Loading

0 comments on commit 49180a3

Please sign in to comment.