Skip to content

Instantly share code, notes, and snippets.

@ggzeng
ggzeng / cmd_flag_ex1.go
Last active April 12, 2021 09:27
使用flag包做命令行参数解析 官方的example已经比较全面,可以满足一般的使用 根据官方example,使用方法可以总结为下面三步: 1. 定义全局变量来保存命令行参数值 2. 在init()函数中定义参数名与变量的关系 3. 在main()中执行flag.Parse() [Go 命令行解析 flag 包之通过子命令实现看 go 命令源码](https://zhuanlan.zhihu.com/p/94580903) [Go 命令行解析 flag 包之快速上手](https://mp.w
// These examples demonstrate more intricate uses of the flag package.
package main
import (
"errors"
"flag"
"fmt"
"strings"
"time"
)
@ggzeng
ggzeng / tcp_connect_timeout_check.go
Last active October 21, 2019 11:33
检测TCP/UDP连接超时
m.Conn.SetReadDeadline(time.Now().Add(delay))
for {
n, err := m.Conn.Read(buffer)
if err != nil {
log.Println(err)
}
if n > 0 {
// something was read before the deadline
// let's delay the deadline
m.Conn.SetReadDeadline(time.Now().Add(delay))
@ggzeng
ggzeng / CMakeList.txt
Last active October 21, 2019 11:38
在clang中执行lua脚本
cmake_minimum_required (VERSION 3.0)
project (lua_embed C)
find_package(Lua REQUIRED)
include_directories (
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}
${LUA_INCLUDE_DIR}
)
@ggzeng
ggzeng / add.lua
Last active October 21, 2019 11:23
在clang中调用lua函数
function f(x, y)
return x + y
end
@ggzeng
ggzeng / call_go_from_lua.go
Last active October 21, 2019 11:34
在lua中调用go中的函数
package main
import lua "github.com/yuin/gopher-lua"
func Double(L *lua.LState) int {
lv := L.ToInt(1) /* get argument */
L.Push(lua.LNumber(lv * 2)) /* push result */
return 1 /* number of results */
}
@ggzeng
ggzeng / call_lua_function.go
Last active June 16, 2021 07:00
在golang里调用lua函数
package main
import (
"fmt"
lua "github.com/yuin/gopher-lua"
)
func main() {
L := lua.NewState()
defer L.Close()
@ggzeng
ggzeng / build_variable.go
Last active October 21, 2019 16:56
在build编译的时候初始化包中的变量
package main
import "fmt"
var (
VERSION string
BUILD_TIME string
GO_VERSION string
)
@ggzeng
ggzeng / golang_prometheus_metric_counter.go
Last active July 1, 2024 10:10
prometheus golang 客户端中的各类metric写法
//step1:初始一个counter, with help string
pushCounter = prometheus.NewCounter(prometheus.CounterOpts{
Name: "repository_pushes",
Help: "Number of pushes to external repository.",
})
//setp2: 注册容器
err = prometheus.Register(pushCounter)
if err != nil {
fmt.Println("Push counter couldn't be registered AGAIN, no counting will happen:", err)
@ggzeng
ggzeng / receive_channel_exit.go
Created October 22, 2019 06:08
接收channel如何优雅的退出
// 1. 场景:只有一个接收通道。使用for range,如果channel关闭则会自动退出循环
go func(in <-chan int) {
// Using for-range to exit goroutine
// range has the ability to detect the close/end of a channel
for x := range in {
fmt.Printf("Process %d\n", x)
}
}(inCh)
@ggzeng
ggzeng / goroutine_tunny_pool.go
Last active October 23, 2019 05:23
使用tunny包创建goroutine池
package main
import (
"io/ioutil"
"net/http"
"runtime"
"github.com/Jeffail/tunny"
)