EExcel 丞燕快速查詢2

EExcel 丞燕快速查詢2
EExcel 丞燕快速查詢2 https://sandk.ffbizs.com/
顯示具有 golang 標籤的文章。 顯示所有文章
顯示具有 golang 標籤的文章。 顯示所有文章

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.
  }
}

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))
}

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.

5. log have two method.

5.1 File, err := os.Create(ExecPath() + "\\gin_service_run.log")

5.2 【logger.Errorf】 This Error Msg showed at Windows Servce and have Error tag.

OK~ Just try. Hope this blog can help.

[轉]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

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

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

[轉]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

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)

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
}

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

[轉]通过 Channel 实现 Goroutine Pool

https://segmentfault.com/a/1190000020185565

[轉]Go学习之Channel总结

https://segmentfault.com/a/1190000020086749

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 (
...)

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

golang echo rest demo

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

https://github.com/hyacinthus/restdemo