config env get name and value

use github.com/spf13/viper Get env data config.go type urls struct { Demo1 string `mapstructure:"demo1"` Demo2 string `mapstructure:"demo2"` } type NotifyHttps struct { Name string `mapstructure:"name"` Token string `mapstructure:"token"` Urls urls `mapstructure:"urls"` } type env struct { NotifyHttp NotifyHttps `mapstructure:"notify_https"` } .env notify_https: name: order_comfire token: 123456abcdef urls: demo1: localhost:8888 demo2: localhost:8443 notify.go refUrls := reflect.ValueOf(config.Env.NotifyHttps.Urls) urlNum := refUrls.NumField() for i := 0; i < urlNum; i++ { url := refUrls.Field(i).String() if url != "" { // notify url // record refUrls.Type().Field(i).Name be notify. } }

2024-07-18 · 1 min · 84 words · Me

Unmarshal dynamic JSON based on a type key

https://play.golang.com/p/BPWVd0WAfqR package main import ( "encoding/json" "fmt" ) var bodyA = []byte(`{ "type": "A", "data": { "name": "Johnny" } }`) var bodyB = []byte(`{ "type": "B", "data": { "nickname": "J." } }`) type TypeA struct { Name string `json:"name"` } type TypeB struct { Nickname string `json:"nickname"` } func main() { req := struct { Type string `json:"type"` Data any `json:"data"` }{} err := json.Unmarshal(bodyA, &req) // bodyB if err != nil { panic(err) } switch req.Type { case "A": req.Data = new(TypeA) case "B": req.Data = new(TypeB) } err = json.Unmarshal(bodyA, &req) // bodyB if err != nil { panic(err) } message, _ := json.Marshal(&req) fmt.Println(string(message)) }

2024-05-06 · 1 min · 108 words · Me

Golang Concurrency

https://notes.shichao.io/gopl/ch9/

2024-04-16 · 1 min · word · Me

golang gin windows service

Golang Gin Api become Windows Service Use github.com/kardianos/service package main import ( "errors" "fmt" "io" "log" "net" "net/http" "os" "path/filepath" "strings" "time" "github.com/gin-gonic/gin" "github.com/joho/godotenv" "github.com/kardianos/service" ) // Process Windows Service // github.com/kardianos/service var logger service.Logger type program struct{} func (p *program) Start(s service.Service) error { // Start should not block. Do the actual work async. go p.run() return nil } func (p *program) Stop(s service.Service) error { // Stop should not block. Return with a few seconds. return nil } func ExecPath() string { ex, err := os.Executable() if err != nil { panic(err) } exPath := filepath.Dir(ex) return exPath } func main() { File, err := os.Create(ExecPath() + "\\gin_service_run.log") if err != nil { File = os.Stdout } defer File.Close() log.SetOutput(File) var s service.Service svcConfig := service.Config{ Name: "GinAPI", DisplayName: "Gin API Service", Description: "Gin API Server Converter Windows Service", } prg := &program{} s, err = service.New(prg, &svcConfig) if err != nil { log.Fatalln(err) } logger, err = s.Logger(nil) if err != nil { log.Fatalln(err) } if len(os.Args) > 1 { switch os.Args[1] { case "install": err := s.Install() if err != nil { logger.Errorf("Install Service Fail!", err.Error()) return } fmt.Printf("Install Service Success!") case "uninstall": err := s.Uninstall() if err != nil { logger.Errorf("Uninstall Service Fail!", err.Error()) return } fmt.Printf("Uninstall Service Success!") case "start": err := s.Start() if err != nil { logger.Errorf("Start Service Fail!", err.Error()) return } fmt.Printf("Start Service Success!") case "stop": err := s.Stop() if err != nil { logger.Errorf("Stop Service Fail!", err.Error()) return } fmt.Printf("Stop Service Success!") } return } err = s.Run() if err != nil { logger.Error(err) } } func (p *program) run() { // // Create Error logger // errFile, err := os.OpenFile(ExecPath()+"\\errors.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { log.Fatalf("打開日誌文件失敗:", err) } Error = log.New(io.MultiWriter(errFile, os.Stderr), "【Error】", log.Ldate|log.Ltime|log.Lshortfile) // // Get .env // err = godotenv.Load(ExecPath() + "\\.env") if err != nil { msg := "找不到 .env 檔案" logger.Errorf(msg, err) Error.Printf(msg, err) } web_port := os.Getenv("WEB_PORT") // // Start Gin // router := gin.Default() corsConfig := cors.DefaultConfig() corsConfig.AllowAllOrigins = true router.Use(cors.New(corsConfig)) router.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": "Gin Api Success!"}) }) log.Fatal(http.ListenAndServe(":"+web_port, router)) } 1. run server.exe can run Gin Api Server right now. 2. run server install, server uninstall, server start, server stop. 2.1 【Install and Start】run server install Then server start 2.2 【Stop and uninstall】run server stop Then server uninstall 3. log file use absolute path. ExecPath() can get absolute path. 4. .env must use absolute path. Try to use svcConfig.EnvVars = map[string]string{ "WEB_PORT": web port } see register Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\GinAPI have EnvVars Data. But err := godotenv.Load() can’t get anything, just No Error. So must use absolute path. ...

2023-01-11 · 3 min · 472 words · Me

LeetCode Cookbook GO GOLANG golang

https://books.halfrost.com/leetcode/

2020-08-14 · 1 min · word · Me

[轉]Go 交叉編譯

https://ithelp.ithome.com.tw/articles/10225188 在Windows上編譯 To MacOs SET CGO_ENABLED=0 SET GOOS=darwin SET GOARCH=amd64 go build main.go To Linux SET CGO_ENABLED=0 SET GOOS=linux SET GOARCH=amd64 go build main.go To Windows ??? go build main.go 在Linux上編譯 CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

2020-03-26 · 1 min · 49 words · Me

可參考的gin架構

https://marcoma.xyz/2019/02/23/gin-tutorial-1/

2020-01-22 · 1 min · word · Me

golang loggin gin

https://github.com/uber-go/zap https://marcoma.xyz/2019/03/17/gin-tutorial-7/ https://github.com/natefinch/lumberjack https://juejin.im/post/5d3932bde51d454f73356e2d

2020-01-21 · 1 min · 4 words · Me

NSQ golang 消息queue

http://www.jfh.com/jfperiodical/article/1949?

2020-01-04 · 1 min · word · Me

HEX 0x string to []byte to string DecodeString

https://play.golang.org/p/i90_qsN2Sz- package main import ( "fmt" "encoding/hex" ) func main() { id := "0x1dd84569ad60faa1b6838526ba7156388cf7c8d376ed0ccda9bce0419c2c3519" fmt.Printf("Ori ID: %v \n\n", id) fmt.Printf("Ori ID[2:]: %v \n\n", id[2:]) byteid := []byte(id) fmt.Printf("===== Byte id ===== Decimal \n") fmt.Printf("Byte ID: %v \n", byteid) fmt.Printf("Byte ID 0x%x \n\n", byteid) fmt.Printf("===== Decode(Byte id[2:]) ===== Decimal HEX \n") byteid = []byte(id[2:]) fmt.Printf("Byte ID: %v \n", byteid) fmt.Printf("Byte ID 0x%x \n\n", byteid) n, _ := hex.Decode(byteid, byteid) fmt.Printf("Byte ID[2:]: %v \n", byteid) fmt.Printf("Byte ID[2:] 0x%x \n", byteid) fmt.Printf("Byte ID[2:] [:n]: %v \n", byteid[:n]) fmt.Printf("Byte ID[2:] [:n] 0x%x \n\n", byteid[:n]) fmt.Printf("===== id ===== Decimal \n") idbyte32 := covertStringTByte32(id) fmt.Printf("Byte32 ID: %v \n", idbyte32 ) //fmt.Printf("String ID: %s \n", idbyte32 ) fmt.Printf("HEX ID: 0x%x \n\n", idbyte32 ) fmt.Printf("===== id[2:] ===== Decimal \n") idbyte32 = covertStringT2Byte32(id) fmt.Printf("Byte32 ID: %v \n", idbyte32 ) //fmt.Printf("String ID: %s \n", idbyte32 ) fmt.Printf("HEX ID: 0x%x \n\n", idbyte32 ) fmt.Printf("===== DecodeString(id[2:]) ===== HEX \n") idbyte32 = covertStringDecodeStringByte32(id) fmt.Printf("Byte32 ID: %v \n", idbyte32 ) //fmt.Printf("String ID: %s \n", idbyte32 ) fmt.Printf("HEX ID: 0x%x \n", idbyte32 ) } func covertStringTByte32(t string) [32]byte { var b32 [32]byte copy(b32[:], t) return b32 } func covertStringT2Byte32(t string) [32]byte { var b32 [32]byte copy(b32[:], t[2:]) //remove 0x return b32 } func covertStringDecodeStringByte32(t string) [32]byte { data, err := hex.DecodeString(t[2:]) if err != nil { fmt.Printf("ERR \n") } fmt.Printf("DecodeString data: %v \n", data) fmt.Printf("DecodeString data length: %v \n\n", len(data)) var b32 [32]byte copy(b32[:], data) return b32 } Ori ID: 0x1dd84569ad60faa1b6838526ba7156388cf7c8d376ed0ccda9bce0419c2c3519 Ori ID[2:]: 1dd84569ad60faa1b6838526ba7156388cf7c8d376ed0ccda9bce0419c2c3519 ===== Byte id ===== Decimal Byte ID: [48 120 49 100 100 56 52 53 54 57 97 100 54 48 102 97 97 49 98 54 56 51 56 53 50 54 98 97 55 49 53 54 51 56 56 99 102 55 99 56 100 51 55 54 101 100 48 99 99 100 97 57 98 99 101 48 52 49 57 99 50 99 51 53 49 57] Byte ID 0x307831646438343536396164363066616131623638333835323662613731353633383863663763386433373665643063636461396263653034313963326333353139 ===== Decode(Byte id[2:]) ===== Decimal HEX Byte ID: [49 100 100 56 52 53 54 57 97 100 54 48 102 97 97 49 98 54 56 51 56 53 50 54 98 97 55 49 53 54 51 56 56 99 102 55 99 56 100 51 55 54 101 100 48 99 99 100 97 57 98 99 101 48 52 49 57 99 50 99 51 53 49 57] Byte ID 0x31646438343536396164363066616131623638333835323662613731353633383863663763386433373665643063636461396263653034313963326333353139 Byte ID[2:]: [29 216 69 105 173 96 250 161 182 131 133 38 186 113 86 56 140 247 200 211 118 237 12 205 169 188 224 65 156 44 53 25 56 99 102 55 99 56 100 51 55 54 101 100 48 99 99 100 97 57 98 99 101 48 52 49 57 99 50 99 51 53 49 57] Byte ID[2:] 0x1dd84569ad60faa1b6838526ba7156388cf7c8d376ed0ccda9bce0419c2c35193863663763386433373665643063636461396263653034313963326333353139 Byte ID[2:] [:n]: [29 216 69 105 173 96 250 161 182 131 133 38 186 113 86 56 140 247 200 211 118 237 12 205 169 188 224 65 156 44 53 25] Byte ID[2:] [:n] 0x1dd84569ad60faa1b6838526ba7156388cf7c8d376ed0ccda9bce0419c2c3519 ===== id ===== Decimal Byte32 ID: [48 120 49 100 100 56 52 53 54 57 97 100 54 48 102 97 97 49 98 54 56 51 56 53 50 54 98 97 55 49 53 54] HEX ID: 0x3078316464383435363961643630666161316236383338353236626137313536 ===== id[2:] ===== Decimal Byte32 ID: [49 100 100 56 52 53 54 57 97 100 54 48 102 97 97 49 98 54 56 51 56 53 50 54 98 97 55 49 53 54 51 56] HEX ID: 0x3164643834353639616436306661613162363833383532366261373135363338 ===== DecodeString(id[2:]) ===== HEX DecodeString data: [29 216 69 105 173 96 250 161 182 131 133 38 186 113 86 56 140 247 200 211 118 237 12 205 169 188 224 65 156 44 53 25] DecodeString data length: 32 Byte32 ID: [29 216 69 105 173 96 250 161 182 131 133 38 186 113 86 56 140 247 200 211 118 237 12 205 169 188 224 65 156 44 53 25] HEX ID: 0x1dd84569ad60faa1b6838526ba7156388cf7c8d376ed0ccda9bce0419c2c3519 Program exited. https://onlineutf8tools.com/convert-hexadecimal-to-utf8 ...

2019-09-11 · 4 min · 662 words · Me

[轉]Go-JWT-RESTful身份认证教程

https://segmentfault.com/a/1190000020329813 1.什么是JWT JWT(JSON Web Token)是一个非常轻巧的规范,这个规范允许我们使用JWT在用户和服务器之间传递安全可靠的信息, 一个JWT由三部分组成,Header头部、Claims载荷、Signature签名, JWT原理类似我们加盖公章或手写签名的的过程,合同上写了很多条款,不是随便一张纸随便写啥都可以的,必须要一些证明,比如签名,比如盖章,JWT就是通过附加签名,保证传输过来的信息是真的,而不是伪造的, 它将用户信息加密到token里,服务器不保存任何用户信息,服务器通过使用保存的密钥验证token的正确性,只要正确即通过验证, 2.JWT构成 一个JWT由三部分组成,Header头部、Claims载荷、Signature签名, Header头部:头部,表明类型和加密算法 Claims载荷:声明,即载荷(承载的内容) Signature签名:签名,这一部分是将header和claims进行base64转码后,并用header中声明的加密算法加盐(secret)后构成,即: let tmpstr = base64(header)+base64(claims) let signature = encrypt(tmpstr,secret) //最后三者用".“连接,即: let token = base64(header)+”."+base64(claims)+"."+signature

2019-09-09 · 1 min · 26 words · Me

oauth2 NewClient InsecureSkipVerify

https://github.com/terraform-providers/terraform-provider-github/blob/master/github/config.go ctx := context.Background() insecureClient := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, }, } ctx = context.WithValue(ctx, oauth2.HTTPClient, insecureClient) client := oauth2.NewClient(ctx, oauth2.StaticTokenSource(&oauth2.Token{ AccessToken: c.Param("accesstoken"), TokenType: "Bearer", })) resp, err := client.Get("https://ory-hydra-login-consent:9020/openid/userinfo") if err != nil { return newHTTPError(400, "InvalidToken", err.Error()) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return newHTTPError(400, "InvalidToken", err.Error()) } c.Logger().Debugf("resp: %s", body) var t map[string]interface{} err = json.Unmarshal(body, &t) if err != nil { return newHTTPError(400, "InvalidToken", err.Error()) } return c.JSON(http.StatusOK, t)

2019-09-09 · 1 min · 83 words · Me

golang go-ethereum contract string to [32]byte

func covertStringByte32(t string) [32]byte { var b32 [32]byte copy(b32[:], []byte(t)) return b32 } func covertStringByte64(t string) [64]byte { var b64 [64]byte copy(b64[:], []byte(t)) return b64 }

2019-09-05 · 1 min · 26 words · Me

golang test e2e

httpexpect star 1159 https://github.com/gavv/httpexpect https://github.com/gavv/httpexpect/blob/master/_examples/echo_test.go goconvey https://segmentfault.com/a/1190000014924022 https://github.com/smartystreets/goconvey/ baloo star 652 https://github.com/h2non/baloo frisby star 249 https://github.com/verdverm/frisby apitest star 121 https://github.com/steinfletcher/apitest

2019-09-04 · 1 min · 20 words · Me

[轉]通过 Channel 实现 Goroutine Pool

https://segmentfault.com/a/1190000020185565

2019-09-04 · 1 min · word · Me

[轉]Go学习之Channel总结

https://segmentfault.com/a/1190000020086749

2019-09-04 · 1 min · word · Me

go mod custome model

https://stackoverflow.com/questions/52079662/go-get-cannot-find-local-packages-when-using-multiple-modules-in-a-repo api/contracts/contract.go package contracts import ( "math/big" "strings" ).... func DeployContract(...) api/contract.go package main import ( "api/contracts" ...) func deployContract(c echo.Context) error { address, tx, token, err := contracts.DeployContract(auth, client) ... } ! Best Import is api/go.mod module api require ( api/contracts v0.0.0 ...) replace ( api/contracts v0.0.0 => ./contracts ...) And api/contracts/go.mod module api/contracts require ( ...) ``` ` `` ``````

2019-09-03 · 1 min · 62 words · Me

go-eth

https://medium.com/taipei-ethereum-meetup/%E4%BD%BF%E7%94%A8-go-%E8%88%87%E4%BB%A5%E5%A4%AA%E5%9D%8A%E5%8D%80%E5%A1%8A%E9%8F%88%E4%BA%92%E5%8B%95-%E4%B8%89-7b7b1f40c06a https://github.com/sc0Vu/go-eth

2019-09-02 · 1 min · 2 words · Me

golang echo rest demo

https://github.com/hyacinthus/restdemo/blob/master/GOLANG-RESTFUL-API.pdf https://github.com/hyacinthus/restdemo

2019-08-31 · 1 min · 2 words · Me

[轉]Go面向对象编程以及在Tendermint/Cosmos-SDK中的应用

https://segmentfault.com/a/1190000019776978

2019-07-16 · 1 min · word · Me