text stringlengths 11 4.05M |
|---|
package hashmap_shards
import (
"fmt"
"time"
)
func (impl implementation) HSetWithExpiration(key, field string, value interface{}, ttl time.Duration) error {
keyShards := fmt.Sprintf("%s-%d", key, impl.hash(field))
return impl.redis.HSetWithExpiration(keyShards, field, value, ttl)
}
func (impl implementation) HSet(key, field string, value interface{}) error {
keyShards := fmt.Sprintf("%s-%d", key, impl.hash(field))
return impl.redis.HSet(keyShards, field, value)
} |
package upstream_notify
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/shopspring/decimal"
"tpay_backend/model"
"tpay_backend/payapi/internal/logic"
"tpay_backend/upstream"
"github.com/tal-tech/go-zero/core/logx"
"tpay_backend/payapi/internal/svc"
)
type GoldPaysTransferLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGoldPaysTransferLogic(ctx context.Context, svcCtx *svc.ServiceContext) GoldPaysTransferLogic {
return GoldPaysTransferLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GoldPaysTransferLogic) GoldPaysTransfer(body []byte) error {
var reqData struct {
AppId string `json:"merchant"` // 商户号
ReqNo string `json:"orderId"` // 商户订单号
OrderNo string `json:"platOrderId"` // 平台订单号
Amount string `json:"amount"` // 金额
Msg string `json:"msg"` // 处理消息
OrderStatus string `json:"status"` // 交易状态,值见数据字典
Sign string `json:"sign"` // 签名
}
// 1.解析接口数据
if err := json.Unmarshal(body, &reqData); err != nil {
return errors.New(fmt.Sprintf("解析json参数失败:%v", err))
}
// 2.参数验证
if reqData.AppId == "" || reqData.ReqNo == "" || reqData.OrderNo == "" || reqData.OrderStatus == "" || reqData.Sign == "" || reqData.Amount == "" {
return errors.New(fmt.Sprintf("缺少必须参数,reqData:%+v", reqData))
}
// 3.获取上游
up, err := model.NewUpstreamModel(l.svcCtx.DbEngine).FindOneByUpstreamMerchantNo(reqData.AppId)
if err != nil {
if err == model.ErrRecordNotFound {
return errors.New(fmt.Sprintf("未找到对应的上游:UpstreamMerchantNo:%v", reqData.AppId))
} else {
return errors.New(fmt.Sprintf("查询上游信息失败:err:%v,UpstreamMerchantNo:%v", err, reqData.AppId))
}
}
upObj, err := logic.NewFuncLogic(l.svcCtx).GetUpstreamObject(up)
if err != nil {
logx.Errorf("获取上游对象失败err:%v,upstream:%+v", err, up)
return errors.New("获取上游对象失败")
}
// 4.验签
dataMap := make(map[string]interface{})
if err := json.Unmarshal(body, &dataMap); err != nil {
logx.Errorf("解析body到map失败err:%v", err)
return errors.New("解析body到map失败")
}
if err := upObj.CheckSign(dataMap); err != nil {
l.Errorf("验签失败, data:%+v, err:%v", dataMap, err)
return err
}
// 5.查询订单
order, err := model.NewTransferOrderModel(l.svcCtx.DbEngine).FindByOrderNo(reqData.ReqNo)
if err != nil {
if err == model.ErrRecordNotFound {
l.Errorf("订单[%v]不存在", reqData.ReqNo)
return errors.New(fmt.Sprintf("找不到订单[%v]", reqData.ReqNo))
} else {
return errors.New("查询订单失败")
}
}
l.Infof("订单信息:%+v", order)
if order.OrderStatus == model.TransferOrderStatusPaid {
l.Errorf("代付订单已支付,重复通知, order.OrderNo:%v", order.OrderNo)
return nil
}
if order.OrderStatus != model.TransferOrderStatusPending {
l.Errorf("代付订单不是待支付订单, order.OrderNo:%v, order.OrderStatus:%v", order.OrderNo, order.OrderStatus)
return errors.New("订单状态不允许")
}
// 上游金额单位是卢比 平台金额单位是分 1卢比=100分
orderAmount := decimal.NewFromInt(order.ReqAmount).Div(decimal.NewFromInt(100)).Round(2).String()
if orderAmount != reqData.Amount {
l.Errorf("订单[%v]金额不对, order.reqAmount:%v, reqData.Amount:%v", reqData.ReqNo, order.ReqAmount, reqData.Amount)
return errors.New("订单金额不对")
}
// 6.同步订单信息
var orderStatus int64
switch reqData.OrderStatus {
case upstream.GoldPaysOrderStatusPaySuccess:
orderStatus = model.TransferOrderStatusPaid
case upstream.GoldPaysOrderStatusPayFail:
orderStatus = model.TransferOrderStatusFail
default:
l.Errorf("上游通知的是一个未知的订单状态, order_status:%v", reqData.OrderStatus)
return errors.New("订单状态不对")
}
if err := NewSyncOrder(context.TODO(), l.svcCtx).SyncTransferOrder(order, orderStatus, reqData.Msg); err != nil {
l.Errorf("同步订单信息, orderNo:%v, MerchantNo:%v, err:%v", order.OrderNo, order.MerchantNo, err)
return err
}
return nil
}
|
package main
import (
SL "golang_Learn/ptslowlog/slowlog"
"fmt"
)
func main(){
//SL.SlowLogForMart("/home/jiemin/code/go_dev/src/golang_Learn/ptslowlog/conf/conf.yaml")
slowlogStr:=SL.SlowLogForMart("/home/jiemin/code/go_dev/src/golang_Learn/ptslowlog/conf/conf.yaml")
fmt.Println(slowlogStr)
}
|
package zconfig
import (
"bufio"
"errors"
"fmt"
"os"
"strconv"
"strings"
)
func (c *Configer) parse(f *os.File) error {
//
line := 0
s := bufio.NewScanner(f)
for s.Scan() {
line = line + 1
content := strings.TrimSpace(s.Text())
if len(content) == 0 {
continue
}
// comment
if commentIndex := strings.Index(content, COMMENT_STRING); commentIndex == 0 {
continue
}
// equal
equalIndex := strings.Index(content, EQUAL_STRING)
if equalIndex <= 0 {
return fmt.Errorf("invalid format[near =] in line:%v!", line)
}
//
key := strings.TrimSpace(content[0:equalIndex])
if len(key) < 0 {
return fmt.Errorf("invalid format[near key] in line:%v", line)
}
//
value := strings.TrimSpace(content[equalIndex+1:])
value = c.correct(value)
if len(value) < 0 {
return fmt.Errorf("invalid format[near value] in line:%v", line)
}
c.set(key, value)
}
if err := s.Err(); err != nil {
return fmt.Errorf("read %s error! error:%v\n", c.path, err.Error())
}
return nil
}
func (c *Configer) set(key string, value string) {
c.data[key] = value
arrs := strings.Split(key, SUBSPLIT_STRING)
if len(arrs) != 2 {
return
}
prefix, subfix := arrs[0], arrs[1]
subs, ok := c.prefix[prefix]
if !ok {
subs = make([]string, 0)
}
c.prefix[prefix] = append(subs, subfix)
}
// 如果两边都有引号 去除两边引号
func (c *Configer) correct(value string) string {
if len(value) == 1 {
return value
}
// 两侧都有引号 去除引号
if ((string(value[0]) == "\"") && (string(value[len(value)-1]) == "\"")) ||
((string(value[0]) == "'") && (string(value[len(value)-1]) == "'")) {
return value[1 : len(value)-1]
}
return value
}
func (c *Configer) correct2(value string) (string, error) {
if len(value) == 1 {
return "", errors.New("invalid value format!")
}
// 两侧都有引号 去除引号
first, last := (string(value[0]) == "\""), (string(value[len(value)-1]) == "\"")
if first && last {
return value[1 : len(value)-1], nil
}
//
first, last = (string(value[0]) == "'"), (string(value[len(value)-1]) == "'")
if first && last {
return value[1 : len(value)-1], nil
}
// 两侧都没有 返回value
if (!first) && (!last) {
return value, nil
}
// 一侧有 一侧没有报错
return "", errors.New("invalid value format!")
}
// 可能会有001 100 002 这种情况
func (c *Configer) sortInt(keys []string) ([]int, map[int]string) {
arr := make([]int, 0)
sortmap := make(map[int]string)
for _, key := range keys {
ikey, err := strconv.Atoi(key)
if err != nil {
continue
}
sortmap[ikey] = key
// 直接插入排序
pos := len(arr) - 1
arr = append(arr, ikey)
for ; pos >= 0; pos-- {
if ikey < arr[pos] {
arr[pos+1] = arr[pos]
continue
}
break
}
arr[pos+1] = ikey
}
return arr, sortmap
}
|
/*
* Copyright © 2020-2022 Software AG, Darmstadt, Germany and/or its licensors
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package adabas
import (
"github.com/SoftwareAG/adabas-go-api/adatypes"
)
// ReadLobStream reads field data using partial lob reads and provide it
// stream-like to the user. It is possible to use it to read big LOB data
// or stream a video.
// The value of the field is reused, so that the value does not need to
// evaluate/searched in the result instance once more after the first
// call.
// This method initialize the first call by
// - searching the record (it must be a unique result)
// - prepare partial lob query
// Important parameter is the blocksize in the `ReadRequest` which
// defines the size of one block to be read
func (request *ReadRequest) ReadLobStream(search, field string) (cursor *Cursoring, err error) {
//err = request.QueryFields("#" + field)
err = request.QueryFields("")
if err != nil {
return
}
result, rerr := request.ReadLogicalWith(search)
if rerr != nil {
return nil, rerr
}
if len(result.Values) != 1 {
if len(result.Values) > 1 {
err = adatypes.NewGenericError(137)
return
}
err = adatypes.NewGenericError(138)
return
}
request.definition.ResetRestrictToFields()
adatypes.Central.Log.Debugf("Found record ...streaming ISN=%d BlockSize=%d",
result.Values[0].Isn, request.BlockSize)
request.cursoring.result, err = request.ReadLOBRecord(result.Values[0].Isn, field, uint64(request.BlockSize))
if err != nil {
return nil, err
}
adatypes.Central.Log.Debugf("Read record ...streaming ISN=%d BlockSize=%d",
result.Values[0].Isn, request.BlockSize)
return request.cursoring, nil
}
// ReadLOBSegment reads field data using partial lob reads and provide it
// stream-like to the user. It is possible to use it to read big LOB data
// or stream a video.
// The value of the field is reused, so that the value does not need to
// evaluate/searched in the result instance once more after the first
// call.
// This method initialize the first call by
// - offset 0
// - prepare partial lob query of given blocksize
// Important parameter is the blocksize in the `ReadRequest` which
// defines the size of one block to be read
func (request *ReadRequest) ReadLOBSegment(isn adatypes.Isn, field string, blocksize uint64) (segment []byte, err error) {
result, err := request.ReadLOBRecord(isn, field, blocksize)
if err != nil {
return nil, err
}
// If last segment is reached and EOF is received, record is not available
if result.NrRecords() != 1 {
segment = make([]byte, 0)
return
}
// Search record containing the segment
v, found := result.Values[0].searchValue(field)
if found {
segment = v.Bytes()
return
}
err = adatypes.NewGenericError(183)
return
}
// ReadLOBRecord read lob records in an stream, repeated call will read next segment of LOB
func (request *ReadRequest) ReadLOBRecord(isn adatypes.Isn, field string, blocksize uint64) (result *Response, err error) {
debug := adatypes.Central.IsDebugLevel()
if request.cursoring == nil || request.cursoring.adabasRequest == nil {
if debug {
adatypes.Central.Log.Debugf("Read LOB record initiated ...")
}
request.cursoring = &Cursoring{}
request.BlockSize = uint32(blocksize)
request.PartialRead = true
_, oErr := request.Open()
if oErr != nil {
err = oErr
return
}
err = request.QueryFields(field)
if err != nil {
adatypes.Central.Log.Debugf("Query fields error ...%#v", err)
return nil, err
}
if debug {
adatypes.Central.Log.Debugf("LOB Definition generated ...BlockSize=%d", request.BlockSize)
}
err = request.definition.CreateValues(false)
if err != nil {
return
}
if debug {
adatypes.Central.Log.Debugf("LOB create values, types defined")
request.definition.DumpTypes(true, true)
adatypes.Central.Log.Debugf("LOB list of values")
request.definition.DumpValues(true)
adatypes.Central.Log.Debugf("Search field: %s", field)
}
fieldName, index := parseField(field)
fieldValue, ferr := request.definition.SearchByIndex(fieldName, index, true)
if ferr != nil {
return nil, ferr
}
if fieldValue == nil {
return nil, adatypes.NewGenericError(184, field)
}
if debug {
adatypes.Central.Log.Debugf("LOB after defined")
request.definition.DumpValues(true)
adatypes.Central.Log.Debugf("Found field: %s for %d,%d", fieldValue.Type().Name(), fieldValue.MultipleIndex(), fieldValue.PeriodIndex())
}
var lob adatypes.ILob
switch t := fieldValue.(type) {
case adatypes.ILob:
lob = t
default:
return nil, adatypes.NewGenericError(185, field)
}
lob.SetLobBlockSize(blocksize)
lob.SetLobPartRead(true)
if debug {
adatypes.Central.Log.Debugf("Read LOB with ...%#v", field)
}
adabasRequest, prepareErr := request.prepareRequest(false)
if prepareErr != nil {
err = prepareErr
return
}
adabasRequest.Parser = parseReadToRecord
adabasRequest.Limit = 1
request.cursoring.adabasRequest = adabasRequest
if debug {
adatypes.Central.Log.Debugf("Query field LOB values ...%#v", field)
adatypes.Central.Log.Debugf("Create LOB values ...%#v", field)
}
adabasRequest.Limit = 1
adabasRequest.Multifetch = 1
adabasRequest.Isn = isn
adabasRequest.Option.PartialRead = true
request.cursoring.adabasRequest = adabasRequest
request.cursoring.search = field
request.queryFunction = request.readSteamSegment
request.cursoring.request = request
result = &Response{Definition: request.definition, fields: request.fields}
err = request.adabas.readISN(request.repository.Fnr, adabasRequest, result)
} else {
if debug {
adatypes.Central.Log.Debugf("Read next LOB segment with ...cursoring")
}
/*
request.definition.DumpTypes(false, false, "All")
request.definition.DumpTypes(false, true, "Active")
request.definition.DumpValues(true)
request.definition.DumpValues(false)*/
err = request.definition.CreateValues(false)
if err != nil {
return
}
/*
request.definition.DumpTypes(false, false, "All")
request.definition.DumpTypes(false, true, "Active")
request.definition.DumpValues(true)
request.definition.DumpValues(false)
fmt.Println("Search", field, request.definition.Fieldnames())
*/
fieldValue := request.definition.Search(field)
lob := fieldValue.(adatypes.ILob)
lob.SetLobBlockSize(blocksize)
lob.SetLobPartRead(true)
request.cursoring.adabasRequest.Option.PartialRead = true
/*
request.definition.DumpValues(true)
request.definition.DumpValues(false)
*/
result = &Response{Definition: request.definition, fields: request.fields}
if debug {
adatypes.Central.Log.Debugf("Call next LOB read %v/%d", request.cursoring.adabasRequest.Option.PartialRead, request.BlockSize)
}
err = request.adabas.loopCall(request.cursoring.adabasRequest, result)
}
if debug {
adatypes.Central.Log.Debugf("Error reading %v", err)
}
return result, err
}
func (request *ReadRequest) readSteamSegment(search, descriptors string) (result *Response, err error) {
if adatypes.Central.IsDebugLevel() {
adatypes.Central.Log.Debugf("read LOB >1 segments")
}
return request.ReadLOBRecord(0, search, uint64(request.BlockSize))
}
|
//
// Copyright (c) 2017, Stardog Union. <http://stardog.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sdutils
import (
"time"
"gopkg.in/alecthomas/kingpin.v2"
)
// ConsoleEffect is a function for writing lines to the console in a
// visually pleasing way. For example red text for error messages.
type ConsoleEffect func(a ...interface{}) string
// BaseDeployment hold information about the deployments and is serialized
// to JSON. CloudOpts is defined by the specific plugin in use.
type BaseDeployment struct {
Type string `json:"type,omitempty"`
Name string `json:"name,omitempty"`
Directory string `json:"directory,omitempty"`
Version string `json:"version,omitempty"`
PrivateKey string `json:"private_key,omitempty"`
CustomPropsFile string `json:"custom_props,omitempty"`
CustomLog4J string `json:"custom_log4j,omitempty"`
IdleTimeout int `json:"idle_timeout,omitempty"`
Environment []string `json:"environment,omitempty"`
DisableSecurity bool `json:"disable_security,omitempty"`
CloudOpts interface{} `json:"cloud_opts,omitempty"`
CustomScript string `json:"custom_script,omitempty"`
CustomZkScript string `json:"custom_zk_script,omitempty"`
}
// AppContext provides and abstraction to logging, console interaction and
// basic configuration information
type AppContext interface {
ConsoleLog(level int, format string, v ...interface{})
Logf(level int, format string, v ...interface{})
GetConfigDir() string
GetVersion() string
GetInteractive() bool
HighlightString(a ...interface{}) string
SuccessString(a ...interface{}) string
FailString(a ...interface{}) string
}
// StardogDescription represents the state of a Stardog deployment. It is effectively
// the output from a status command.
type StardogDescription struct {
StardogURL string `json:"stardog_url,omitempty"`
StardogInternalURL string `json:"stardog_internal_url,omitempty"`
StardogNodes []string `json:"stardog_nodes,omitempty"`
SSHHost string `json:"ssh_host,omitempty"`
Healthy bool `json:"healthy,omitempty"`
TimeStamp time.Time `json:"timestamp,omitempty"`
VolumeDescription interface{} `json:"volume,omitempty"`
InstanceDescription interface{} `json:"instance,omitempty"`
}
// Deployment is an interface to a plugin that is managing the actual Stardog services.
type Deployment interface {
CreateVolumeSet(licensePath string, sizeOfEachVolume int, clusterSize int) error
DeleteVolumeSet() error
StatusVolumeSet() error
VolumeExists() bool
ClusterSize() (int, error)
CreateInstance(volumeSize int, zookeeperSize int, idleTimeout int, bastionVolSnapshotId string) error
OpenInstance(volumeSize int, zookeeperSize int, mask string, idleTimeout int) error
DeleteInstance() error
StatusInstance() error
InstanceExists() bool
FullStatus() (*StardogDescription, error)
DestroyDeployment() error
}
// CommandOpts holds all of the CLI parsing information for the system.
// It is passed to plugins so that each driver can add their own specific
// flags.
type CommandOpts struct {
Cli *kingpin.Application
LaunchCmd *kingpin.CmdClause
DestroyCmd *kingpin.CmdClause
StatusCmd *kingpin.CmdClause
LeaksCmd *kingpin.CmdClause
ClientCmd *kingpin.CmdClause
SSHCmd *kingpin.CmdClause
PasswdCmd *kingpin.CmdClause
AboutCmd *kingpin.CmdClause
BuildCmd *kingpin.CmdClause
NewDeploymentCmd *kingpin.CmdClause
DestroyDeploymentCmd *kingpin.CmdClause
ListDeploymentCmd *kingpin.CmdClause
NewVolumesCmd *kingpin.CmdClause
DestroyVolumesCmd *kingpin.CmdClause
StatusVolumesCmd *kingpin.CmdClause
LaunchInstanceCmd *kingpin.CmdClause
DestroyInstanceCmd *kingpin.CmdClause
StatusInstanceCmd *kingpin.CmdClause
}
// Plugin defines the interface for adding drivers to the system
type Plugin interface {
Register(cmdOpts *CommandOpts) error
DeploymentLoader(context AppContext, baseD *BaseDeployment, new bool) (Deployment, error)
LoadDefaults(defaultCliOpts interface{}) error
BuildImage(context AppContext, sdReleaseFilePath string, version string) error
GetName() string
FindLeaks(context AppContext, deploymentName string, destroy bool, force bool) error
HaveImage(context AppContext) bool
}
|
package main
import (
"github.com/eiannone/keyboard"
)
type Keypress struct {
ch rune
key keyboard.Key
}
func keyboardChannel() (<-chan Keypress /*, func ()*/) {
kch := make(chan Keypress)
go func() {
var err error
err = keyboard.Open()
if err == nil {
for {
ch, key, err := keyboard.GetKey()
if err != nil { break }
if ch == 0 && key == 0 { break /* closed */ }
kch<- Keypress{ch, key}
}
}
keyboard.Close()
close(kch)
return
}()
/* var kcl := func() { keyboard.Close() } */
return kch /* , kcl */
}
|
package cli
import (
"fmt"
"strconv"
rpcclient "github.com/raedahgroup/dcrcli/walletrpcclient"
qrcode "github.com/skip2/go-qrcode"
)
func balance(walletrpcclient *rpcclient.Client, commandArgs []string) (*response, error) {
balances, err := walletrpcclient.Balance()
if err != nil {
return nil, err
}
res := &response{
columns: []string{
"Account",
"Total",
"Spendable",
"Locked By Tickets",
"Voting Authority",
"Unconfirmed",
},
result: make([][]interface{}, len(balances)),
}
for i, v := range balances {
res.result[i] = []interface{}{
v.AccountName,
v.Total,
v.Spendable,
v.LockedByTickets,
v.VotingAuthority,
v.Unconfirmed,
}
}
return res, nil
}
func normalSend(walletrpcclient *rpcclient.Client, _ []string) (*response, error) {
return send(walletrpcclient, false)
}
func customSend(walletrpcclient *rpcclient.Client, _ []string) (*response, error) {
return send(walletrpcclient, true)
}
func send(walletrpcclient *rpcclient.Client, custom bool) (*response, error) {
var err error
sourceAccount, err := getSendSourceAccount(walletrpcclient)
if err != nil {
return nil, err
}
// check if account has positive non-zero balance before proceeding
// if balance is zero, there'd be no unspent outputs to use
accountBalance, err := walletrpcclient.SingleAccountBalance(sourceAccount, nil)
if err != nil {
return nil, err
}
if accountBalance.Total == 0 {
return nil, fmt.Errorf("Selected account has 0 balance. Cannot proceed")
}
destinationAddress, err := getSendDestinationAddress(walletrpcclient)
if err != nil {
return nil, err
}
sendAmount, err := getSendAmount()
if err != nil {
return nil, err
}
var utxoSelection []string
if custom {
// get all utxos in account, pass 0 amount to get all
utxos, err := walletrpcclient.UnspentOutputs(sourceAccount, 0)
if err != nil {
return nil, err
}
utxoSelection, err = getUtxosForNewTransaction(utxos, sendAmount)
if err != nil {
return nil, err
}
}
passphrase, err := getWalletPassphrase()
if err != nil {
return nil, err
}
var result *rpcclient.SendResult
if custom {
result, err = walletrpcclient.SendFromUTXOs(utxoSelection, sendAmount, sourceAccount,
destinationAddress, passphrase)
} else {
result, err = walletrpcclient.SendFromAccount(sendAmount, sourceAccount, destinationAddress, passphrase)
}
if err != nil {
return nil, err
}
res := &response{
columns: []string{
"Result",
"Hash",
},
result: [][]interface{}{
[]interface{}{
"The transaction was published successfully",
result.TransactionHash,
},
},
}
return res, nil
}
func receive(walletrpcclient *rpcclient.Client, commandArgs []string) (*response, error) {
var recieveAddress uint32
// if no address passed in
if len(commandArgs) == 0 {
// display menu options to select account
var err error
recieveAddress, err = getSendSourceAccount(walletrpcclient)
if err != nil {
return nil, err
}
} else {
// if an address was passed in eg. ./dcrcli receive 0 use that address
x, err := strconv.ParseUint(commandArgs[0], 10, 32)
if err != nil {
return nil, fmt.Errorf("Error parsing account number: %s", err.Error())
}
recieveAddress = uint32(x)
}
r, err := walletrpcclient.Receive(recieveAddress)
if err != nil {
return nil, err
}
qr, err := qrcode.New(r.Address, qrcode.Medium)
if err != nil {
return nil, fmt.Errorf("Error generating QR Code: %s", err.Error())
}
res := &response{
columns: []string{
"Address",
"QR Code",
},
result: [][]interface{}{
[]interface{}{
r.Address,
qr.ToString(true),
},
},
}
return res, nil
}
func transactionHistory(walletrpcclient *rpcclient.Client, _ []string) (*response, error) {
transactions, err := walletrpcclient.GetTransactions()
if err != nil {
return nil, err
}
res := &response{
columns: []string{
"Date",
"Amount (DCR)",
"Direction",
"Hash",
"Type",
},
result: make([][]interface{}, len(transactions)),
}
for i, tx := range transactions {
res.result[i] = []interface{}{
tx.FormattedTime,
tx.Amount,
tx.Direction,
tx.Hash,
tx.Type,
}
}
return res, nil
}
|
package gobchest
import (
"encoding/gob"
"fmt"
"io/ioutil"
"math/rand"
"os"
"path/filepath"
"testing"
"time"
)
func randomFilePath() string {
return filepath.Join(os.TempDir(), "golang-gobchest-test-file-"+fmt.Sprintf("%d", rand.Uint32()))
}
func randomAddr() string {
return fmt.Sprintf("localhost:%d", 20000+rand.Intn(10000))
}
func setupTestServer(t *testing.T) (*Server, string) {
retries := 3
retry:
addr := randomAddr()
server, err := NewServer(addr, randomFilePath())
if err != nil {
if retries > 0 {
retries--
goto retry
} else {
t.Fatal(err)
}
}
return server, addr
}
func setupTestClient(t *testing.T, addr string) *Client {
client, err := NewClient(addr)
if err != nil {
t.Fatal(err)
}
return client
}
func TestNew(t *testing.T) {
server, addr := setupTestServer(t)
defer server.Close()
client := setupTestClient(t, addr)
defer client.Close()
}
func TestBadAddr(t *testing.T) {
_, err := NewClient("nohost:999")
if err == nil {
t.Fatal("should fail")
}
_, err = NewServer("nohost:999", randomFilePath())
if err == nil {
t.Fatal("should fail")
}
}
func TestInvalidFilePath(t *testing.T) {
_, err := NewServer(randomAddr(), os.TempDir())
if err == nil {
t.Fatal("should fail")
}
_, err = NewServer(randomAddr(), "\000\000\000")
if err == nil {
t.Fatal("should fail")
}
server, err := NewServer(randomAddr(), randomFilePath())
if err != nil {
t.Fatal(err)
}
filePath := server.filePath
server.Save()
err = os.Chmod(filePath, 0000) // make it non-readable
if err != nil {
t.Fatal(err)
}
_, err = NewServer(randomAddr(), filePath)
if err == nil {
t.Fatal("should fail")
}
}
func TestReopen(t *testing.T) {
server, err := NewServer(randomAddr(), randomFilePath())
if err != nil {
t.Fatal(err)
}
filePath := server.filePath
server.Save()
server.Close()
server, err = NewServer(randomAddr(), filePath)
if err != nil {
t.Fatal(err)
}
}
func TestInvalidFile(t *testing.T) {
filePath := randomFilePath()
err := ioutil.WriteFile(filePath, []byte("garbage"), 0600)
if err != nil {
t.Fatal(err)
}
_, err = NewServer(randomAddr(), filePath)
if err == nil {
t.Fatal("should fail")
}
}
func TestSaveFail(t *testing.T) {
dirPath := randomFilePath()
err := os.Mkdir(dirPath, 0500)
if err != nil {
t.Fatal(err)
}
filePath := filepath.Join(dirPath, "foo")
server, err := NewServer(randomAddr(), filePath)
if err != nil {
t.Fatal(err)
}
func() {
defer func() {
if err := recover(); err == nil {
t.Fatal("should fail")
}
}()
server.Save()
}()
errored := false
server.SetErrorHandler(func(err error) {
errored = true
})
server.Save()
if !errored {
t.Fatal("should fail")
}
}
func TestInvalidValue(t *testing.T) {
server, _ := setupTestServer(t)
gob.Register(new(func()))
server.chest.Data["foo"] = func() {} // not encodable
errored := false
server.SetErrorHandler(func(error) {
errored = true
})
server.Save()
if !errored {
t.Fatal("should fail")
}
}
func TestSetGet(t *testing.T) {
server, addr := setupTestServer(t)
defer server.Close()
client := setupTestClient(t, addr)
defer client.Close()
err := client.Set("foo", "foo")
if err != nil {
t.Fatal(err)
}
if server.chest.Data["foo"] != "foo" {
t.Fatal("Set: foo is not foo")
}
v, err := client.Get("foo")
if err != nil {
t.Fatal(err)
}
if v.(string) != "foo" {
t.Fatal("Get: foo is not foo")
}
v, err = client.Get("keynotexists")
if err == nil {
t.Fatal("Get: should fail")
}
}
func TestSave(t *testing.T) {
server, addr := setupTestServer(t)
client := setupTestClient(t, addr)
err := client.Set("foo", "foo")
if err != nil {
t.Fatal(err)
}
server.Save()
server.Close()
server, err = NewServer(randomAddr(), server.filePath)
if err != nil {
t.Fatal(err)
}
client, err = NewClient(server.addr)
if err != nil {
t.Fatal(err)
}
v, err := client.Get("foo")
if err != nil {
t.Fatal(err)
}
if v.(string) != "foo" {
t.Fatal("foo is not foo")
}
}
func TestPeriodicSave(t *testing.T) {
server, addr := setupTestServer(t)
defer server.Close()
client := setupTestClient(t, addr)
defer client.Close()
stop := make(chan struct{})
for i := 0; i < 128; i++ {
go func() {
for {
select {
case <-stop:
return
default:
client.Set("foo", "foo")
}
}
}()
}
time.Sleep(time.Second * 2)
close(stop)
}
func TestMultipleClient(t *testing.T) {
server, addr := setupTestServer(t)
defer server.Close()
stop := make(chan struct{})
for i := 0; i < 16; i++ {
client := setupTestClient(t, addr)
defer client.Close()
go func() {
for {
select {
case <-stop:
return
default:
client.Set("foo", "foo")
client.Get("foo")
}
}
}()
}
time.Sleep(time.Second * 1)
close(stop)
}
func TestListAppend(t *testing.T) {
server, addr := setupTestServer(t)
defer server.Close()
client := setupTestClient(t, addr)
defer client.Close()
err := client.ListAppend("foo", 1, 2, 3, 4, 5)
if err != nil {
t.Fatal(err)
}
v, err := client.Get("foo")
if err != nil {
t.Fatal(err)
}
if v, ok := v.([]int); !ok {
t.Fatal("type not match")
} else {
for i := 1; i <= 5; i++ {
if v[i-1] != i {
t.Fatal("list not match")
}
}
}
err = client.ListAppend("foo", 6, 7, 8, 9, 10)
if err != nil {
t.Fatal(err)
}
v, err = client.Get("foo")
if err != nil {
t.Fatal(err)
}
if v, ok := v.([]int); !ok {
t.Fatal("type not match")
} else {
for i := 1; i <= 10; i++ {
if v[i-1] != i {
t.Fatal("list not match")
}
}
}
}
func TestSetAdd(t *testing.T) {
server, addr := setupTestServer(t)
defer server.Close()
client := setupTestClient(t, addr)
defer client.Close()
err := client.SetAdd("foo", 1)
if err != nil {
t.Fatal(err)
}
if v, ok := server.chest.Data["foo"]; !ok {
t.Fatalf("set not set")
} else {
if _, ok := v.(map[int]struct{})[1]; !ok {
t.Fatalf("key not set")
}
}
err = client.SetAdd("foo", 42)
if err != nil {
t.Fatal(err)
}
if v, ok := server.chest.Data["foo"]; !ok {
t.Fatalf("set not set")
} else {
if _, ok := v.(map[int]struct{})[42]; !ok {
t.Fatalf("key not set")
}
}
}
func TestSetExists(t *testing.T) {
server, addr := setupTestServer(t)
defer server.Close()
client := setupTestClient(t, addr)
defer client.Close()
err := client.SetAdd("foo", 1)
if err != nil {
t.Fatal(err)
}
if !client.SetExists("foo", 1) {
t.Fatal("should be true")
}
if client.SetExists("foo", 42) {
t.Fatal("should be false")
}
if client.SetExists("bar", 42) {
t.Fatal("should be false")
}
client.SetAdd("bar", 42)
if !client.SetExists("bar", 42) {
t.Fatal("should be true")
}
}
func TestBadListAppend(t *testing.T) {
server, addr := setupTestServer(t)
defer server.Close()
client := setupTestClient(t, addr)
defer client.Close()
client.Set("foo", 1)
err := client.ListAppend("foo", 1)
if err == nil {
t.Fatal("should fail")
}
}
|
package main
import (
"github.com/jinzhu/gorm"
)
type PendingUnlocksRepository struct {
db *gorm.DB
}
func NewPendingUnlocksRepository(db *gorm.DB) *PendingUnlocksRepository {
return &PendingUnlocksRepository{db: db}
}
func (repo *PendingUnlocksRepository) Get(slackUserId string) (*PendingUnlock, error) {
pendingUnlock := new(PendingUnlock)
res := repo.db.First(pendingUnlock, &PendingUnlock{SlackUserId: slackUserId})
if res.Error == nil {
return pendingUnlock, nil
} else if res.RecordNotFound() {
return nil, nil
}
return nil, res.Error
}
func (repo *PendingUnlocksRepository) Create(slackUserId string) error {
pendingUnlock := &PendingUnlock{SlackUserId: slackUserId}
res := repo.db.Create(pendingUnlock)
return res.Error
}
func (repo *PendingUnlocksRepository) Delete(pendingUnlock *PendingUnlock) error {
res := repo.db.Delete(pendingUnlock)
return res.Error
}
|
package models
import "gopkg.in/mgo.v2/bson"
// Represents a video, we uses bson keyword to tell the mgo driver how to name
// the properties in mongodb document
type Video struct {
ID bson.ObjectId `bson:"_id" json:"id"`
User_ID int `bson:"user_id" json:"user_id"`
Category_ID string `bson:"category_id" json:"category_id"`
Video_ID string `bson:"video_id" json:"video_id"`
Views int `bson:"views" json:"views"`
Title string `bson:"title" json:"title"`
Description string `bson:"description" json:"description"`
OriginalName string `bson:"originalname" json:"originalname"`
Filename string `bson:"filename" json:"filename"`
Image string `bson:"image" json:"image"`
}
|
package web
import (
"net/http"
)
// HandlerFunc is a http.HandlerFunc variant that returns error
type HandlerFunc func(w http.ResponseWriter, r *http.Request) error
// Handler is a http.Handler implementation that handles HandlerFunc
type Handler struct {
H HandlerFunc
}
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := h.H(w, r); err != nil {
RespondJSON(r.Context(), w, err, nil)
}
}
|
package login
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/charlesfan/go-api/service/rsi"
"github.com/charlesfan/go-api/utils/log"
)
func EmailLogin(c *gin.Context) {
//Implement: Use backend service
s := rsi.LoginService
b := c.MustGet("info").(rsi.EmailLoginBody)
if err := s.EmailChecking(&b); err != nil {
log.Error(err)
resp := map[string]string{"error": "EmailChecking return false"}
code := 401
c.JSON(code, resp)
c.Abort()
return
}
responseData := map[string]interface{}{
"mgs": "success",
}
c.JSON(http.StatusOK, responseData)
}
|
package chapter4
import "fmt"
//不像Java与.Net,Go为程序员提供了控制数据结构的指针的能力
//但不能进行指针运算,通过给予程序员基本内存布局,Go语言允许控制
//特定集合的数据结构,分配的数量以及内存访问模式
//
//每个内存块(或字)有一个地址,通常使用十六进制数表示
//
//Go语言的取地址符是& 放到一个变量前使用就会返回相应变量的内存地址
//
func TestPointerPrint(){
a := 5
fmt.Printf("Int: %d, Ptr: %v\n",a,&a)
//这个地址可以存储在一个叫做指针的特殊数据类型中,在本例中这是一个指向int的指针
//可以声明一个int类型的指针
var intP *int
intP = &a
fmt.Println(intP)
//一个指针变量可以指向任何一个值的内存地址,它指向的那个值的内存地址
//在32位机上占用4个字节 64位机上占用8个字节
//使用一个指针引用一个值为间接引用,
//反引用,指针转移,或叫解指针同样使用*与C++几乎一样的语法
//当一个指针被定义没有分配任何变量时,值为nil
//一个指针变量通常编写为ptr
//注意:在书写表达式类似 var p *type时,一定要将*与变量名用一个空格分开
//虽然 p*type语法是正确识别的,但容易被认为是一个乘法表达式
//
//符号*可以放在指针类型上,C++中叫做二级指针
//
var test_multi_ptr **int
test_multi_ptr = &intP
fmt.Println(test_multi_ptr,*test_multi_ptr,**test_multi_ptr)
s := "good bye"
var p *string = &s
*p = "ciao"
fmt.Printf("Here is the pointer p: %p\n", p) // prints address
fmt.Printf("Here is the string *p: %s\n", *p) // prints string
fmt.Printf("Here is the string s: %s\n", s) // prints same string
//注意:不能得到一个文字或常量的地址,例如
//const i = 5
//ptr := &i
//ptr2 := &10
//
//Go语言和C++这些语言一样,但是对于经常导致C语言内存泄漏从而导致程序崩溃的指针运算
//(即指 ptr++ 这样操作)是不被允许的,Go为了保证内存安全,更像是Java中的引用
//注意:Go不支持指针本地的(偏移)运算
//指针的高级应用是可以传递变量使用(参数),指针传递是廉价的,提高效率
//
//另一方面,由于指针导致的间接引用(一个进程执行了另一个地址),指针的过度频繁使用可以会导致性能下降
//
//指针也可以指向另一个指针,并且可以进行任意深度的嵌套,即多级指针(多级间接引用)
//注意:Go语言为了方便程序员,隐藏间接引用,如:自动反向引用
//
//对于一个空指针的反向引用是不合法的,并且会使用程序崩溃
//注意:相当于C++的野指针,为了防止危险操作
//指针使用前一定要正确地初始化
//var p *int = nil
//*p = 0
}
|
package main
import (
"fmt"
"sync"
)
type rect struct {
length int
width int
}
func (r rect) area(group *sync.WaitGroup) {
defer group.Done()
if r.length < 0 {
fmt.Printf("rect %v's length should be greater than zero\n", r)
return
}
if r.width < 0 {
fmt.Printf("rect %v's width should be greater than zero\n", r)
return
}
area := r.length * r.width
fmt.Printf("rect %v's area %d",r, area)
group.Done()
}
func main() {
var group sync.WaitGroup
r1 := rect{
length: -67,
width: 89,
}
r2 := rect{
length: 5,
width: -67,
}
r3 := rect{
length: 8,
width: 9,
}
rects := []rect{r1, r2, r3}
for _, r := range rects {
group.Add(1)
go r.area(&group)
}
group.Wait()
fmt.Println("All go routines finished executing")
} |
// Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package binloginfo_test
import (
"context"
"fmt"
"net"
"os"
"strconv"
"sync"
"testing"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
_ "github.com/pingcap/tidb/autoid_service"
"github.com/pingcap/tidb/ddl"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/parser/terror"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/binloginfo"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/testkit"
"github.com/pingcap/tidb/testkit/external"
pumpcli "github.com/pingcap/tidb/tidb-binlog/pump_client"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tipb/go-binlog"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type mockBinlogPump struct {
mu struct {
sync.Mutex
payloads [][]byte
mockFail bool
}
}
func (p *mockBinlogPump) WriteBinlog(ctx context.Context, req *binlog.WriteBinlogReq) (*binlog.WriteBinlogResp, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.mu.mockFail {
return &binlog.WriteBinlogResp{}, errors.New("mock fail")
}
p.mu.payloads = append(p.mu.payloads, req.Payload)
return &binlog.WriteBinlogResp{}, nil
}
// PullBinlogs implements PumpServer interface.
func (p *mockBinlogPump) PullBinlogs(req *binlog.PullBinlogReq, srv binlog.Pump_PullBinlogsServer) error {
return nil
}
type binlogSuite struct {
store kv.Storage
serv *grpc.Server
pump *mockBinlogPump
client *pumpcli.PumpsClient
ddl ddl.DDL
}
const maxRecvMsgSize = 64 * 1024
func createBinlogSuite(t *testing.T) (s *binlogSuite) {
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/store/driver/txn/mockSyncBinlogCommit", `return(true)`))
s = new(binlogSuite)
store := testkit.CreateMockStore(t)
s.store = store
unixFile := "/tmp/mock-binlog-pump" + strconv.FormatInt(time.Now().UnixNano(), 10)
l, err := net.Listen("unix", unixFile)
require.NoError(t, err)
s.serv = grpc.NewServer(grpc.MaxRecvMsgSize(maxRecvMsgSize))
s.pump = new(mockBinlogPump)
binlog.RegisterPumpServer(s.serv, s.pump)
go func() {
err := s.serv.Serve(l)
require.NoError(t, err)
}()
opt := grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout("unix", addr, timeout)
})
clientCon, err := grpc.Dial(unixFile, opt, grpc.WithTransportCredentials(insecure.NewCredentials()))
require.NoError(t, err)
require.NotNil(t, clientCon)
tk := testkit.NewTestKit(t, s.store)
sessionDomain := domain.GetDomain(tk.Session().(sessionctx.Context))
s.ddl = sessionDomain.DDL()
s.client = binloginfo.MockPumpsClient(binlog.NewPumpClient(clientCon))
s.ddl.SetBinlogClient(s.client)
t.Cleanup(func() {
clientCon.Close()
err = s.ddl.Stop()
require.NoError(t, err)
s.serv.Stop()
err = os.Remove(unixFile)
if err != nil {
require.EqualError(t, err, fmt.Sprintf("remove %v: no such file or directory", unixFile))
}
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/store/driver/txn/mockSyncBinlogCommit"))
})
return
}
func TestBinlog(t *testing.T) {
s := createBinlogSuite(t)
tk := testkit.NewTestKit(t, s.store)
tk.MustExec("use test")
tk.Session().GetSessionVars().BinlogClient = s.client
pump := s.pump
tk.MustExec("drop table if exists local_binlog")
ddlQuery := "create table local_binlog (id int unique key, name varchar(10)) shard_row_id_bits=1"
binlogDDLQuery := "create table local_binlog (id int unique key, name varchar(10)) /*T! shard_row_id_bits=1 */"
tk.MustExec(ddlQuery)
var matched bool // got matched pre DDL and commit DDL
for i := 0; i < 10; i++ {
preDDL, commitDDL, _ := getLatestDDLBinlog(t, pump, binlogDDLQuery)
if preDDL != nil && commitDDL != nil {
if preDDL.DdlJobId == commitDDL.DdlJobId {
require.Equal(t, preDDL.StartTs, commitDDL.StartTs)
require.Greater(t, commitDDL.CommitTs, commitDDL.StartTs)
matched = true
break
}
}
time.Sleep(time.Millisecond * 10)
}
require.True(t, matched)
tk.MustExec("insert local_binlog values (1, 'abc'), (2, 'cde')")
prewriteVal := getLatestBinlogPrewriteValue(t, pump)
require.Greater(t, prewriteVal.SchemaVersion, int64(0))
require.Greater(t, prewriteVal.Mutations[0].TableId, int64(0))
expected := [][]types.Datum{
{types.NewIntDatum(1), types.NewCollationStringDatum("abc", mysql.DefaultCollationName)},
{types.NewIntDatum(2), types.NewCollationStringDatum("cde", mysql.DefaultCollationName)},
}
gotRows := mutationRowsToRows(t, prewriteVal.Mutations[0].InsertedRows, 2, 4)
require.Equal(t, expected, gotRows)
tk.MustExec("update local_binlog set name = 'xyz' where id = 2")
prewriteVal = getLatestBinlogPrewriteValue(t, pump)
oldRow := [][]types.Datum{
{types.NewIntDatum(2), types.NewCollationStringDatum("cde", mysql.DefaultCollationName)},
}
newRow := [][]types.Datum{
{types.NewIntDatum(2), types.NewCollationStringDatum("xyz", mysql.DefaultCollationName)},
}
gotRows = mutationRowsToRows(t, prewriteVal.Mutations[0].UpdatedRows, 1, 3)
require.Equal(t, oldRow, gotRows)
gotRows = mutationRowsToRows(t, prewriteVal.Mutations[0].UpdatedRows, 7, 9)
require.Equal(t, newRow, gotRows)
tk.MustExec("delete from local_binlog where id = 1")
prewriteVal = getLatestBinlogPrewriteValue(t, pump)
gotRows = mutationRowsToRows(t, prewriteVal.Mutations[0].DeletedRows, 1, 3)
expected = [][]types.Datum{
{types.NewIntDatum(1), types.NewCollationStringDatum("abc", mysql.DefaultCollationName)},
}
require.Equal(t, expected, gotRows)
// Test table primary key is not integer.
tk.Session().GetSessionVars().EnableClusteredIndex = variable.ClusteredIndexDefModeIntOnly
tk.MustExec("create table local_binlog2 (name varchar(64) primary key, age int)")
tk.MustExec("insert local_binlog2 values ('abc', 16), ('def', 18)")
tk.MustExec("delete from local_binlog2 where name = 'def'")
prewriteVal = getLatestBinlogPrewriteValue(t, pump)
require.Equal(t, binlog.MutationType_DeleteRow, prewriteVal.Mutations[0].Sequence[0])
expected = [][]types.Datum{
{types.NewStringDatum("def"), types.NewIntDatum(18), types.NewIntDatum(-1), types.NewIntDatum(2)},
}
gotRows = mutationRowsToRows(t, prewriteVal.Mutations[0].DeletedRows, 1, 3, 4, 5)
require.Equal(t, expected, gotRows)
// Test Table don't have primary key.
tk.MustExec("create table local_binlog3 (c1 int, c2 int)")
tk.MustExec("insert local_binlog3 values (1, 2), (1, 3), (2, 3)")
tk.MustExec("update local_binlog3 set c1 = 3 where c1 = 2")
prewriteVal = getLatestBinlogPrewriteValue(t, pump)
// The encoded update row is [oldColID1, oldColVal1, oldColID2, oldColVal2, -1, handle,
// newColID1, newColVal2, newColID2, newColVal2, -1, handle]
gotRows = mutationRowsToRows(t, prewriteVal.Mutations[0].UpdatedRows, 7, 9)
expected = [][]types.Datum{
{types.NewIntDatum(3), types.NewIntDatum(3)},
}
require.Equal(t, expected, gotRows)
expected = [][]types.Datum{
{types.NewIntDatum(-1), types.NewIntDatum(3), types.NewIntDatum(-1), types.NewIntDatum(3)},
}
gotRows = mutationRowsToRows(t, prewriteVal.Mutations[0].UpdatedRows, 4, 5, 10, 11)
require.Equal(t, expected, gotRows)
tk.MustExec("delete from local_binlog3 where c1 = 3 and c2 = 3")
prewriteVal = getLatestBinlogPrewriteValue(t, pump)
require.Equal(t, binlog.MutationType_DeleteRow, prewriteVal.Mutations[0].Sequence[0])
gotRows = mutationRowsToRows(t, prewriteVal.Mutations[0].DeletedRows, 1, 3, 4, 5)
expected = [][]types.Datum{
{types.NewIntDatum(3), types.NewIntDatum(3), types.NewIntDatum(-1), types.NewIntDatum(3)},
}
require.Equal(t, expected, gotRows)
// Test Mutation Sequence.
tk.MustExec("create table local_binlog4 (c1 int primary key, c2 int)")
tk.MustExec("insert local_binlog4 values (1, 1), (2, 2), (3, 2)")
tk.MustExec("begin")
tk.MustExec("delete from local_binlog4 where c1 = 1")
tk.MustExec("insert local_binlog4 values (1, 1)")
tk.MustExec("update local_binlog4 set c2 = 3 where c1 = 3")
tk.MustExec("commit")
prewriteVal = getLatestBinlogPrewriteValue(t, pump)
require.Equal(t, []binlog.MutationType{
binlog.MutationType_DeleteRow,
binlog.MutationType_Insert,
binlog.MutationType_Update,
}, prewriteVal.Mutations[0].Sequence)
// Test statement rollback.
tk.MustExec("create table local_binlog5 (c1 int primary key)")
tk.MustExec("begin")
tk.MustExec("insert into local_binlog5 value (1)")
// This statement execute fail and should not write binlog.
_, err := tk.Exec("insert into local_binlog5 value (4),(3),(1),(2)")
require.Error(t, err)
tk.MustExec("commit")
prewriteVal = getLatestBinlogPrewriteValue(t, pump)
require.Equal(t, []binlog.MutationType{
binlog.MutationType_Insert,
}, prewriteVal.Mutations[0].Sequence)
checkBinlogCount(t, pump)
pump.mu.Lock()
originBinlogLen := len(pump.mu.payloads)
pump.mu.Unlock()
tk.MustExec("set @@global.autocommit = 0")
tk.MustExec("set @@global.autocommit = 1")
pump.mu.Lock()
newBinlogLen := len(pump.mu.payloads)
pump.mu.Unlock()
require.Equal(t, originBinlogLen, newBinlogLen)
}
func TestMaxRecvSize(t *testing.T) {
s := createBinlogSuite(t)
info := &binloginfo.BinlogInfo{
Data: &binlog.Binlog{
Tp: binlog.BinlogType_Prewrite,
PrewriteValue: make([]byte, maxRecvMsgSize+1),
},
Client: s.client,
}
binlogWR := info.WriteBinlog(1)
err := binlogWR.GetError()
require.Error(t, err)
require.Falsef(t, terror.ErrCritical.Equal(err), fmt.Sprintf("%v", err))
}
func getLatestBinlogPrewriteValue(t *testing.T, pump *mockBinlogPump) *binlog.PrewriteValue {
var bin *binlog.Binlog
pump.mu.Lock()
for i := len(pump.mu.payloads) - 1; i >= 0; i-- {
payload := pump.mu.payloads[i]
bin = new(binlog.Binlog)
err := bin.Unmarshal(payload)
require.NoError(t, err)
if bin.Tp == binlog.BinlogType_Prewrite {
break
}
}
pump.mu.Unlock()
require.NotNil(t, bin)
preVal := new(binlog.PrewriteValue)
err := preVal.Unmarshal(bin.PrewriteValue)
require.NoError(t, err)
return preVal
}
func getLatestDDLBinlog(t *testing.T, pump *mockBinlogPump, ddlQuery string) (preDDL, commitDDL *binlog.Binlog, offset int) {
pump.mu.Lock()
for i := len(pump.mu.payloads) - 1; i >= 0; i-- {
payload := pump.mu.payloads[i]
bin := new(binlog.Binlog)
err := bin.Unmarshal(payload)
require.NoError(t, err)
if bin.Tp == binlog.BinlogType_Commit && bin.DdlJobId > 0 {
commitDDL = bin
}
if bin.Tp == binlog.BinlogType_Prewrite && bin.DdlJobId != 0 {
preDDL = bin
}
if preDDL != nil && commitDDL != nil {
offset = i
break
}
}
pump.mu.Unlock()
require.Greater(t, preDDL.DdlJobId, int64(0))
require.Greater(t, preDDL.StartTs, int64(0))
require.Equal(t, int64(0), preDDL.CommitTs)
formatted, err := binloginfo.FormatAndAddTiDBSpecificComment(ddlQuery)
require.NoError(t, err, "ddlQuery: %s", ddlQuery)
require.Equal(t, formatted, string(preDDL.DdlQuery))
return
}
func checkBinlogCount(t *testing.T, pump *mockBinlogPump) {
var bin *binlog.Binlog
prewriteCount := 0
ddlCount := 0
pump.mu.Lock()
length := len(pump.mu.payloads)
for i := length - 1; i >= 0; i-- {
payload := pump.mu.payloads[i]
bin = new(binlog.Binlog)
err := bin.Unmarshal(payload)
require.NoError(t, err)
if bin.Tp == binlog.BinlogType_Prewrite {
if bin.DdlJobId != 0 {
ddlCount++
} else {
prewriteCount++
}
}
}
pump.mu.Unlock()
require.Greater(t, ddlCount, 0)
match := false
for i := 0; i < 10; i++ {
pump.mu.Lock()
length = len(pump.mu.payloads)
pump.mu.Unlock()
if (prewriteCount+ddlCount)*2 == length {
match = true
break
}
time.Sleep(time.Millisecond * 10)
}
require.True(t, match)
}
func mutationRowsToRows(t *testing.T, mutationRows [][]byte, columnValueOffsets ...int) [][]types.Datum {
var rows = make([][]types.Datum, 0)
for _, mutationRow := range mutationRows {
datums, err := codec.Decode(mutationRow, 5)
require.NoError(t, err)
for i := range datums {
if datums[i].Kind() == types.KindBytes {
datums[i].SetBytesAsString(datums[i].GetBytes(), mysql.DefaultCollationName, collate.DefaultLen)
}
}
row := make([]types.Datum, 0, len(columnValueOffsets))
for _, colOff := range columnValueOffsets {
row = append(row, datums[colOff])
}
rows = append(rows, row)
}
return rows
}
func TestBinlogForSequence(t *testing.T) {
s := createBinlogSuite(t)
tk := testkit.NewTestKit(t, s.store)
tk.MustExec("use test")
s.pump.mu.Lock()
s.pump.mu.payloads = s.pump.mu.payloads[:0]
s.pump.mu.Unlock()
tk.Session().GetSessionVars().BinlogClient = s.client
tk.MustExec("drop sequence if exists seq")
// the default start = 1, increment = 1.
tk.MustExec("create sequence seq cache 3")
// trigger the sequence cache allocation.
tk.MustQuery("select nextval(seq)").Check(testkit.Rows("1"))
sequenceTable := external.GetTableByName(t, tk, "test", "seq")
tc, ok := sequenceTable.(*tables.TableCommon)
require.Equal(t, true, ok)
_, end, round := tc.GetSequenceCommon().GetSequenceBaseEndRound()
require.Equal(t, int64(3), end)
require.Equal(t, int64(0), round)
// Check the sequence binlog.
// Got matched pre DDL and commit DDL.
ok = mustGetDDLBinlog(s, "select setval(`test`.`seq`, 3)", t)
require.True(t, ok)
// Invalidate the current sequence cache.
tk.MustQuery("select setval(seq, 5)").Check(testkit.Rows("5"))
// trigger the next sequence cache allocation.
tk.MustQuery("select nextval(seq)").Check(testkit.Rows("6"))
_, end, round = tc.GetSequenceCommon().GetSequenceBaseEndRound()
require.Equal(t, int64(8), end)
require.Equal(t, int64(0), round)
ok = mustGetDDLBinlog(s, "select setval(`test`.`seq`, 8)", t)
require.True(t, ok)
tk.MustExec("create database test2")
tk.MustExec("use test2")
tk.MustExec("drop sequence if exists seq2")
tk.MustExec("create sequence seq2 start 1 increment -2 cache 3 minvalue -10 maxvalue 10 cycle")
// trigger the sequence cache allocation.
tk.MustQuery("select nextval(seq2)").Check(testkit.Rows("1"))
sequenceTable = external.GetTableByName(t, tk, "test2", "seq2")
tc, ok = sequenceTable.(*tables.TableCommon)
require.Equal(t, true, ok)
_, end, round = tc.GetSequenceCommon().GetSequenceBaseEndRound()
require.Equal(t, int64(-3), end)
require.Equal(t, int64(0), round)
ok = mustGetDDLBinlog(s, "select setval(`test2`.`seq2`, -3)", t)
require.True(t, ok)
tk.MustQuery("select setval(seq2, -100)").Check(testkit.Rows("-100"))
// trigger the sequence cache allocation.
tk.MustQuery("select nextval(seq2)").Check(testkit.Rows("10"))
_, end, round = tc.GetSequenceCommon().GetSequenceBaseEndRound()
require.Equal(t, int64(6), end)
require.Equal(t, int64(1), round)
ok = mustGetDDLBinlog(s, "select setval(`test2`.`seq2`, 6)", t)
require.True(t, ok)
// Test dml txn is independent from sequence txn.
tk.MustExec("drop sequence if exists seq")
tk.MustExec("create sequence seq cache 3")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (a int default next value for seq)")
// sequence txn commit first then the dml txn.
tk.MustExec("insert into t values(-1),(default),(-1),(default)")
// binlog list like [... ddl prewrite(offset), ddl commit, dml prewrite, dml commit]
_, _, offset := getLatestDDLBinlog(t, s.pump, "select setval(`test2`.`seq`, 3)")
s.pump.mu.Lock()
require.Equal(t, len(s.pump.mu.payloads)-1, offset+3)
s.pump.mu.Unlock()
}
// Sometimes this test doesn't clean up fail, let the function name begin with 'Z'
// so it runs last and would not disrupt other tests.
func TestZIgnoreError(t *testing.T) {
s := createBinlogSuite(t)
tk := testkit.NewTestKit(t, s.store)
tk.MustExec("use test")
tk.Session().GetSessionVars().BinlogClient = s.client
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (id int)")
binloginfo.SetIgnoreError(true)
s.pump.mu.Lock()
s.pump.mu.mockFail = true
s.pump.mu.Unlock()
tk.MustExec("insert into t values (1)")
tk.MustExec("insert into t values (1)")
// Clean up.
s.pump.mu.Lock()
s.pump.mu.mockFail = false
s.pump.mu.Unlock()
binloginfo.DisableSkipBinlogFlag()
binloginfo.SetIgnoreError(false)
}
func TestPartitionedTable(t *testing.T) {
s := createBinlogSuite(t)
// This test checks partitioned table write binlog with table ID, rather than partition ID.
tk := testkit.NewTestKit(t, s.store)
tk.MustExec("use test")
tk.Session().GetSessionVars().BinlogClient = s.client
tk.MustExec("drop table if exists t")
tk.MustExec(`create table t (id int) partition by range (id) (
partition p0 values less than (1),
partition p1 values less than (4),
partition p2 values less than (7),
partition p3 values less than (10))`)
tids := make([]int64, 0, 10)
for i := 0; i < 10; i++ {
tk.MustExec("insert into t values (?)", i)
prewriteVal := getLatestBinlogPrewriteValue(t, s.pump)
tids = append(tids, prewriteVal.Mutations[0].TableId)
}
require.Equal(t, 10, len(tids))
for i := 1; i < 10; i++ {
require.Equal(t, tids[0], tids[i])
}
}
func TestPessimisticLockThenCommit(t *testing.T) {
s := createBinlogSuite(t)
tk := testkit.NewTestKit(t, s.store)
tk.MustExec("use test")
tk.Session().GetSessionVars().BinlogClient = s.client
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int, b int)")
tk.MustExec("begin pessimistic")
tk.MustExec("insert into t select 1, 1")
tk.MustExec("commit")
prewriteVal := getLatestBinlogPrewriteValue(t, s.pump)
require.Equal(t, 1, len(prewriteVal.Mutations))
}
func TestDeleteSchema(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("CREATE TABLE `b1` (`id` int(11) NOT NULL AUTO_INCREMENT, `job_id` varchar(50) NOT NULL, `split_job_id` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`), KEY `b1` (`job_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;")
tk.MustExec("CREATE TABLE `b2` (`id` int(11) NOT NULL AUTO_INCREMENT, `job_id` varchar(50) NOT NULL, `batch_class` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `bu` (`job_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4")
tk.MustExec("insert into b2 (job_id, batch_class) values (2, 'TEST');")
tk.MustExec("insert into b1 (job_id) values (2);")
// This test cover a bug that the final schema and the binlog row inconsistent.
// The final schema of this SQL should be the schema of table b1, rather than the schema of join result.
tk.MustExec("delete from b1 where job_id in (select job_id from b2 where batch_class = 'TEST') or split_job_id in (select job_id from b2 where batch_class = 'TEST');")
tk.MustExec("delete b1 from b2 right join b1 on b1.job_id = b2.job_id and batch_class = 'TEST';")
}
func TestFormatAndAddTiDBSpecificComment(t *testing.T) {
testCase := []struct {
input string
result string
}{
{
"create table t1 (id int ) shard_row_id_bits=2;",
"CREATE TABLE `t1` (`id` INT) /*T! SHARD_ROW_ID_BITS = 2 */;",
},
{
"create table t1 (id int ) shard_row_id_bits=2 pre_split_regions=2;",
"CREATE TABLE `t1` (`id` INT) /*T! SHARD_ROW_ID_BITS = 2 */ /*T! PRE_SPLIT_REGIONS = 2 */;",
},
{
"create table t1 (id int ) shard_row_id_bits=2 pre_split_regions=2;",
"CREATE TABLE `t1` (`id` INT) /*T! SHARD_ROW_ID_BITS = 2 */ /*T! PRE_SPLIT_REGIONS = 2 */;",
},
{
"create table t1 (id int ) shard_row_id_bits=2 engine=innodb pre_split_regions=2;",
"CREATE TABLE `t1` (`id` INT) /*T! SHARD_ROW_ID_BITS = 2 */ ENGINE = innodb /*T! PRE_SPLIT_REGIONS = 2 */;",
},
{
"create table t1 (id int ) pre_split_regions=2 shard_row_id_bits=2;",
"CREATE TABLE `t1` (`id` INT) /*T! PRE_SPLIT_REGIONS = 2 */ /*T! SHARD_ROW_ID_BITS = 2 */;",
},
{
"create table t6 (id int ) shard_row_id_bits=2 shard_row_id_bits=3 pre_split_regions=2;",
"CREATE TABLE `t6` (`id` INT) /*T! SHARD_ROW_ID_BITS = 2 */ /*T! SHARD_ROW_ID_BITS = 3 */ /*T! PRE_SPLIT_REGIONS = 2 */;",
},
{
"create table t1 (id int primary key auto_random(2));",
"CREATE TABLE `t1` (`id` INT PRIMARY KEY /*T![auto_rand] AUTO_RANDOM(2) */);",
},
{
"create table t1 (id int primary key auto_random);",
"CREATE TABLE `t1` (`id` INT PRIMARY KEY /*T![auto_rand] AUTO_RANDOM */);",
},
{
"create table t1 (id int auto_random ( 4 ) primary key);",
"CREATE TABLE `t1` (`id` INT /*T![auto_rand] AUTO_RANDOM(4) */ PRIMARY KEY);",
},
{
"create table t1 (id int auto_random ( 4 ) primary key);",
"CREATE TABLE `t1` (`id` INT /*T![auto_rand] AUTO_RANDOM(4) */ PRIMARY KEY);",
},
{
"create table t1 (id int auto_random ( 3 ) primary key) auto_random_base = 100;",
"CREATE TABLE `t1` (`id` INT /*T![auto_rand] AUTO_RANDOM(3) */ PRIMARY KEY) /*T![auto_rand_base] AUTO_RANDOM_BASE = 100 */;",
},
{
"create table t1 (id int auto_random primary key) auto_random_base = 50;",
"CREATE TABLE `t1` (`id` INT /*T![auto_rand] AUTO_RANDOM */ PRIMARY KEY) /*T![auto_rand_base] AUTO_RANDOM_BASE = 50 */;",
},
{
"create table t1 (id int auto_increment key) auto_id_cache 100;",
"CREATE TABLE `t1` (`id` INT AUTO_INCREMENT PRIMARY KEY) /*T![auto_id_cache] AUTO_ID_CACHE = 100 */;",
},
{
"create table t1 (id int auto_increment unique) auto_id_cache 10;",
"CREATE TABLE `t1` (`id` INT AUTO_INCREMENT UNIQUE KEY) /*T![auto_id_cache] AUTO_ID_CACHE = 10 */;",
},
{
"create table t1 (id int) auto_id_cache = 5;",
"CREATE TABLE `t1` (`id` INT) /*T![auto_id_cache] AUTO_ID_CACHE = 5 */;",
},
{
"create table t1 (id int) auto_id_cache=5;",
"CREATE TABLE `t1` (`id` INT) /*T![auto_id_cache] AUTO_ID_CACHE = 5 */;",
},
{
"create table t1 (id int) /*T![auto_id_cache] auto_id_cache=5 */ ;",
"CREATE TABLE `t1` (`id` INT) /*T![auto_id_cache] AUTO_ID_CACHE = 5 */;",
},
{
"create table t1 (id int, a varchar(255), primary key (a, b) clustered);",
"CREATE TABLE `t1` (`id` INT,`a` VARCHAR(255),PRIMARY KEY(`a`, `b`) /*T![clustered_index] CLUSTERED */);",
},
{
"create table t1(id int, v int, primary key(a) clustered);",
"CREATE TABLE `t1` (`id` INT,`v` INT,PRIMARY KEY(`a`) /*T![clustered_index] CLUSTERED */);",
},
{
"create table t1(id int primary key clustered, v int);",
"CREATE TABLE `t1` (`id` INT PRIMARY KEY /*T![clustered_index] CLUSTERED */,`v` INT);",
},
{
"alter table t add primary key(a) clustered;",
"ALTER TABLE `t` ADD PRIMARY KEY(`a`) /*T![clustered_index] CLUSTERED */;",
},
{
"create table t1 (id int, a varchar(255), primary key (a, b) nonclustered);",
"CREATE TABLE `t1` (`id` INT,`a` VARCHAR(255),PRIMARY KEY(`a`, `b`) /*T![clustered_index] NONCLUSTERED */);",
},
{
"create table t1 (id int, a varchar(255), primary key (a, b) /*T![clustered_index] nonclustered */);",
"CREATE TABLE `t1` (`id` INT,`a` VARCHAR(255),PRIMARY KEY(`a`, `b`) /*T![clustered_index] NONCLUSTERED */);",
},
{
"create table clustered_test(id int)",
"CREATE TABLE `clustered_test` (`id` INT);",
},
{
"create database clustered_test",
"CREATE DATABASE `clustered_test`;",
},
{
"create database clustered",
"CREATE DATABASE `clustered`;",
},
{
"create table clustered (id int)",
"CREATE TABLE `clustered` (`id` INT);",
},
{
"create table t1 (id int, a varchar(255) key clustered);",
"CREATE TABLE `t1` (`id` INT,`a` VARCHAR(255) PRIMARY KEY /*T![clustered_index] CLUSTERED */);",
},
{
"alter table t force auto_increment = 12;",
"ALTER TABLE `t` /*T![force_inc] FORCE */ AUTO_INCREMENT = 12;",
},
{
"alter table t force, auto_increment = 12;",
"ALTER TABLE `t` FORCE /* AlterTableForce is not supported */ , AUTO_INCREMENT = 12;",
},
{
// https://github.com/pingcap/tiflow/issues/3755
"create table cdc_test (id varchar(10) primary key ,c1 varchar(10)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin/*!90000 SHARD_ROW_ID_BITS=4 PRE_SPLIT_REGIONS=3 */",
"CREATE TABLE `cdc_test` (`id` VARCHAR(10) PRIMARY KEY,`c1` VARCHAR(10)) ENGINE = InnoDB DEFAULT CHARACTER SET = UTF8MB4 DEFAULT COLLATE = UTF8MB4_BIN /*T! SHARD_ROW_ID_BITS = 4 */ /*T! PRE_SPLIT_REGIONS = 3 */;",
},
{
"create table clustered (id int); create table t1 (id int, a varchar(255) key clustered); ",
"CREATE TABLE `clustered` (`id` INT);CREATE TABLE `t1` (`id` INT,`a` VARCHAR(255) PRIMARY KEY /*T![clustered_index] CLUSTERED */);",
},
{
"",
"",
},
{
";;",
"",
},
{
"alter table t cache",
"ALTER TABLE `t` CACHE;",
},
{
"alter table t nocache",
"ALTER TABLE `t` NOCACHE;",
},
}
for _, ca := range testCase {
re, err := binloginfo.FormatAndAddTiDBSpecificComment(ca.input)
require.Equal(t, ca.result, re)
require.NoError(t, err, "Unexpected error for AddTiDBSpecificComment, test input: %s", ca.input)
}
}
func mustGetDDLBinlog(s *binlogSuite, ddlQuery string, t *testing.T) (matched bool) {
for i := 0; i < 10; i++ {
preDDL, commitDDL, _ := getLatestDDLBinlog(t, s.pump, ddlQuery)
if preDDL != nil && commitDDL != nil {
if preDDL.DdlJobId == commitDDL.DdlJobId {
require.Equal(t, preDDL.StartTs, commitDDL.StartTs)
require.Greater(t, commitDDL.CommitTs, commitDDL.StartTs)
matched = true
break
}
}
time.Sleep(time.Millisecond * 30)
}
return
}
func TestTempTableBinlog(t *testing.T) {
s := createBinlogSuite(t)
tk := testkit.NewTestKit(t, s.store)
tk.MustExec("use test")
tk.Session().GetSessionVars().BinlogClient = s.client
tk.MustExec("begin")
tk.MustExec("drop table if exists temp_table")
ddlQuery := "create global temporary table temp_table(id int) on commit delete rows"
tk.MustExec(ddlQuery)
ok := mustGetDDLBinlog(s, ddlQuery, t)
require.True(t, ok)
tk.MustExec("insert temp_table value(1)")
tk.MustExec("update temp_table set id=id+1")
tk.MustExec("commit")
prewriteVal := getLatestBinlogPrewriteValue(t, s.pump)
require.Equal(t, 0, len(prewriteVal.Mutations))
tk.MustExec("begin")
tk.MustExec("delete from temp_table")
tk.MustExec("commit")
prewriteVal = getLatestBinlogPrewriteValue(t, s.pump)
require.Equal(t, 0, len(prewriteVal.Mutations))
ddlQuery = "truncate table temp_table"
tk.MustExec(ddlQuery)
ok = mustGetDDLBinlog(s, ddlQuery, t)
require.True(t, ok)
ddlQuery = "drop table if exists temp_table"
tk.MustExec(ddlQuery)
ok = mustGetDDLBinlog(s, ddlQuery, t)
require.True(t, ok)
// for local temporary table
latestNonLocalTemporaryTableDDL := ddlQuery
tk.MustExec("create temporary table l_temp_table(id int)")
// create temporary table do not write to bin log, so the latest ddl binlog is the previous one
ok = mustGetDDLBinlog(s, latestNonLocalTemporaryTableDDL, t)
require.True(t, ok)
tk.MustExec("insert l_temp_table value(1)")
prewriteVal = getLatestBinlogPrewriteValue(t, s.pump)
require.Equal(t, 0, len(prewriteVal.Mutations))
tk.MustExec("update l_temp_table set id=id+1")
prewriteVal = getLatestBinlogPrewriteValue(t, s.pump)
require.Equal(t, 0, len(prewriteVal.Mutations))
tk.MustExec("delete from l_temp_table")
prewriteVal = getLatestBinlogPrewriteValue(t, s.pump)
require.Equal(t, 0, len(prewriteVal.Mutations))
tk.MustExec("begin")
tk.MustExec("insert l_temp_table value(1)")
tk.MustExec("update l_temp_table set id=id+1")
tk.MustExec("commit")
prewriteVal = getLatestBinlogPrewriteValue(t, s.pump)
require.Equal(t, 0, len(prewriteVal.Mutations))
tk.MustExec("begin")
tk.MustExec("delete from l_temp_table")
tk.MustExec("commit")
prewriteVal = getLatestBinlogPrewriteValue(t, s.pump)
require.Equal(t, 0, len(prewriteVal.Mutations))
tk.MustExec("truncate table l_temp_table")
ok = mustGetDDLBinlog(s, latestNonLocalTemporaryTableDDL, t)
require.True(t, ok)
tk.MustExec("drop table l_temp_table")
ok = mustGetDDLBinlog(s, latestNonLocalTemporaryTableDDL, t)
require.True(t, ok)
}
func TestAlterTableCache(t *testing.T) {
s := createBinlogSuite(t)
// Don't write binlog for 'ALTER TABLE t CACHE|NOCACHE'.
// Cached table is regarded as normal table.
tk := testkit.NewTestKit(t, s.store)
tk.MustExec("use test")
tk.Session().GetSessionVars().BinlogClient = s.client
tk.MustExec("drop table if exists t")
ddlQuery := "create table t (id int)"
tk.MustExec(ddlQuery)
tk.MustExec(`alter table t cache`)
// The latest DDL is still the previous one.
getLatestDDLBinlog(t, s.pump, ddlQuery)
tk.MustExec("insert into t values (?)", 666)
prewriteVal := getLatestBinlogPrewriteValue(t, s.pump)
require.Equal(t, 1, len(prewriteVal.Mutations))
tk.MustExec(`alter table t nocache`)
getLatestDDLBinlog(t, s.pump, ddlQuery)
}
func TestIssue28292(t *testing.T) {
s := createBinlogSuite(t)
tk := testkit.NewTestKit(t, s.store)
tk.MustExec("use test")
tk.Session().GetSessionVars().BinlogClient = s.client
tk.MustExec("set @@tidb_txn_mode = 'pessimistic'")
tk.MustExec(`CREATE TABLE xxx (
machine_id int(11) DEFAULT NULL,
date datetime DEFAULT NULL,
code int(11) DEFAULT NULL,
value decimal(20,3) DEFAULT NULL,
KEY stat_data_index1 (machine_id,date,code)
) PARTITION BY RANGE ( TO_DAYS(date) ) (
PARTITION p0 VALUES LESS THAN (TO_DAYS('2021-09-04')),
PARTITION p1 VALUES LESS THAN (TO_DAYS('2021-09-19')),
PARTITION p2 VALUES LESS THAN (TO_DAYS('2021-10-04')),
PARTITION p3 VALUES LESS THAN (TO_DAYS('2021-10-19')),
PARTITION p4 VALUES LESS THAN (TO_DAYS('2021-11-04')))`)
tk.MustExec("INSERT INTO xxx value(123, '2021-09-22 00:00:00', 666, 123.24)")
tk.MustExec("BEGIN")
// No panic.
tk.MustExec("DELETE FROM xxx WHERE machine_id = 123 and date = '2021-09-22 00:00:00'")
tk.MustExec("COMMIT")
}
|
// SPDX-License-Identifier: Unlicense OR MIT
package headless
import (
"image"
"image/color"
"testing"
"github.com/gop9/olt/gio/f32"
"github.com/gop9/olt/gio/op"
"github.com/gop9/olt/gio/op/paint"
)
func TestHeadless(t *testing.T) {
sz := image.Point{X: 800, Y: 600}
w, err := NewWindow(sz.X, sz.Y)
if err != nil {
t.Skipf("headless windows not supported: %v", err)
}
col := color.RGBA{A: 0xff, R: 0xcc, G: 0xcc}
var ops op.Ops
paint.ColorOp{Color: col}.Add(&ops)
// Paint only part of the screen to avoid the glClear optimization.
paint.PaintOp{Rect: f32.Rectangle{Max: f32.Point{
X: float32(sz.X) - 100,
Y: float32(sz.Y) - 100,
}}}.Add(&ops)
w.Frame(&ops)
img, err := w.Screenshot()
if err != nil {
t.Fatal(err)
}
if isz := img.Bounds().Size(); isz != sz {
t.Errorf("got %v screenshot, expected %v", isz, sz)
}
if got := img.RGBAAt(0, 0); got != col {
t.Errorf("got color %v, expected %v", got, col)
}
}
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-10-14 09:00
# @File : lt_81_Search_in_Rotated_Sorted_Array_II.go
# @Description :
# @Attention :
*/
package array
import (
"fmt"
"testing"
)
func Test_search(t *testing.T) {
a := []int{5,1,3}
target := 3
b := search(a, target)
fmt.Println(b)
}
|
package fastpbkdf2
/*
#cgo CFLAGS: -std=c99 -O3
#cgo LDFLAGS: -lcrypto
#include "fastpbkdf2.h"
*/
import "C"
import (
"bytes"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"fmt"
"hash"
"unsafe"
)
// go doesn't appear to make this easy :(
// we compare hashes of the empty string
func sameHash(a, b func() hash.Hash) bool {
ha := a().Sum(make([]byte, 0))
hb := b().Sum(make([]byte, 0))
return bytes.Equal(ha, hb)
}
func Key(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
output := make([]byte, keyLen)
if keyLen == 0 {
return output
}
// convert arguments to C types; note that &slice[0] is illegal for empty slices
var c_password, c_salt, c_output *C.uint8_t
if len(password) != 0 {
c_password = (*C.uint8_t)(unsafe.Pointer(&password[0]))
} else {
c_password = (*C.uint8_t)(nil)
}
if len(salt) != 0 {
c_salt = (*C.uint8_t)(unsafe.Pointer(&salt[0]))
} else {
c_salt = (*C.uint8_t)(nil)
}
c_output = (*C.uint8_t)(unsafe.Pointer(&output[0]))
if sameHash(h, sha1.New) {
C.fastpbkdf2_hmac_sha1(c_password, C.size_t(len(password)),
c_salt, C.size_t(len(salt)),
C.uint32_t(iter),
c_output, C.size_t(keyLen))
} else if sameHash(h, sha256.New) {
C.fastpbkdf2_hmac_sha256(c_password, C.size_t(len(password)),
c_salt, C.size_t(len(salt)),
C.uint32_t(iter),
c_output, C.size_t(keyLen))
} else if sameHash(h, sha512.New) {
C.fastpbkdf2_hmac_sha512(c_password, C.size_t(len(password)),
c_salt, C.size_t(len(salt)),
C.uint32_t(iter),
c_output, C.size_t(keyLen))
} else {
panic(fmt.Sprintf("Hash function %v not supported (only sha1.New, sha256.New or sha512.New)", h))
}
return output
}
|
package main
import (
"fmt"
"runtime"
)
/*
Concurrency VS Parallelism
Concurrency is an architecture. Basically a way of programming to support parallelism
Parallelism is when multiple programs are running parallely
So if there are multiple CPUs(or cores), A Concurrent program will achieve parallelism
but if there is only one CPU, even a Concurrent program will not run parallely
*/
func main() {
fmt.Println("System Details ::")
fmt.Println("\t OS ::", runtime.GOOS)
fmt.Println("\t Architecture ::", runtime.GOARCH)
fmt.Println("\t CPUs ::", runtime.NumCPU())
fmt.Println("\t GoRoutines ::", runtime.NumGoroutine())
// to run something in parallel, use "go" keyword
go foo()
bar()
fmt.Println("\t GoRoutines ::", runtime.NumGoroutine())
}
func foo() {
for i := 0; i < 10; i++ {
fmt.Println("foo :", i)
}
}
func bar() {
for i := 0; i < 100; i++ {
fmt.Println("bar :", i)
}
}
|
package main
import (
"errors"
"fmt"
"io/ioutil"
"os/exec"
"gopkg.in/yaml.v2"
)
// Creates a gopack.yml example file
func genFile() {
out, _ := exec.Command("go", "version").Output()
outString := string(out[13:17])
testfile := goPack{
GoVersion: outString}
err := saveFile(testfile)
check(err, "Failed to generate gopack.yml")
fmt.Println("Created gopack.yml")
}
// Loads a gopack.yml file
func loadFile() (goPack, error) {
f, readErr := ioutil.ReadFile("./gopack.yml")
var goFile goPack
marshErr := yaml.Unmarshal(f, &goFile)
if marshErr != nil || readErr != nil {
return goPack{}, errors.New("Failed to load file")
}
return goFile, nil
}
// Saves gopack.yml
func saveFile(goFile goPack) error {
yamlData, marshErr := yaml.Marshal(goFile)
check(marshErr, "Failed to Convert to Yaml")
writeErr := ioutil.WriteFile("./gopack.yml", yamlData, 0644)
if marshErr != nil || writeErr != nil {
return errors.New("Failed to save file")
}
return nil
}
|
package fuzztime
import "time"
// FuzzTime is a very simple fuzzing function
func FuzzTime(data []byte) int {
_, err := time.ParseDuration(string(data))
if err != nil {
return 1
}
return 0
}
|
package main
import (
"crypto/sha256"
"encoding/base64"
"fmt"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
func InitDb() *gorm.DB {
var err error
db, err := gorm.Open("postgres", "host=127.0.0.1 user=postgres dbname=profileapi sslmode=disable password=profileapi")
if err != nil {
fmt.Println(err)
} else {
fmt.Println("Connection Success!")
}
return db
}
type Profile struct {
ID uint `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
Token string `json:"token"`
}
func main() {
migrate()
r := gin.Default()
r.POST("/profile", CreateProfile)
r.Use(Middleware)
r.GET("/profile/:id", ReadProfile)
r.GET("/profile", ReadProfiles)
r.PUT("/profile/:id", UpdateProfile)
r.DELETE("/profile/:id", DeleteProfile)
r.Run(":8080")
}
func migrate() {
var profile Profile
db := InitDb()
defer db.Close()
db.AutoMigrate(&profile)
}
func ReadProfile(c *gin.Context) {
var profile Profile
db := InitDb()
id := c.Params.ByName("id")
if err := db.Where("id = ?", id).First(&profile).Error; err != nil {
fmt.Println(err)
}
profile.Token = ""
c.JSON(200, profile)
}
func ReadProfiles(c *gin.Context) {
var profile []Profile
db := InitDb()
defer db.Close()
if err := db.Find(&profile).Error; err != nil {
fmt.Println(err)
}
for _, p := range profile {
p.Token = ""
}
c.JSON(200, profile)
}
func CreateProfile(c *gin.Context) {
var profile Profile
db := InitDb()
defer db.Close()
c.BindJSON(&profile)
profile.Token = GenerateToken("Ini adalah combination string yang akan dibuat token serta harusnya ditambahi dengan salt, bisa diambil dari combinasi data nama atau apapun")
db.Create(&profile)
c.JSON(200, profile)
}
func UpdateProfile(c *gin.Context) {
var profile Profile
db := InitDb()
defer db.Close()
id := c.Params.ByName("id")
if err := db.Where("id = ?", id).First(&profile).Error; err != nil {
fmt.Println(err)
}
c.BindJSON(&profile)
db.Save(&profile)
profile.Token = ""
c.JSON(200, profile)
}
func DeleteProfile(c *gin.Context) {
var profile Profile
db := InitDb()
defer db.Close()
id := c.Params.ByName("id")
if err := db.Where("id = ?", id).Delete(&profile).Error; err != nil {
fmt.Println(err)
}
c.JSON(200, gin.H{"Account ID : " + id: " deleted."})
}
func GenerateToken(text string) string {
encoded := base64.StdEncoding.EncodeToString([]byte(text))
h := sha256.New()
h.Write([]byte(encoded))
var sha = h.Sum(nil)
var token = base64.StdEncoding.EncodeToString([]byte(sha))
return token
}
func Middleware(c *gin.Context) {
var profile Profile
db := InitDb()
defer db.Close()
token := c.Request.Header.Get("token")
if token == "" {
data := map[string]interface{}{
"Message": "Token Required",
}
c.AbortWithStatusJSON(400, data)
return
}
if err := db.Where("token = ?", token).First(&profile).Error; err != nil {
data := map[string]interface{}{
"Message": "You have no authorization",
}
c.AbortWithStatusJSON(400, data)
return
}
c.Next()
}
|
package main
import (
"fmt"
//"strconv"
)
func main() {
n := 37
k := 3
mask := ^(1 << uint(k-1))
n &= mask
fmt.Println(n)
}
|
package sdkconnector
import (
"path/filepath"
"strings"
"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)
//CreateSDKInstance creates SDK instance for given organization.
func CreateSDKInstance(orgName string) (*fabsdk.FabricSDK, error) {
configpath := filepath.Join("configs", strings.ToLower(orgName)+"config.yaml")
config := config.FromFile(configpath)
sdk, err := fabsdk.New(config)
return sdk, err
}
|
// netconfs project main.go
package main
func main() {
local := new(NetConfSData)
local.Init()
netConfInit(&local.config)
}
|
package awsclient
import (
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
)
type media struct {
cmsId string
pHash string
createdAt string
}
func TestS3Client_Success(t *testing.T) {
dummyFiles := map[string]interface{}{
"avod/mediaId-0": struct{ cmsId string }{"A"},
"avod/mediaId-1": media{cmsId: "A", pHash: "abcd-12345", createdAt: "01/01/2021"},
"avod/mediaId-2": media{cmsId: "B", pHash: "abcd-1234", createdAt: "02/02/2021"},
"svod/mediaId-0": struct{ cmsId string }{"A"},
"svod/mediaId-1": media{cmsId: "A", pHash: "abcd-12345", createdAt: "01/01/2021"},
"svod/mediaId-2": media{cmsId: "B", pHash: "abcd-1234", createdAt: "02/02/2021"},
}
mS3 := mockS3Client{files: dummyFiles}
var getInput *s3.GetObjectInput
var getOutput *s3.GetObjectOutput
var err error
getInput = &s3.GetObjectInput{Bucket: aws.String("avod"), Key: aws.String("mediaId-1")}
getOutput, err = mS3.GetObject(getInput)
if err != nil {
t.Fatalf("S3:GetObject response has error: %v", err)
}
if len(*getOutput.ETag) == 0 {
t.Fatalf("S3:GetObject response has empty etag: %v", *getOutput)
}
if *getOutput.ContentLength == 0 {
t.FailNow()
}
getInput = &s3.GetObjectInput{Bucket: aws.String("avod"), Key: aws.String("mediaId-0")}
getOutput, err = mS3.GetObject(getInput)
if err != nil {
t.Fatalf("S3:GetObject response has error: %v", err)
}
if len(*getOutput.ETag) == 0 {
t.Fatalf("S3:GetObject response has empty etag: %v", *getOutput)
}
if *getOutput.ContentLength == 0 {
t.FailNow()
}
getInput = &s3.GetObjectInput{Bucket: aws.String("svod"), Key: aws.String("mediaId-1")}
getOutput, err = mS3.GetObject(getInput)
if err != nil {
t.Fatalf("S3:GetObject response has error: %v", err)
}
if len(*getOutput.ETag) == 0 {
t.Fatalf("S3:GetObject response has empty etag: %v", *getOutput)
}
if *getOutput.ContentLength == 0 {
t.FailNow()
}
getInput = &s3.GetObjectInput{Bucket: aws.String("svod"), Key: aws.String("mediaId-0")}
getOutput, err = mS3.GetObject(getInput)
if err != nil {
t.Fatalf("S3:GetObject response has error: %v", err)
}
if len(*getOutput.ETag) == 0 {
t.Fatalf("S3:GetObject response has empty etag: %v", *getOutput)
}
if *getOutput.ContentLength == 0 {
t.FailNow()
}
}
func TestS3Client_Failure(t *testing.T) {
dummyFiles := map[string]interface{}{
"avod/mediaId-0": struct{ cmsId string }{"A"},
"avod/mediaId-1": media{cmsId: "A", pHash: "abcd-12345", createdAt: "01/01/2021"},
"avod/mediaId-2": media{cmsId: "B", pHash: "abcd-1234", createdAt: "02/02/2021"},
"svod/mediaId-0": struct{ cmsId string }{"A"},
"svod/mediaId-1": media{cmsId: "A", pHash: "abcd-12345", createdAt: "01/01/2021"},
"svod/mediaId-2": media{cmsId: "B", pHash: "abcd-1234", createdAt: "02/02/2021"},
}
mS3 := mockS3Client{files: dummyFiles}
var getInput *s3.GetObjectInput
var err error
getInput = &s3.GetObjectInput{Bucket: aws.String("avod"), Key: aws.String("mediaId-3")}
_, err = mS3.GetObject(getInput)
// this should fail, as the key is not present
if err == nil {
t.FailNow()
}
getInput = &s3.GetObjectInput{Bucket: aws.String("avod"), Key: aws.String("mediaId-3"), Range: aws.String("0-10")}
_, err = mS3.GetObject(getInput)
// this should fail, as the key is not present
if err == nil {
t.FailNow()
}
}
|
package gui
import (
"github.com/andlabs/ui"
)
func addTasksInput() {
/*
window
groupcontainer
formgroup
radiogroup
o
o
o
buttonscontainer
buttons
*/
window := ui.NewWindow("supatc - Add Tasks", 300, 600, false)
window.SetMargined(true)
window.OnClosing(func(*ui.Window) bool {
return true
})
windowContainer := ui.NewVerticalBox()
windowContainer.SetPadded(true)
window.SetChild(windowContainer)
formGroup := ui.NewGroup("tasks")
formGroup.SetMargined(true)
formGroupContainer := ui.NewVerticalBox()
formGroup.SetChild(formGroupContainer)
windowContainer.Append(formGroup, false)
entryForm := ui.NewForm()
entryForm.SetPadded(true)
formGroupContainer.Append(entryForm, false)
entryForm.Append("Product keywords", ui.NewEntry(), false)
entryForm.Append("Color keywords", ui.NewEntry(), false)
entryForm.Append("Proxy", ui.NewEntry(), false)
size := ui.NewCombobox()
size.Append("S")
size.Append("M")
size.Append("L")
entryForm.Append("Size", size, false)
profile := ui.NewCombobox()
profile.Append("TODO: Fill this with profiles")
entryForm.Append("Profile", profile, false)
checkout := ui.NewRadioButtons()
checkout.Append("Lightning")
checkout.Append("Anti-Bot")
checkoutContainer := ui.NewVerticalBox()
checkoutContainer.Append(checkout, false)
formGroupContainer.Append(checkoutContainer, false)
buttonsContainer := ui.NewHorizontalBox()
buttonsContainer.SetPadded(true)
submit := ui.NewButton("Add")
submit.OnClicked(func(*ui.Button) {
window.Destroy()
})
cancel := ui.NewButton("Cancel")
cancel.OnClicked(func(*ui.Button) {
window.Destroy()
})
buttonsContainer.Append(submit, false)
buttonsContainer.Append(cancel, false)
windowContainer.Append(buttonsContainer, false)
window.Show()
}
// func addTasksInput() {
// window := ui.NewWindow("supatc - Add Tasks", 300, 600, false)
// vbox := ui.NewVerticalBox()
// group := ui.NewGroup("Add new tasks, separate keywords with ;")
// group.SetMargined(true)
// form := ui.NewForm()
// form.SetPadded(true)
// form.Append("Product keywords", ui.NewEntry(), false)
// form.Append("Color keywords", ui.NewEntry(), false)
// form.Append("Proxy", ui.NewEntry(), false)
// size := ui.NewCombobox()
// size.Append("S")
// size.Append("M")
// size.Append("L")
// form.Append("Size", size, false)
// profile := ui.NewCombobox()
// profile.Append("TODO: Fill this with profiles")
// form.Append("Profile", profile, false)
// checkout := ui.NewRadioButtons()
// checkout.Append("Lightning")
// checkout.Append("Anti-Bot")
// // TODO bug label shows bottom button instead of top
// form.Append("Checkout Type", checkout, false)
// profile = ui.NewCombobox()
// profile.Append("TODO: Fill this with profiles")
// form.Append("Profile", profile, false)
// group.SetChild(form)
// vbox.Append(group, true)
// hbox := ui.NewHorizontalBox()
// hbox.SetPadded(true)
// submit := ui.NewButton("Add")
// submit.OnClicked(func(*ui.Button) {
// window.Destroy()
// })
// cancel := ui.NewButton("Cancel")
// cancel.OnClicked(func(*ui.Button) {
// window.Destroy()
// })
// hbox.Append(submit, false)
// hbox.Append(cancel, false)
// vbox.Append(hbox, false)
// window.SetMargined(true)
// window.SetChild(vbox)
// window.OnClosing(func(*ui.Window) bool {
// return true
// })
// window.Show()
// }
|
// +build test
package db
import (
"re/db/client"
"re/db/form"
"gorm.io/gorm"
)
var db = client.DB
/*
初始化业务数据用于演示
标记说明:
<*> 表示对外(对运营)暴露,否则是中间变量
(1) 圆括号后面接因子的操作符函数
三个域:
下订单(事件初始域)
顾客ID(用户)
商家ID(用户)
<*>消费金额
(1) 和上一次消费金额相同
购买物品ID(商品)
用户域
ID
<*>信用分
(2) 高于百分之 {} 的用户
<*>本月消费金额列表
(3) 平均值小于 {}
商品域
ID
<*>商品月销量
(4) 大于等于 {} 且小于 {}
*/
func init() {
// event
db.Create(&form.Event{gorm.Model{ID: 1}, "下订单"})
// event domain
db.Create(&form.Domain{gorm.Model{ID: 1}, "下订单"})
{
{ //factor
db.Create(&form.Factor{
Domain: 1,
Code: "consumer_id",
Model: gorm.Model{ID: 1},
Name: "顾客ID",
Constructor: "",
})
db.Create(&form.Factor{
Domain: 1,
Code: "seller_id",
Model: gorm.Model{ID: 2},
Name: "商家ID",
Constructor: "",
})
db.Create(&form.Factor{
Domain: 1,
Code: "amount",
Model: gorm.Model{ID: 3},
Name: "消费金额",
Constructor: "",
})
{ // operation
db.Create(&form.Operation{
Model: gorm.Model{ID: 1},
View: `和上一次消费金额相同`,
Script: `
subDomain := domain("user domain1")
list := factor(subDomain, "ConsumptionAmountListMonth")
if len(list) > 0 {
output = list[0] == self
}else{
output = false
}
`,
})
db.Create(&form.RelFactorOperation{OperationID: 1, FactorID: 3})
}
db.Create(&form.Factor{
Domain: 1,
Code: "commodity_id",
Model: gorm.Model{ID: 4},
Name: "购买物品ID",
Constructor: "",
})
}
// rel event domain
db.Create(&form.RelEventDomain{
EventID: 1,
DomainID: 1,
Constructor: `
output = {
consumer_id: input.consumer_id,
seller_id: input.seller_id,
amount: input.amount,
commodity_id: input.commodity_id
}`,
})
{ //bridge
db.Create(&form.DomainBridge{1, 2, "顾客指向的用户域", "user domain1", `
output = {id: factor(this, "consumer_id")}
`})
db.Create(&form.DomainBridge{1, 2, "商家指向的用户域", "user domain2", `
output = {id: factor(this, "seller_id")}
`})
db.Create(&form.DomainBridge{1, 3, "购买物品指向的商品域", "commodity domain", `
output = {id: factor(this, "commodity_id"), monthly_sales: 188}
`})
}
}
db.Create(&form.Domain{gorm.Model{ID: 2}, "用户"})
{ //factor
db.Create(&form.Factor{
Domain: 2,
Code: "id",
Model: gorm.Model{ID: 5},
Name: "ID",
Constructor: "",
})
db.Create(&form.Factor{
Domain: 2,
Code: "CreditScore",
Model: gorm.Model{ID: 6},
Name: "信用分",
Constructor: "output = 100", // TODO, 这里应该是 rpc 调用结果
})
{ // operation
db.Create(&form.Operation{
Model: gorm.Model{ID: 2},
View: `高于百分之 {type: "int", placeholder: "占比"} 的用户`,
Script: "output = true", // TODO, 这里应该是 rpc 调用结果
})
db.Create(&form.RelFactorOperation{OperationID: 2, FactorID: 6})
}
db.Create(&form.Factor{
Domain: 2,
Code: "ConsumptionAmountListMonth",
Model: gorm.Model{ID: 7},
Name: "本月消费金额列表",
Constructor: `
// result := rpc.call(PSM, {params})
// output = ...
output = [200,100,150]`, // TODO, 这里应该是 rpc 调用结果
})
{ // operation
db.Create(&form.Operation{
Model: gorm.Model{ID: 3},
View: `平均值小于 {type: "int", placeholder: "数量"}`,
Script: `
n := 0
for v in self{
n += v
}
n /= len(self)
output = n < args[0]
`,
})
db.Create(&form.RelFactorOperation{OperationID: 3, FactorID: 7})
}
}
db.Create(&form.Domain{gorm.Model{ID: 3}, "商品"})
{ //factor
db.Create(&form.Factor{
Domain: 3,
Code: "id",
Model: gorm.Model{ID: 8},
Name: "ID",
Constructor: "",
})
db.Create(&form.Factor{
Domain: 3,
Code: "monthly_sales",
Model: gorm.Model{ID: 9},
Name: "商品月销量",
Constructor: "",
})
{ // operation
db.Create(&form.Operation{
Model: gorm.Model{ID: 4},
View: `大于等于 {type: "int", placeholder: "数字1"} 且小于 {type: "int", placeholder: "数字2"}`,
Script: "output = (self >= args[0] && self < args[1])",
})
db.Create(&form.RelFactorOperation{OperationID: 4, FactorID: 9})
}
}
}
|
package driver
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"github.com/5xxxx/pie/schemas"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Client interface {
// FindPagination find
FindPagination(page, count int64, doc interface{}, ctx ...context.Context) error
FindOneAndReplace(doc interface{}, ctx ...context.Context) error
FindOneAndUpdate(doc interface{}, ctx ...context.Context) (*mongo.SingleResult, error)
FindAndDelete(doc interface{}, ctx ...context.Context) error
FindOne(doc interface{}, ctx ...context.Context) error
FindAll(docs interface{}, ctx ...context.Context) error
RegexFilter(key, pattern string) Session
Distinct(doc interface{}, columns string, ctx ...context.Context) ([]interface{}, error)
FindOneAndUpdateBson(coll interface{}, bson interface{}, ctx ...context.Context) (*mongo.SingleResult, error)
// InsertOne insert
InsertOne(v interface{}, ctx ...context.Context) (primitive.ObjectID, error)
InsertMany(v interface{}, ctx ...context.Context) (*mongo.InsertManyResult, error)
BulkWrite(docs interface{}, ctx ...context.Context) (*mongo.BulkWriteResult, error)
ReplaceOne(doc interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)
// Update update
Update(bean interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)
// UpdateMany The following operation updates all of the documents with quantity value less than 50.
UpdateMany(bean interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)
UpdateOneBson(coll interface{}, bson interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)
UpdateManyBson(coll interface{}, bson interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)
// SoftDeleteOne delete
SoftDeleteOne(filter interface{}, ctx ...context.Context) error
SoftDeleteMany(filter interface{}, ctx ...context.Context) error
DeleteOne(filter interface{}, ctx ...context.Context) (*mongo.DeleteResult, error)
DeleteMany(filter interface{}, ctx ...context.Context) (*mongo.DeleteResult, error)
// DataBase db operation
DataBase() *mongo.Database
// Collection(name string, db ...string) *mongo.Collection
Collection(name string, collOpts []*options.CollectionOptions, db ...string) *mongo.Collection
Ping() error
Connect(ctx ...context.Context) (err error)
Disconnect(ctx ...context.Context) error
// Soft filter
Soft(s bool) Session
FilterBy(object interface{}) Session
Filter(key string, value interface{}) Session
Asc(colNames ...string) Session
Eq(key string, value interface{}) Session
Ne(key string, ne interface{}) Session
Nin(key string, nin interface{}) Session
Nor(c Condition) Session
Exists(key string, exists bool, filter ...Condition) Session
Type(key string, t interface{}) Session
Expr(filter Condition) Session
Regex(key string, value string) Session
ID(id interface{}) Session
Gt(key string, value interface{}) Session
Gte(key string, value interface{}) Session
Lt(key string, value interface{}) Session
Lte(key string, value interface{}) Session
In(key string, value interface{}) Session
And(filter Condition) Session
Not(key string, value interface{}) Session
Or(filter Condition) Session
Limit(limit int64) Session
Skip(skip int64) Session
Count(i interface{}, ctx ...context.Context) (int64, error)
Desc(s1 ...string) Session
FilterBson(d bson.D) Session
// NewIndexes indexes
NewIndexes() Indexes
DropAll(doc interface{}, ctx ...context.Context) error
DropOne(doc interface{}, name string, ctx ...context.Context) error
AddIndex(keys interface{}, opt ...*options.IndexOptions) Indexes
// NewSession session
NewSession() Session
Aggregate() Aggregate
// CollectionNameForStruct SetDatabase(string string) Client
CollectionNameForStruct(doc interface{}) (*schemas.Collection, error)
CollectionNameForSlice(doc interface{}) (*schemas.Collection, error)
Transaction(ctx context.Context, f schemas.TransFunc) error
TransactionWithOptions(ctx context.Context, f schemas.TransFunc, opt ...*options.SessionOptions) error
}
|
package models
import (
"strings"
"github.com/jmoiron/sqlx"
)
func chanteyQuery(db *sqlx.DB, sql, searchString string) ([]Chantey, error) {
result := []Chantey{}
err := db.Select(&result, sql, searchString)
return result, err
}
// ChanteyByID returns a list of chanteys that have IDs like the search term.
func ChanteyByID(db *sqlx.DB, idString string) ([]Chantey, error) {
return chanteyQuery(
db,
`SELECT * FROM chantey WHERE id LIKE $1;`,
dbSearchString(strings.ToUpper(nonIDCharRegex.ReplaceAllString(idString, ""))),
)
}
// ChanteyByName returns a list of chanteys that have names like the search term.
func ChanteyByName(db *sqlx.DB, nameString string) ([]Chantey, error) {
return chanteyQuery(
db,
`SELECT * FROM chantey WHERE name LIKE $1;`,
dbSearchString(nameString),
)
}
// ChanteyByCollectionID returns a list of chanteys that have an exact match on collection ID.
func ChanteyByCollectionID(db *sqlx.DB, collectionID string) ([]Chantey, error) {
return chanteyQuery(
db,
`SELECT * FROM chantey WHERE collection_id = $1 ORDER BY collection_location;`,
strings.ToUpper(collectionID),
)
}
|
package main
import (
"fmt"
"math/rand"
"reflect"
"time"
"github.com/nervelife/learning-golang/src/app/data"
"github.com/nervelife/learning-golang/src/app/server"
)
func main() {
fmt.Println("Hello World!")
main2()
main3()
main4()
fmt.Println(getFourNumbers())
main5()
server.Run()
}
func main2() {
var name string
name = "Yasser"
name1 := "Harbi"
name2 := new(string)
name2 = &name1
name3 := &name
x := 42
y := float32(43.3)
z := bool(false)
fmt.Println(name, name1, *name2, *name3, x, y, z)
fmt.Println(reflect.TypeOf(name).Kind(), reflect.TypeOf(name1).Kind(), reflect.TypeOf(name2).Kind(),
reflect.TypeOf(name3).Kind(), reflect.TypeOf(x).Kind(), reflect.TypeOf(y).Kind(), reflect.TypeOf(z).Kind())
}
func main3() {
var array1 []string
array2 := make([]string, 5)
array2[0] = "1"
array2[1] = "2"
array2[2] = "3"
array2[4] = "4"
array3 := []string{"One", "Two", "Three", "Four"}
array1 = append(array2, array3...)
fmt.Println(array1, array2, array3)
}
type person struct {
name string
age int
married bool
}
func main4() {
b := &person{
name: "Yasser",
age: 43,
married: false,
}
c := *b
c.age = 50
fmt.Println(b, c)
c.breakIt()
justBreakIt(b)
}
func (p *person) breakIt() {
if p.married {
fmt.Println("Broken..", p.name)
} else {
fmt.Println("Poor guy can't break it ", p.name)
}
}
func getFourNumbers() (x, y, z, o int64) {
rand.Seed(time.Now().UnixNano())
xx := rand.Int63n(10)
yy := rand.Int63n(10) + 10
zz := rand.Int63n(10) + 20
oo := rand.Int63n(10) + 30
return xx, yy, zz, oo
}
type breakble interface {
breakIt()
}
func justBreakIt(b breakble) {
fmt.Println("I'm going to break you ")
b.breakIt()
}
func main5() {
m := data.Maxy{
Planet: "Mars",
Size: 8,
}
m.CalcDistance()
}
|
package ice
import "errors"
var (
errCheckRetry = errors.New("retry again")
errTriedTooManyTimes = errors.New("have tried too many times")
errInvalidStunMessage = errors.New("Invalid STUN message")
errStunInvalidLength = errors.New("Invalid STUN message length")
errStunUnknownType = errors.New("Invalid or unexpected STUN message type")
errStunTimeout = errors.New("STUN transaction has timed out")
errStunTooManyAttributes = errors.New("Too many STUN attributes")
errStunAttributeLength = errors.New("Invalid STUN attribute length")
)
|
package banner
import (
"fmt"
"github.com/iotaledger/hive.go/node"
)
// PluginName is the name of the banner plugin.
const PluginName = "Banner"
const (
// AppVersion version number
AppVersion = "v0.1.0"
// AppName app code name
AppName = "Wasp"
)
func Init() *node.Plugin {
return node.NewPlugin(PluginName, node.Enabled, configure, run)
}
func configure(ctx *node.Plugin) {
fmt.Printf(`
__ __
\ \ / /
\ \ /\ / /_ _ ___ _ __
\ \/ \/ / _| / __| |_ \
\ /\ / (_| \__ \ |_) |
\/ \/ \__,_|___/ |__/
| |
|_|
%s
`, AppVersion)
fmt.Println()
// TODO embed build time see https://stackoverflow.com/questions/53031035/generate-build-timestamp-in-go/53045029
ctx.Node.Logger.Info("Loading plugins ...")
}
func run(_ *node.Plugin) {
}
|
package limit_ip
import (
"fmt"
"strconv"
"sync"
"sync/atomic"
"testing"
)
func TestLimitIp_IsInvalid(t *testing.T) {
limitIp := &LimitIp{}
var res int64 = 0
var wg sync.WaitGroup
for i := 0; i < 1000; i ++ {
if i == 3 {
//time.Sleep(time.Second * 11)
}
//time.Sleep(time.Second)
for j := 0; j < 100; j ++ {
wg.Add(1)
go func() {
defer wg.Done()
if limitIp.IsInvalid(strconv.Itoa(j)) {
atomic.AddInt64(&res, 1)
}
}()
}
}
wg.Wait()
fmt.Printf("res=%d",res)
} |
package api
import (
"time"
"testing"
"github.com/stretchr/testify/assert"
)
func TestImports(t *testing.T) {
if assert.Equal(t, 1, 1) != true {
t.Error("Something is wrong.")
}
}
func TestNewConfig(t *testing.T) {
settings := map[string]string{
"client_id": "consumerkey",
"client_secret": "consumersecret",
"access_token": "accesstoken",
"refresh_token": "refreshtoken",
"redirect_uri": "http://a.redirect.uri",
"expires_at": "2018-01-01T01:00:00.000Z",
"expires_in": "100",
"debug": "on",
}
config := NewConfig(settings)
if assert.NotNil(t, config) {
assert.Equal(t, "consumerkey", config.ClientId)
assert.Equal(t, "consumersecret", config.ClientSecret)
assert.Equal(t, "accesstoken", config.AccessToken)
assert.Equal(t, "refreshtoken", config.RefreshToken)
assert.Equal(t, "http://a.redirect.uri", config.RedirectUri)
ttime, _ := time.Parse(TIMEFORMAT, "2018-01-01T01:00:00.000Z")
assert.Equal(t, ttime, config.ExpiresAt)
assert.Equal(t, "100", config.ExpiresIn)
assert.True(t, true, config.Debug)
}
}
func TestReadConfig(t *testing.T) {
config := ReadConfig("../example/config.json")
if assert.NotNil(t, config) {
assert.Equal(t, "YOUR_CONSUMER_KEY", config.ClientId)
assert.Equal(t, "YOUR_CONSUMER_SECRET", config.ClientSecret)
assert.Equal(t, "access-token-if-known-otherwise-remove", config.AccessToken)
assert.Equal(t, "access-token-if-known-otherwise-remove", config.RefreshToken)
assert.Equal(t, "https://a.callback.url", config.RedirectUri)
ttime, _ := time.Parse(TIMEFORMAT, "2018-01-01T01:00:00.000Z")
assert.Equal(t, ttime, config.ExpiresAt)
}
}
|
package tracker
type TicketComments []TicketComment
type TicketComment map[string]interface{}
// Return last comment
func (t TicketComments) GetLast() TicketComment {
countComments := len(t)
if countComments == 0 {
return TicketComment{}
}
return t[len(t)-1]
}
// Get comment author
func (t TicketComment) CreatedBy() User {
if createdBy, ok := t["createdBy"].(map[string]interface{}); ok {
return User{
Self: toString(createdBy["self"]),
ID: toString(createdBy["id"]),
Display: toString(createdBy["display"]),
}
}
return User{}
}
// Get comment text
func (t TicketComment) Text() string {
return t.GetField("text")
}
// Get comment author
func (t TicketComment) Summonees() Users {
if summonees, ok := t["summonees"].([]interface{}); ok {
users := make(Users, len(summonees))
for i := range summonees {
users[i] = User{
Self: toString(summonees[i].(map[string]interface{})["self"]),
ID: toString(summonees[i].(map[string]interface{})["id"]),
Display: toString(summonees[i].(map[string]interface{})["display"]),
}
}
return users
}
return Users{}
}
// Get any custom ticket field
func (t TicketComment) GetField(field string) string {
if key, ok := t[field]; ok {
return toString(key)
}
return ""
}
|
package interactive
import "io"
// shell implements the ReadWriter interface.
type shell struct {
io.Reader
io.Writer
}
func (s *shell) read(data []byte) (n int, err error) {
return s.Read(data)
}
func (s *shell) write(data []byte) (n int, err error) {
return s.Write(data)
}
|
package models
import (
"fmt"
"math/rand"
"sort"
"github.com/mrap/stringutil"
wordpatterns "github.com/mrap/wordpatterns"
)
const (
MinCombosCount = 0
MinMaxComboLen = 2
MinMinComboLen = 2
)
// TODO: Might provide other languages/wordlists in the future.
// We would need to store lookups/wordmaps in a db
var (
_sharedWordmap *wordpatterns.Wordmap
)
func init() {
StoreWords("wordlists/google-10000-english.txt")
}
func GenerateCombos(chars string, count, minLen, maxLen int) []string {
// Validate and normalize params
if len(chars) == 0 {
return []string{}
}
if count < MinCombosCount {
count = MinCombosCount
}
if minLen < MinMinComboLen {
minLen = MinMinComboLen
}
if maxLen < MinMaxComboLen {
maxLen = MinMaxComboLen
}
if maxLen < minLen {
maxLen = minLen
}
combos := RankedCombos(_sharedWordmap, chars, minLen, maxLen)
return generateComboList(_sharedWordmap, combos, count)
}
// StoreWords stores words from a word list file into
func StoreWords(filename string) {
wm := NewDefaultWordmap()
wordpatterns.PopulateFromFile(wm, filename)
_sharedWordmap = wm
}
func CombosWithChars(lookup *wordpatterns.Wordmap, chars string, minLen int, maxLen int) []string {
if maxLen < 0 {
maxLen = 0
}
if minLen < 0 {
minLen = 0
}
var combos []string
for _, combo := range stringutil.Substrs(chars, minLen) {
if (minLen != 0 && len(combo) < minLen) || (maxLen != 0 && len(combo) > maxLen || len(lookup.WordsContaining(combo)) == 0) {
continue
} else {
combos = append(combos, combo)
}
}
return combos
}
func RankedCombos(lookup *wordpatterns.Wordmap, chars string, minLen, maxLen int) []string {
combos := CombosWithChars(lookup, chars, minLen, maxLen)
sort.Sort(ByWordCount(combos))
return combos
}
// generateComboList returns a slice of combos that are distributed based on rank
// More occurring combos will appear more frequently
func generateComboList(wm *wordpatterns.Wordmap, combos []string, count int) []string {
total := 0
for _, c := range combos {
total += len(wm.WordsContaining(c))
}
list := make([]string, count)
var r, cur int
for i := 0; i < count; i++ {
cur = 0
r = rand.Intn(total) + 1
for _, c := range combos {
cur += len(wm.WordsContaining(c))
if r <= cur {
list[i] = c
break
}
}
}
return list
}
type ByWordCount []string
func (a ByWordCount) Len() int { return len(a) }
func (a ByWordCount) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByWordCount) Less(i, j int) bool {
return _sharedWordmap.Compare(a[i], a[j]) >= 0
}
func printComboListCounts(combos []string) {
counts := make(map[string]int)
for _, c := range combos {
counts[c]++
}
for key, count := range counts {
fmt.Printf("%s -> %d\n", key, count)
}
fmt.Println()
}
|
package utils
import (
"sync"
"time"
)
//go-message-queue消息队列
type Queue struct {
size int
queue []Message
sync.RWMutex
}
type Message struct {
Id string
Name string
Time time.Time
Message string
}
func (this *Queue) Push(s Message) {
this.Lock()
defer this.Unlock()
this.queue = append(this.queue, s)
this.size = this.size + 1
}
func (this *Queue) PushNext(msg Message, index int) {
this.Lock()
defer this.Unlock()
if index == -1 {
this.queue = append(this.queue, msg)
} else {
tmp := append(this.queue[:index], msg)
this.queue = append(tmp, this.queue[index:]...)
}
this.size += 1
}
//队列先进先出
func (this *Queue) Pop() Message {
this.Lock()
defer this.Unlock()
s := this.queue[0]
this.queue = this.queue[1:]
this.size = this.size - 1
// log.Println(s[0])
return s
}
//队列先进后出
func (this *Queue) Pull() Message {
this.Lock()
defer this.Unlock()
s := this.queue[this.size-1]
this.queue = this.queue[0 : this.size-1]
this.size -= 1
return s
}
func (this *Queue) Size() int {
this.RLock()
defer this.RUnlock()
return this.size
}
func (this *Queue) Get(index int) Message {
this.RLock()
defer this.RUnlock()
return this.queue[index]
}
func (this *Queue) List() []Message {
this.RLock()
defer this.RUnlock()
return this.queue
}
func (this *Queue) FindById(id string) (index int, msg Message) {
this.RLock()
defer this.RUnlock()
index = -1
if this.size <= 0 {
return
}
for k, v := range this.queue {
if v.Id == id {
return k, v
}
}
return
}
func (this *Queue) FindByName(name string) (index int, msg Message) {
this.RLock()
defer this.RUnlock()
index = -1
if this.size <= 0 {
return
}
for k, v := range this.queue {
if v.Name == name {
return k, v
}
}
return
}
func (this *Queue) DeleteById(id string) int {
this.Lock()
defer this.Unlock()
found := -1
for k, v := range this.queue {
if v.Id == id {
found = k
break
}
}
if found >= 0 {
this.queue = append(this.queue[:found], this.queue[found+1:]...)
this.size = this.size - 1
}
return found
}
|
package main
import "fmt"
func main() {
var x int
var y float64
fmt.Scanf("%f", &y)
x = int(y)
fmt.Printf("%d\n", x)
}
|
package transmitter
import (
"container/heap"
)
// webhookHeap is a heap that will always give you
// a webhook that has either expired or is closest to its expiry.
//
// To be more accurate, it returns the oldest webhook.
//
// This struct will never modify a webhook, so you need to do this yourself.
type webhookHeap struct {
indices map[string]int
list []webhook
}
func newWebhookHeap() webhookHeap {
return webhookHeap{
make(map[string]int),
[]webhook{},
}
}
func (h webhookHeap) Len() int {
return len(h.list)
}
func (h webhookHeap) Less(i, j int) bool {
return h.list[i].lastUse.Before(h.list[j].lastUse)
}
func (h webhookHeap) Swap(i, j int) {
iChannel := h.list[i].ChannelID
jChannel := h.list[j].ChannelID
h.list[i], h.list[j] = h.list[j], h.list[i]
h.indices[iChannel], h.indices[jChannel] = j, i
}
func (h *webhookHeap) Push(x interface{}) {
wh := x.(*wrappedWebhook)
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
h.indices[wh.ChannelID] = len(h.list)
h.list = append(h.list, wh)
}
func (h *webhookHeap) Pop() interface{} {
old := h.list
n := len(old)
x := old[n-1]
h.list = old[0 : n-1]
delete(h.indices, x.ChannelID)
return x
}
func (h *webhookHeap) Remove(channel string) {
i := h.indices[channel]
heap.Remove(h, i)
}
func (h *webhookHeap) Get(channel string) webhook {
i, ok := h.indices[channel]
if !ok {
return nil
}
return h.list[i]
}
// Fix must to be called when a webhook's
// lastUse attribute is changed.
//
// This function will panic if no such
// webhook for that channel exists.
func (h *webhookHeap) Fix(channel string) {
i, ok := h.indices[channel]
if !ok {
panic("could not fix channel: " + channel)
}
heap.Fix(h, i)
}
// Peak returns the soonest-to-expire webhook without popping it from the heap.
//
// This function will panic if there are no webhooks in the heap.
func (h *webhookHeap) Peak() webhook {
return h.list[0]
}
// Swap must be called when changing a webhook's channel ID.
//
// This function will panic if the old channel does not exist.
// Behaviour is undefined if the new channel already exists.
//
// This does not modify the webhook (does not change the webhook ChannelID)
func (h *webhookHeap) SwapChannel(oldID, newID string) {
h.indices[newID] = h.indices[oldID]
delete(h.indices, oldID)
}
|
package main
import (
"fmt"
"net/rpc"
)
type General struct {
Nombre string
Materia string
Calificacion float64
}
func client() {
c, err := rpc.Dial("tcp", "127.0.0.1:9999")
if err != nil {
fmt.Println(err)
return
}
var op int64
for {
fmt.Println("---------------MENU-----------------")
fmt.Println("1. Agregar Alumno con materia" )
fmt.Println("2. Materias de un alumno" )
fmt.Println("3. Mostrar alumnos por materia" )
fmt.Println("4. Promedio de Materia" )
fmt.Println("5. Promedio de Alumno" )
fmt.Println("6. Promedio General" )
fmt.Println("0. Salir" )
fmt.Scanln(&op)
switch op {
case 1:
fmt.Println("----Agregar Alumno----")
var nombre string
fmt.Println( "Nombre alumno: " )
fmt.Scanln(&nombre)
var materia string
fmt.Println( "Nombre de la materia: " )
fmt.Scanln(&materia)
var calificacion float64
fmt.Println( "Calificacion: " )
fmt.Scanln(&calificacion)
alumnoNuevo := General{nombre, materia, calificacion}
var result string
err = c.Call( "Server.NuevoAlumno" , alumnoNuevo, &result)
if err != nil {
fmt.Println (err)
} else {
fmt.Println (result)
}
case 2:
fmt.Println("----Materias de un Alumno----")
var nombre string
fmt.Println( "Nombre alumno: " )
fmt.Scanln(&nombre)
var result string
err = c.Call( "Server.MateriasPorAlumno" , nombre, &result)
if err != nil {
fmt.Println (err)
} else {
fmt.Println (result)
}
case 3:
fmt.Println("----Mostrar alumnos por materia----")
var materia string
fmt.Println( "Nombre de la materia: " )
fmt.Scanln(&materia)
var result string
err = c.Call( "Server.AlumnosPorMateria" , materia , &result)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
case 4:
fmt.Println("----Promedio de materia----")
var materia string
fmt.Println( "Nombre de la materia: " )
fmt.Scanln(&materia)
var result float64
err = c.Call( "Server.PromedioPorMateria" , materia , &result)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
case 5:
fmt.Println("----Promedio de Alumno----")
var nombre string
fmt.Println( "Nombre del alumno: " )
fmt.Scanln(&nombre)
var result float64
err = c.Call( "Server.PromedioPorAlumno" , nombre , &result)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
case 6:
fmt.Println("----Promedio de todos los alumnos----")
aux := "_"
var result float64
err = c.Call( "Server.PromedioGeneral" , aux , &result)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
case 0:
return
}
}
}
func main() {
client()
} |
package server
import (
"context"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/json"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/crewjam/saml"
"github.com/crewjam/saml/samlsp"
"github.com/dimfeld/httptreemux"
"github.com/gofrs/uuid"
"github.com/rkuris/journey/authentication"
"github.com/rkuris/journey/configuration"
"github.com/rkuris/journey/conversion"
"github.com/rkuris/journey/database"
"github.com/rkuris/journey/date"
"github.com/rkuris/journey/filenames"
"github.com/rkuris/journey/notifications"
"github.com/rkuris/journey/slug"
"github.com/rkuris/journey/structure"
"github.com/rkuris/journey/structure/methods"
"github.com/rkuris/journey/templates"
)
var sessionHandler authentication.SessionHandler
// JSONPost is a JSON representation of a post
type JSONPost struct {
ID int64
Title string
Slug string
Markdown string
HTML string
IsFeatured bool
IsPage bool
IsPublished bool
Image string
MetaDescription string
Date *time.Time
Tags string
}
// JSONBlog is a JSON representation of the whole blog
// mostly metadata
type JSONBlog struct {
URL string `json:"url"`
Title string
Description string
Logo string
Cover string
Themes []string
ActiveTheme string
PostsPerPage int64
NavigationItems []structure.Navigation
}
// JSONUser is for users managed by the blog
type JSONUser struct {
ID int64
Name string
Slug string
Email string
Image string
Cover string
Bio string
Website string
Location string
Password string
PasswordRepeated string
}
// JSONUserID is the ID for the user
type JSONUserID struct {
ID int64 `json:"Id"`
}
// JSONImage is a blog image
type JSONImage struct {
Filename string
}
// Function to serve the login page
func getLoginHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
if database.RetrieveUsersCount() == 0 {
http.Redirect(w, r, "/admin/register", http.StatusFound)
return
}
http.ServeFile(w, r, filepath.Join(filenames.AdminFilepath, "login.html"))
return
}
// Function to receive a login form
func postLoginHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
name := r.FormValue("name")
password := r.FormValue("password")
if name != "" && password != "" {
if authentication.LoginIsCorrect(name, password) {
logInUser(name, w)
} else {
log.Println("Failed login attempt for user " + name)
}
}
http.Redirect(w, r, "/admin", http.StatusFound)
return
}
// Function to serve the registration form
func getRegistrationHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
if database.RetrieveUsersCount() == 0 {
http.ServeFile(w, r, filepath.Join(filenames.AdminFilepath, "registration.html"))
return
}
http.Redirect(w, r, "/admin", http.StatusFound)
return
}
// Function to recieve a registration form.
func postRegistrationHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
if database.RetrieveUsersCount() == 0 { // TODO: Or check if authenticated user is admin when adding users from inside the admin area
name := r.FormValue("name")
email := r.FormValue("email")
password := r.FormValue("password")
if name != "" && password != "" {
hashedPassword, err := authentication.EncryptPassword(password)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user := structure.User{Name: []byte(name), Slug: slug.Generate(name, "users"), Email: []byte(email), Image: []byte(filenames.DefaultUserImageFilename), Cover: []byte(filenames.DefaultUserCoverFilename), Role: 4}
err = methods.SaveUser(&user, hashedPassword, 1)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/admin", http.StatusFound)
return
}
http.Redirect(w, r, "/admin", http.StatusFound)
return
}
// TODO: Handle creation of other users (not just the first one)
http.Error(w, "Not implemented yet.", http.StatusInternalServerError)
return
}
// Function to log out the user. Not used at the moment.
func logoutHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
sessionHandler.ClearSession(w, r)
return
}
// Function to route the /admin/ url accordingly. (Is user logged in? Is at least one user registered?)
func adminHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
if database.RetrieveUsersCount() == 0 {
http.Redirect(w, r, "/admin/register", http.StatusFound)
return
}
userName := sessionHandler.GetUserName(r)
if userName != "" {
http.ServeFile(w, r, filepath.Join(filenames.AdminFilepath, "admin.html"))
return
}
http.Redirect(w, r, "/admin/login", http.StatusFound)
}
// Function to serve files belonging to the admin interface.
func adminFileHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
userName := sessionHandler.GetUserName(r)
if userName != "" {
// Get arguments (files)
http.ServeFile(w, r, filepath.Join(filenames.AdminFilepath, params["filepath"]))
return
}
http.NotFound(w, r)
}
// API function to get all posts by pages
func apiPostsHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
userName := sessionHandler.GetUserName(r)
if userName != "" {
number := params["number"]
page, err := strconv.Atoi(number)
if err != nil || page < 1 {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
postsPerPage := int64(15)
posts, err := database.RetrievePostsForAPI(postsPerPage, ((int64(page) - 1) * postsPerPage))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json, err := json.Marshal(postsToJSON(posts))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(json)
return
}
http.Error(w, "Not logged in!", http.StatusInternalServerError)
}
// API function to get a post by id
func getAPIPostHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
userName := sessionHandler.GetUserName(r)
if userName != "" {
id := params["id"]
// Get post
postID, err := strconv.ParseInt(id, 10, 64)
if err != nil || postID < 1 {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
post, err := database.RetrievePostByID(postID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json, err := json.Marshal(postToJSON(post))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(json)
return
}
http.Error(w, "Not logged in!", http.StatusInternalServerError)
}
// API function to create a post
func postAPIPostHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
userName := sessionHandler.GetUserName(r)
if userName != "" {
userID, err := getUserID(userName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Create post
decoder := json.NewDecoder(r.Body)
var json JSONPost
err = decoder.Decode(&json)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var postSlug string
if json.Slug != "" { // Ceck if user has submitted a custom slug
postSlug = slug.Generate(json.Slug, "posts")
} else {
postSlug = slug.Generate(json.Title, "posts")
}
currentTime := date.GetCurrentTime()
post := structure.Post{Title: []byte(json.Title), Slug: postSlug, Markdown: []byte(json.Markdown), HTML: conversion.GenerateHTMLFromMarkdown([]byte(json.Markdown)), IsFeatured: json.IsFeatured, IsPage: json.IsPage, IsPublished: json.IsPublished, MetaDescription: []byte(json.MetaDescription), Image: []byte(json.Image), Date: ¤tTime, Tags: methods.GenerateTagsFromCommaString(json.Tags), Author: &structure.User{ID: userID}}
err = methods.SavePost(&post)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if post.IsPublished {
notifications.Send(string(post.Title), "https://svjaneo.com/"+post.Slug)
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Post created!"))
return
}
http.Error(w, "Not logged in!", http.StatusInternalServerError)
}
// API function to update a post.
func patchAPIPostHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
userName := sessionHandler.GetUserName(r)
if userName != "" {
userID, err := getUserID(userName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Update post
decoder := json.NewDecoder(r.Body)
var json JSONPost
err = decoder.Decode(&json)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var postSlug string
// Get current slug of post
post, err := database.RetrievePostByID(json.ID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if json.Slug != post.Slug { // Check if user has submitted a custom slug
postSlug = slug.Generate(json.Slug, "posts")
} else {
postSlug = post.Slug
}
currentTime := date.GetCurrentTime()
*post = structure.Post{ID: json.ID, Title: []byte(json.Title), Slug: postSlug, Markdown: []byte(json.Markdown), HTML: conversion.GenerateHTMLFromMarkdown([]byte(json.Markdown)), IsFeatured: json.IsFeatured, IsPage: json.IsPage, IsPublished: json.IsPublished, MetaDescription: []byte(json.MetaDescription), Image: []byte(json.Image), Date: ¤tTime, Tags: methods.GenerateTagsFromCommaString(json.Tags), Author: &structure.User{ID: userID}}
newlyPublished, err := methods.UpdatePost(post)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if newlyPublished {
notifications.Send(string(post.Title), "https://svjaneo.com/"+post.Slug)
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Post updated!"))
return
}
http.Error(w, "Not logged in!", http.StatusInternalServerError)
}
// API function to delete a post by id.
func deleteAPIPostHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
userName := sessionHandler.GetUserName(r)
if userName != "" {
id := params["id"]
// Delete post
postID, err := strconv.ParseInt(id, 10, 64)
if err != nil || postID < 1 {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = methods.DeletePost(postID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Post deleted!"))
return
}
http.Error(w, "Not logged in!", http.StatusInternalServerError)
}
// API function to upload images
func apiUploadHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
userName := sessionHandler.GetUserName(r)
if userName != "" {
// Create multipart reader
reader, err := r.MultipartReader()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Slice to hold all paths to the files
allFilePaths := make([]string, 0)
// Copy each part to destination.
for {
part, err := reader.NextPart()
if err == io.EOF {
break
}
// If part.FileName() is empty, skip this iteration.
if part.FileName() == "" {
continue
}
// Folder structure: year/month/randomname
currentDate := date.GetCurrentTime()
filePath := filepath.Join(filenames.ImagesFilepath, currentDate.Format("2006"), currentDate.Format("01"))
if os.MkdirAll(filePath, 0777) != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
dst, err := os.Create(filepath.Join(filePath, strconv.FormatInt(currentDate.Unix(), 10)+"_"+uuid.Must(uuid.NewV4()).String()+filepath.Ext(part.FileName())))
defer dst.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err := io.Copy(dst, part); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Rewrite to file path on server
filePath = strings.Replace(dst.Name(), filenames.ImagesFilepath, "/images", 1)
// Make sure to always use "/" as path separator (to make a valid url that we can use on the blog)
filePath = filepath.ToSlash(filePath)
allFilePaths = append(allFilePaths, filePath)
}
json, err := json.Marshal(allFilePaths)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(json)
return
}
http.Error(w, "Not logged in!", http.StatusInternalServerError)
}
// API function to get all images by pages
func apiImagesHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
userName := sessionHandler.GetUserName(r)
if userName != "" {
number := params["number"]
page, err := strconv.Atoi(number)
if err != nil || page < 1 {
http.Error(w, "Not a valid api function!", http.StatusInternalServerError)
return
}
images := make([]string, 0)
// Walk all files in images folder
err = filepath.Walk(filenames.ImagesFilepath, func(filePath string, info os.FileInfo, err error) error {
if !info.IsDir() && (strings.EqualFold(filepath.Ext(filePath), ".jpg") || strings.EqualFold(filepath.Ext(filePath), ".jpeg") || strings.EqualFold(filepath.Ext(filePath), ".gif") || strings.EqualFold(filepath.Ext(filePath), ".png") || strings.EqualFold(filepath.Ext(filePath), ".svg")) {
// Rewrite to file path on server
filePath = strings.Replace(filePath, filenames.ImagesFilepath, "/images", 1)
// Make sure to always use "/" as path separator (to make a valid url that we can use on the blog)
filePath = filepath.ToSlash(filePath)
// Prepend file to slice (thus reversing the order)
images = append([]string{filePath}, images...)
}
return nil
})
if len(images) == 0 {
// Write empty json array
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("[]"))
return
}
imagesPerPage := 15
start := (page * imagesPerPage) - imagesPerPage
end := page * imagesPerPage
if start > (len(images) - 1) {
// Write empty json array
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("[]"))
return
}
if end > len(images) {
end = len(images)
}
json, err := json.Marshal(images[start:end])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(json)
return
}
http.Error(w, "Not logged in!", http.StatusInternalServerError)
}
// API function to delete an image by its filename.
func deleteAPIImageHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
userName := sessionHandler.GetUserName(r)
if userName != "" { // TODO: Check if the user has permissions to delete the image
// Get the file name from the json data
decoder := json.NewDecoder(r.Body)
var json JSONImage
err := decoder.Decode(&json)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = filepath.Walk(filenames.ImagesFilepath, func(filePath string, info os.FileInfo, err error) error {
if !info.IsDir() && filepath.Base(filePath) == filepath.Base(json.Filename) {
err := os.Remove(filePath)
if err != nil {
return err
}
}
return nil
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Image deleted!"))
return
}
http.Error(w, "Not logged in!", http.StatusInternalServerError)
}
// API function to get blog settings
func getAPIBlogHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
// Read lock the global blog
methods.Blog.RLock()
defer methods.Blog.RUnlock()
blogJSON := blogToJSON(methods.Blog)
json, err := json.Marshal(blogJSON)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(json)
return
}
// API function to update blog settings
func patchAPIBlogHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
userName := sessionHandler.GetUserName(r)
userID, err := getUserID(userName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
decoder := json.NewDecoder(r.Body)
var json JSONBlog
err = decoder.Decode(&json)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Make sure postPerPage is over 0
if json.PostsPerPage < 1 {
json.PostsPerPage = 1
}
// Remove blog url in front of navigation urls
for index := range json.NavigationItems {
if strings.HasPrefix(json.NavigationItems[index].URL, json.URL) {
json.NavigationItems[index].URL = strings.Replace(json.NavigationItems[index].URL, json.URL, "", 1)
// If we removed the blog url, there should be a / in front of the url
if !strings.HasPrefix(json.NavigationItems[index].URL, "/") {
json.NavigationItems[index].URL = "/" + json.NavigationItems[index].URL
}
}
}
// Retrieve old blog settings for comparison
blog, err := database.RetrieveBlog()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tempBlog := structure.Blog{URL: []byte(configuration.Config.URL), Title: []byte(json.Title), Description: []byte(json.Description), Logo: []byte(json.Logo), Cover: []byte(json.Cover), AssetPath: []byte("/assets/"), PostCount: blog.PostCount, PostsPerPage: json.PostsPerPage, ActiveTheme: json.ActiveTheme, NavigationItems: json.NavigationItems}
err = methods.UpdateBlog(&tempBlog, userID)
// Check if active theme setting has been changed, if so, generate templates from new theme
if tempBlog.ActiveTheme != blog.ActiveTheme {
err = templates.Generate()
if err != nil {
// If there's an error while generating the new templates, the whole program must be stopped.
log.Fatal("Fatal error: Template data couldn't be generated from theme files: " + err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Blog settings updated!"))
return
}
// API function to get user settings
func getAPIUserHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
userName := sessionHandler.GetUserName(r)
userID, err := getUserID(userName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
id := params["id"]
userIDToGet, err := strconv.ParseInt(id, 10, 64)
if err != nil || userIDToGet < 1 {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else if userIDToGet != userID { // Make sure the authenticated user is only accessing his/her own data. TODO: Make sure the user is admin when multiple users have been introduced
http.Error(w, "You don't have permission to access this data.", http.StatusForbidden)
return
}
user, err := database.RetrieveUser(userIDToGet)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
userJSON := userToJSON(user)
json, err := json.Marshal(userJSON)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(json)
return
}
// API function to patch user settings
func patchAPIUserHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
userName := sessionHandler.GetUserName(r)
userID, err := getUserID(userName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
decoder := json.NewDecoder(r.Body)
var json JSONUser
err = decoder.Decode(&json)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Make sure user id is over 0
if json.ID < 1 {
http.Error(w, "Wrong user id.", http.StatusInternalServerError)
return
} else if userID != json.ID { // Make sure the authenticated user is only changing his/her own data. TODO: Make sure the user is admin when multiple users have been introduced
http.Error(w, "You don't have permission to change this data.", http.StatusInternalServerError)
return
}
// Get old user data to compare
tempUser, err := database.RetrieveUser(json.ID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Make sure user email is provided
if json.Email == "" {
json.Email = string(tempUser.Email)
}
// Make sure user name is provided
if json.Name == "" {
json.Name = string(tempUser.Name)
}
// Make sure user slug is provided
if json.Slug == "" {
json.Slug = tempUser.Slug
}
// Check if new name is already taken
if json.Name != string(tempUser.Name) {
_, err = database.RetrieveUserByName([]byte(json.Name))
if err == nil {
// The new user name is already taken. Assign the old name.
// TODO: Return error that will be displayed in the admin interface.
json.Name = string(tempUser.Name)
}
}
// Check if new slug is already taken
if json.Slug != tempUser.Slug {
_, err = database.RetrieveUserBySlug(json.Slug)
if err == nil {
// The new user slug is already taken. Assign the old slug.
// TODO: Return error that will be displayed in the admin interface.
json.Slug = tempUser.Slug
}
}
user := structure.User{ID: json.ID, Name: []byte(json.Name), Slug: json.Slug, Email: []byte(json.Email), Image: []byte(json.Image), Cover: []byte(json.Cover), Bio: []byte(json.Bio), Website: []byte(json.Website), Location: []byte(json.Location)}
err = methods.UpdateUser(&user, userID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if json.Password != "" && (json.Password == json.PasswordRepeated) { // Update password if a new one was submitted
encryptedPassword, err := authentication.EncryptPassword(json.Password)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = database.UpdateUserPassword(user.ID, encryptedPassword, date.GetCurrentTime(), json.ID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// Check if the user name was changed. If so, update the session cookie to the new user name.
if json.Name != string(tempUser.Name) {
logInUser(json.Name, w)
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("User settings updated!"))
return
}
// API function to get the id of the currently authenticated user
func getAPIUserIDHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
userName := sessionHandler.GetUserName(r)
userID, err := getUserID(userName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonUserID := JSONUserID{ID: userID}
json, err := json.Marshal(jsonUserID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(json)
return
}
func getUserID(userName string) (int64, error) {
user, err := database.RetrieveUserByName([]byte(userName))
if err != nil {
return 0, err
}
return user.ID, nil
}
func logInUser(name string, w http.ResponseWriter) {
sessionHandler.SetSession(name, w)
userID, err := getUserID(name)
if err != nil {
log.Println("Couldn't get id of logged in user:", err)
}
err = database.UpdateLastLogin(date.GetCurrentTime(), userID)
if err != nil {
log.Println("Couldn't update last login date of a user:", err)
}
}
func postsToJSON(posts []structure.Post) *[]JSONPost {
jsonPosts := make([]JSONPost, len(posts))
for index := range posts {
jsonPosts[index] = *postToJSON(&posts[index])
}
return &jsonPosts
}
func postToJSON(post *structure.Post) *JSONPost {
var jsonPost JSONPost
jsonPost.ID = post.ID
jsonPost.Title = string(post.Title)
jsonPost.Slug = post.Slug
jsonPost.Markdown = string(post.Markdown)
jsonPost.HTML = string(post.HTML)
jsonPost.IsFeatured = post.IsFeatured
jsonPost.IsPage = post.IsPage
jsonPost.IsPublished = post.IsPublished
jsonPost.MetaDescription = string(post.MetaDescription)
jsonPost.Image = string(post.Image)
jsonPost.Date = post.Date
tags := make([]string, len(post.Tags))
for index := range post.Tags {
tags[index] = string(post.Tags[index].Name)
}
jsonPost.Tags = strings.Join(tags, ",")
return &jsonPost
}
func blogToJSON(blog *structure.Blog) *JSONBlog {
var jsonBlog JSONBlog
jsonBlog.URL = string(blog.URL)
jsonBlog.Title = string(blog.Title)
jsonBlog.Description = string(blog.Description)
jsonBlog.Logo = string(blog.Logo)
jsonBlog.Cover = string(blog.Cover)
jsonBlog.PostsPerPage = blog.PostsPerPage
jsonBlog.Themes = templates.GetAllThemes()
jsonBlog.ActiveTheme = blog.ActiveTheme
jsonBlog.NavigationItems = blog.NavigationItems
return &jsonBlog
}
func userToJSON(user *structure.User) *JSONUser {
var jsonUser JSONUser
jsonUser.ID = user.ID
jsonUser.Name = string(user.Name)
jsonUser.Slug = user.Slug
jsonUser.Email = string(user.Email)
jsonUser.Image = string(user.Image)
jsonUser.Cover = string(user.Cover)
jsonUser.Bio = string(user.Bio)
jsonUser.Website = string(user.Website)
jsonUser.Location = string(user.Location)
return &jsonUser
}
// InitializeAdmin initializes all the /admin handlers
func InitializeAdmin(router *httptreemux.TreeMux) {
if configuration.Config.SAMLCert != "" {
keyPair, err := tls.LoadX509KeyPair(configuration.Config.SAMLCert,
configuration.Config.SAMLKey)
if err != nil {
panic(err)
}
keyPair.Leaf, err = x509.ParseCertificate(keyPair.Certificate[0])
if err != nil {
panic(err)
}
rootURL, err := url.Parse(configuration.Config.HTTPSUrl)
if err != nil {
panic(err)
}
var metadata *saml.EntityDescriptor
if strings.HasPrefix(configuration.Config.SAMLIDPUrl, "https://") {
idpMetadataURL, err := url.Parse(configuration.Config.SAMLIDPUrl)
if err != nil {
panic(err)
}
metadata, err = samlsp.FetchMetadata(context.TODO(), http.DefaultClient, *idpMetadataURL)
if err != nil {
panic(err)
}
} else if strings.HasPrefix(configuration.Config.SAMLIDPUrl, "/") {
data, err := ioutil.ReadFile(configuration.Config.SAMLIDPUrl)
if err != nil {
panic(err)
}
metadata, err = samlsp.ParseMetadata(data)
}
samlSP, err := samlsp.New(samlsp.Options{
URL: *rootURL,
Key: keyPair.PrivateKey.(*rsa.PrivateKey),
Certificate: keyPair.Leaf,
IDPMetadata: metadata,
// CookieMaxAge: 12 * time.Hour, // consider moving this to the configuration
})
if err != nil {
log.Fatalf("Error initializing saml: %s", err)
}
log.Println("setting up /saml/ handler")
router.GET("/saml/*all", httptreemux.HandlerFunc(func(w http.ResponseWriter, r *http.Request, _ map[string]string) {
samlSP.ServeHTTP(w, r)
}))
router.POST("/saml/*all", httptreemux.HandlerFunc(func(w http.ResponseWriter, r *http.Request, _ map[string]string) {
samlSP.ServeHTTP(w, r)
}))
sessionHandler = &authentication.SAMLSession{Middleware: samlSP}
} else {
sessionHandler = &authentication.UsernamePasswordSession{}
}
router.GET("/admin", sessionHandler.RequireSession(adminHandler))
// For admin panel
router.GET("/admin/login", getLoginHandler)
router.POST("/admin/login", postLoginHandler)
router.GET("/admin/register", getRegistrationHandler)
router.POST("/admin/register", postRegistrationHandler)
router.GET("/admin/logout", logoutHandler)
router.GET("/admin/*filepath", sessionHandler.RequireSession(adminFileHandler))
// For admin API (no trailing slash)
// Posts
router.GET("/admin/api/posts/:number", sessionHandler.RequireSession(apiPostsHandler))
// Post
router.GET("/admin/api/post/:id", sessionHandler.RequireSession(getAPIPostHandler))
router.POST("/admin/api/post", sessionHandler.RequireSession(postAPIPostHandler))
router.PATCH("/admin/api/post", sessionHandler.RequireSession(patchAPIPostHandler))
router.DELETE("/admin/api/post/:id", sessionHandler.RequireSession(deleteAPIPostHandler))
// Upload
router.POST("/admin/api/upload", sessionHandler.RequireSession(apiUploadHandler))
// Images
router.GET("/admin/api/images/:number", sessionHandler.RequireSession(apiImagesHandler))
router.DELETE("/admin/api/image", sessionHandler.RequireSession(deleteAPIImageHandler))
// Blog
router.GET("/admin/api/blog", sessionHandler.RequireSession(getAPIBlogHandler))
router.PATCH("/admin/api/blog", sessionHandler.RequireSession(patchAPIBlogHandler))
// User
router.GET("/admin/api/user/:id", sessionHandler.RequireSession(getAPIUserHandler))
router.PATCH("/admin/api/user", sessionHandler.RequireSession(patchAPIUserHandler))
// User id
router.GET("/admin/api/userid", sessionHandler.RequireSession(getAPIUserIDHandler))
}
|
package function
func Abs(x int) int {
if x < 0 {
x *= -1
}
return x
}
|
package main
import (
// "learn2/condition"
// "learn2/for"
// "learn2/switch"
"learn2/exercise"
)
func main() {
/*
condition.TestIf()
condition.TestIfelse()
condition.Test()
*/
/*
forDemo.TestFor1()
forDemo.TestFor2()
forDemo.TestFor3()
forDemo.TestFor4()
forDemo.TestFor5()
forDemo.TestFor6()
*/
/*
switchDemo.TestIf()
switchDemo.TestSwitch1()
switchDemo.TestSwitch2()
switchDemo.TestSwitch3()
switchDemo.TestSwitch4()
switchDemo.TestSwitch5()
*/
exercise.TestCfb()
}
|
package main
import "fmt"
func main() {
x := 42
fmt.Println("a - ", x)
fmt.Println("a's memory address - ", &x)
}
// a - 42
// a's memory address - 0xc00010c000
|
package raftor
// Notifier notifies the receiver of the cluster change.
type Notifier interface {
// Notify returns a read-only channel of ClusterChangeEvents which can be read when a node joins, leaves or is updated in the cluster.
Notify(ClusterChangeEvent)
}
|
package matchers
import "bytes"
func Mp3(in []byte) bool {
return bytes.HasPrefix(in, []byte("\x49\x44\x33"))
}
// TODO
func Flac(in []byte) bool {
return false
}
func Midi(in []byte) bool {
return false
}
func Ape(in []byte) bool {
return false
}
func MusePack(in []byte) bool {
return false
}
func Wav(in []byte) bool {
return false
}
func Aiff(in []byte) bool {
return false
}
|
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/rdooley/dogs/dogs"
"net/http"
)
type DogReq struct {
ID int `uri:"id" binding:"required"`
}
type NewDogReq struct {
Name string `json:"name" binding:"required"`
Owner string `json:"owner" binding:"required"`
Details string `json:"details" binding:"required"`
}
type UpdateDogReq struct {
Name string `json:"name" binding:"-"`
Owner string `json:"owner" binding:"-"`
Details string `json:"details" binding:"-"`
}
func main() {
router := gin.Default()
// Get all dogs
router.GET("/dogs", func(c *gin.Context) {
c.JSON(http.StatusOK, dogs.LoadDogs())
})
// Create a dog
router.POST("/dogs", func(c *gin.Context) {
var req NewDogReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
dog := dogs.NewDog(req.Name, req.Owner, req.Details)
c.JSON(http.StatusOK, gin.H{"ID": dog.ID})
})
// Get a specific dog
router.GET("/dogs/:id", func(c *gin.Context) {
var req DogReq
if err := c.ShouldBindUri(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"msg": err})
return
}
dog, found := dogs.LoadDog(req.ID)
if !found {
c.String(http.StatusNotFound, fmt.Sprintf("Dog %d not found", req.ID))
return
}
c.JSON(http.StatusOK, dog)
})
// Update a specific dog
router.PUT("/dogs/:id", func(c *gin.Context) {
// Get the id
var req DogReq
if err := c.ShouldBindUri(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"msg": err})
return
}
ID := req.ID
var updateReq UpdateDogReq
if err := c.ShouldBindJSON(&updateReq); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
dog, found := dogs.LoadDog(ID)
if !found {
c.String(http.StatusNotFound, fmt.Sprintf("Dog %d not found", ID))
return
}
dog = dogs.UpdateDog(dog, updateReq.Name, updateReq.Owner, updateReq.Details)
c.JSON(http.StatusOK, dog)
})
// Delete a dog
router.DELETE("/dogs/:id", func(c *gin.Context) {
// Get the id
var req DogReq
if err := c.ShouldBindUri(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"msg": err})
return
}
_, found := dogs.LoadDog(req.ID)
if !found {
c.String(http.StatusNotFound, fmt.Sprintf("Dog %d not found", req.ID))
return
}
dogs.DeleteDog(req.ID)
c.String(http.StatusOK, fmt.Sprintf("Dog %d deleted", req.ID))
})
// Run the thing on 8080
router.Run(":8080")
}
|
/*
Copyright 2022 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cli
import (
"context"
"fmt"
"strings"
"github.com/spf13/cobra"
"golang.org/x/term"
corev1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
apitypes "k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/kubectl/pkg/util/i18n"
"k8s.io/kubectl/pkg/util/templates"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/auth"
velacmd "github.com/oam-dev/kubevela/pkg/cmd"
cmdutil "github.com/oam-dev/kubevela/pkg/cmd/util"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/utils/util"
)
// AuthCommandGroup commands for create resources or configuration
func AuthCommandGroup(f velacmd.Factory, order string, streams util.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "auth",
Short: i18n.T("Manage identity and authorizations."),
Annotations: map[string]string{
types.TagCommandType: types.TypePlatform,
types.TagCommandOrder: order,
},
}
cmd.AddCommand(NewGenKubeConfigCommand(f, streams))
cmd.AddCommand(NewListPrivilegesCommand(f, streams))
cmd.AddCommand(NewGrantPrivilegesCommand(f, streams))
return cmd
}
// GenKubeConfigOptions options for create kubeconfig
type GenKubeConfigOptions struct {
auth.Identity
util.IOStreams
}
// Complete .
func (opt *GenKubeConfigOptions) Complete(f velacmd.Factory, cmd *cobra.Command) {
if opt.Identity.ServiceAccount != "" {
opt.Identity.ServiceAccountNamespace = velacmd.GetNamespace(f, cmd)
}
opt.Regularize()
}
// Validate .
func (opt *GenKubeConfigOptions) Validate() error {
return opt.Identity.Validate()
}
// Run .
func (opt *GenKubeConfigOptions) Run(f velacmd.Factory) error {
ctx := context.Background()
cli, err := kubernetes.NewForConfig(f.Config())
if err != nil {
return err
}
cfg, err := clientcmd.NewDefaultPathOptions().GetStartingConfig()
if err != nil {
return err
}
cfg, err = auth.GenerateKubeConfig(ctx, cli, cfg, opt.IOStreams.ErrOut, auth.KubeConfigWithIdentityGenerateOption(opt.Identity))
if err != nil {
return err
}
bs, err := clientcmd.Write(*cfg)
if err != nil {
return err
}
_, err = opt.Out.Write(bs)
return err
}
var (
genKubeConfigLong = templates.LongDesc(i18n.T(`
Generate kubeconfig for user
Generate a new kubeconfig with specified identity. By default, the generated kubeconfig
will reuse the certificate-authority-data in the cluster config from the current used
kubeconfig. All contexts, clusters and users that are not in use will not be included
in the generated kubeconfig.
To generate a new kubeconfig for given user and groups, use the --user and --group flag.
Multiple --group flags is allowed. The group kubevela:client is added to the groups by
default. The identity in the current kubeconfig should be able to approve
CertificateSigningRequest in the kubernetes cluster. See
https://kubernetes.io/docs/reference/access-authn-authz/certificate-signing-requests/
for details.
To generate a kubeconfig based on existing ServiceAccount in your cluster, use the
--serviceaccount flag. The corresponding secret token and ca data will be embedded in
the generated kubeconfig, which allows you to act as the serviceaccount.`))
generateKubeConfigExample = templates.Examples(i18n.T(`
# Generate a kubeconfig with provided user
vela auth gen-kubeconfig --user new-user
# Generate a kubeconfig with provided user and group
vela auth gen-kubeconfig --user new-user --group kubevela:developer
# Generate a kubeconfig with provided user and groups
vela auth gen-kubeconfig --user new-user --group kubevela:developer --group my-org:my-team
# Generate a kubeconfig with provided serviceaccount
vela auth gen-kubeconfig --serviceaccount default -n demo`))
)
// NewGenKubeConfigCommand generate kubeconfig for given user and groups
func NewGenKubeConfigCommand(f velacmd.Factory, streams util.IOStreams) *cobra.Command {
o := &GenKubeConfigOptions{IOStreams: streams}
cmd := &cobra.Command{
Use: "gen-kubeconfig",
DisableFlagsInUseLine: true,
Short: i18n.T("Generate kubeconfig for user"),
Long: genKubeConfigLong,
Example: generateKubeConfigExample,
Annotations: map[string]string{
types.TagCommandType: types.TypeCD,
},
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
o.Complete(f, cmd)
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.Run(f))
},
}
cmd.Flags().StringVarP(&o.User, "user", "u", o.User, "The user of the generated kubeconfig. If set, an X509-based kubeconfig will be intended to create. It will be embedded as the Subject in the X509 certificate.")
cmd.Flags().StringSliceVarP(&o.Groups, "group", "g", o.Groups, "The groups of the generated kubeconfig. This flag only works when `--user` is set. It will be embedded as the Organization in the X509 certificate.")
cmd.Flags().StringVarP(&o.ServiceAccount, "serviceaccount", "", o.ServiceAccount, "The serviceaccount of the generated kubeconfig. If set, a kubeconfig will be generated based on the secret token of the serviceaccount. Cannot be set when `--user` presents.")
cmdutil.CheckErr(cmd.RegisterFlagCompletionFunc(
"serviceaccount", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if strings.TrimSpace(o.User) != "" {
return nil, cobra.ShellCompDirectiveNoFileComp
}
namespace := velacmd.GetNamespace(f, cmd)
return velacmd.GetServiceAccountForCompletion(cmd.Context(), f, namespace, toComplete)
}))
return velacmd.NewCommandBuilder(f, cmd).
WithNamespaceFlag(velacmd.UsageOption("The namespace of the serviceaccount. This flag only works when `--serviceaccount` is set.")).
WithStreams(streams).
WithResponsiveWriter().
Build()
}
// ListPrivilegesOptions options for list privileges
type ListPrivilegesOptions struct {
auth.Identity
KubeConfig string
Clusters []string
util.IOStreams
}
// Complete .
func (opt *ListPrivilegesOptions) Complete(f velacmd.Factory, cmd *cobra.Command) {
if opt.KubeConfig != "" {
identity, err := auth.ReadIdentityFromKubeConfig(opt.KubeConfig)
cmdutil.CheckErr(err)
opt.Identity = *identity
}
if opt.Identity.ServiceAccount != "" {
opt.Identity.ServiceAccountNamespace = velacmd.GetNamespace(f, cmd)
}
opt.Clusters = velacmd.GetClusters(cmd)
opt.Regularize()
}
// Validate .
func (opt *ListPrivilegesOptions) Validate(f velacmd.Factory, cmd *cobra.Command) error {
if err := opt.Identity.Validate(); err != nil {
return err
}
for _, cluster := range opt.Clusters {
if _, err := multicluster.NewClusterClient(f.Client()).Get(cmd.Context(), cluster); err != nil {
return fmt.Errorf("failed to find cluster %s: %w", cluster, err)
}
}
return nil
}
// Run .
func (opt *ListPrivilegesOptions) Run(f velacmd.Factory, cmd *cobra.Command) error {
ctx := cmd.Context()
m, err := auth.ListPrivileges(ctx, f.Client(), opt.Clusters, &opt.Identity)
if err != nil {
return err
}
width, _, err := term.GetSize(0)
if err != nil {
width = 80
}
_, _ = opt.Out.Write([]byte(auth.PrettyPrintPrivileges(&opt.Identity, m, opt.Clusters, uint(width)-40)))
return nil
}
var (
listPrivilegesLong = templates.LongDesc(i18n.T(`
List privileges for user
List privileges that user has in clusters. Use --user/--group to check the privileges
for specified user and group. They can be jointly configured to see the union of
privileges. Use --serviceaccount and -n/--namespace to see the privileges for
ServiceAccount. You can also use --kubeconfig to use the identity inside implicitly.
The privileges will be shown in tree format.
This command supports listing privileges across multiple clusters, by using --cluster.
If not set, the control plane will be used. This feature requires cluster-gateway to be
properly setup to use.
The privileges are collected through listing all ClusterRoleBinding and RoleBinding,
following the Kubernetes RBAC Authorization. Other authorization mechanism is not supported
now. See https://kubernetes.io/docs/reference/access-authn-authz/rbac/ for details.
The ClusterRoleBinding and RoleBinding that matches the specified identity will be
tracked. Related ClusterRoles and Roles are retrieved and the contained PolicyRules are
demonstrated.`))
listPrivilegesExample = templates.Examples(i18n.T(`
# List privileges for User alice in the control plane
vela auth list-privileges --user alice
# List privileges for Group org:dev-team in the control plane
vela auth list-privileges --group org:dev-team
# List privileges for User bob with Groups org:dev-team and org:test-team in the control plane and managed cluster example-cluster
vela auth list-privileges --user bob --group org:dev-team --group org:test-team --cluster local --cluster example-cluster
# List privileges for ServiceAccount example-sa in demo namespace in multiple managed clusters
vela auth list-privileges --serviceaccount example-sa -n demo --cluster cluster-1 --cluster cluster-2
# List privileges for identity in kubeconfig
vela auth list-privileges --kubeconfig ./example.kubeconfig --cluster local --cluster cluster-1`))
)
// NewListPrivilegesCommand list privileges for given identity
func NewListPrivilegesCommand(f velacmd.Factory, streams util.IOStreams) *cobra.Command {
o := &ListPrivilegesOptions{IOStreams: streams}
cmd := &cobra.Command{
Use: "list-privileges",
DisableFlagsInUseLine: true,
Short: i18n.T("List privileges for user/group/serviceaccount"),
Long: listPrivilegesLong,
Example: listPrivilegesExample,
Annotations: map[string]string{
types.TagCommandType: types.TypeCD,
},
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
o.Complete(f, cmd)
cmdutil.CheckErr(o.Validate(f, cmd))
cmdutil.CheckErr(o.Run(f, cmd))
},
}
cmd.Flags().StringVarP(&o.User, "user", "u", o.User, "The user to list privileges.")
cmd.Flags().StringSliceVarP(&o.Groups, "group", "g", o.Groups, "The group to list privileges. Can be set together with --user.")
cmd.Flags().StringVarP(&o.ServiceAccount, "serviceaccount", "", o.ServiceAccount, "The serviceaccount to list privileges. Cannot be set with --user and --group.")
cmd.Flags().StringVarP(&o.KubeConfig, "kubeconfig", "", o.KubeConfig, "The kubeconfig to list privileges. If set, it will override all the other identity flags.")
cmdutil.CheckErr(cmd.RegisterFlagCompletionFunc(
"serviceaccount", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if strings.TrimSpace(o.User) != "" {
return nil, cobra.ShellCompDirectiveNoFileComp
}
namespace := velacmd.GetNamespace(f, cmd)
return velacmd.GetServiceAccountForCompletion(cmd.Context(), f, namespace, toComplete)
}))
return velacmd.NewCommandBuilder(f, cmd).
WithNamespaceFlag(velacmd.UsageOption("The namespace of the serviceaccount. This flag only works when `--serviceaccount` is set.")).
WithClusterFlag(velacmd.UsageOption("The cluster to list privileges. If not set, the command will list privileges in the control plane.")).
WithStreams(streams).
WithResponsiveWriter().
Build()
}
// GrantPrivilegesOptions options for grant privileges
type GrantPrivilegesOptions struct {
auth.Identity
KubeConfig string
GrantNamespaces []string
GrantClusters []string
ReadOnly bool
CreateNamespace bool
util.IOStreams
}
// Complete .
func (opt *GrantPrivilegesOptions) Complete(f velacmd.Factory, cmd *cobra.Command) {
if opt.KubeConfig != "" {
identity, err := auth.ReadIdentityFromKubeConfig(opt.KubeConfig)
cmdutil.CheckErr(err)
opt.Identity = *identity
opt.Identity.Groups = nil
}
if opt.Identity.ServiceAccount != "" {
opt.Identity.ServiceAccountNamespace = velacmd.GetNamespace(f, cmd)
}
opt.Regularize()
if len(opt.GrantClusters) == 0 {
opt.GrantClusters = []string{types.ClusterLocalName}
}
}
// Validate .
func (opt *GrantPrivilegesOptions) Validate(f velacmd.Factory, cmd *cobra.Command) error {
if opt.User == "" && len(opt.Groups) == 0 && opt.ServiceAccount == "" {
return fmt.Errorf("at least one idenity (user/group/serviceaccount) should be set")
}
for _, cluster := range opt.GrantClusters {
if _, err := multicluster.NewClusterClient(f.Client()).Get(cmd.Context(), cluster); err != nil {
return fmt.Errorf("failed to find cluster %s: %w", cluster, err)
}
if !opt.CreateNamespace {
for _, namespace := range opt.GrantNamespaces {
if err := f.Client().Get(multicluster.ContextWithClusterName(cmd.Context(), cluster), apitypes.NamespacedName{Name: namespace}, &corev1.Namespace{}); err != nil {
return fmt.Errorf("failed to find namespace %s in cluster %s: %w", namespace, cluster, err)
}
}
}
}
return nil
}
// Run .
func (opt *GrantPrivilegesOptions) Run(f velacmd.Factory, cmd *cobra.Command) error {
ctx := cmd.Context()
if opt.CreateNamespace {
for _, cluster := range opt.GrantClusters {
if _, err := multicluster.NewClusterClient(f.Client()).Get(cmd.Context(), cluster); err != nil {
return fmt.Errorf("failed to find cluster %s: %w", cluster, err)
}
for _, namespace := range opt.GrantNamespaces {
_ctx := multicluster.ContextWithClusterName(cmd.Context(), cluster)
ns := &corev1.Namespace{}
if err := f.Client().Get(_ctx, apitypes.NamespacedName{Name: namespace}, ns); err != nil {
if kerrors.IsNotFound(err) {
ns.SetName(namespace)
if err = f.Client().Create(_ctx, ns); err != nil {
return fmt.Errorf("failed to create namespace %s in cluster %s: %w", namespace, cluster, err)
}
continue
}
return fmt.Errorf("failed to find namespace %s in cluster %s: %w", namespace, cluster, err)
}
}
}
}
var privileges []auth.PrivilegeDescription
for _, cluster := range opt.GrantClusters {
for _, namespace := range opt.GrantNamespaces {
privileges = append(privileges, &auth.ScopedPrivilege{Cluster: cluster, Namespace: namespace, ReadOnly: opt.ReadOnly})
}
if len(opt.GrantNamespaces) == 0 {
privileges = append(privileges, &auth.ScopedPrivilege{Cluster: cluster, ReadOnly: opt.ReadOnly})
}
}
if err := auth.GrantPrivileges(ctx, f.Client(), privileges, &opt.Identity, opt.IOStreams.Out); err != nil {
return err
}
_, _ = fmt.Fprintf(opt.IOStreams.Out, "Privileges granted.\n")
return nil
}
var (
grantPrivilegesLong = templates.LongDesc(i18n.T(`
Grant privileges for user
Grant privileges to user/group/serviceaccount. By using --for-namespace and --for-cluster,
you can grant all read/write privileges for all resources in the specified namespace and
cluster. If --for-namespace is not set, the privileges will be granted cluster-wide.
Setting --create-namespace will automatically create namespace if the namespace of the
granted privilege does not exists. By default, this flag is not enabled and errors will be
returned if the namespace is not found in the corresponding cluster.
Setting --readonly will only grant read privileges for all resources in the destination. This
can be useful if you want to give somebody the privileges to view resources but do not want to
allow them to edit any resource.
If multiple identity information are set, all the identity information will be bond to the
intended privileges respectively.
If --kubeconfig is set, the user/serviceaccount information in the kubeconfig will be used as
the identity to grant privileges. Groups will be ignored.`))
grantPrivilegesExample = templates.Examples(i18n.T(`
# Grant privileges for User alice in the namespace demo of the control plane
vela auth grant-privileges --user alice --for-namespace demo
# Grant privileges for User alice in the namespace demo in cluster-1, create demo namespace if not exist
vela auth grant-privileges --user alice --for-namespace demo --for-cluster cluster-1 --create-namespace
# Grant cluster-scoped privileges for Group org:dev-team in the control plane
vela auth grant-privileges --group org:dev-team
# Grant privileges for Group org:dev-team and org:test-team in the namespace test on the control plane and managed cluster example-cluster
vela auth grant-privileges --group org:dev-team --group org:test-team --for-namespace test --for-cluster local --for-cluster example-cluster
# Grant read privileges for ServiceAccount observer in test namespace on the control plane
vela auth grant-privileges --serviceaccount observer -n test --for-namespace test --readonly
# Grant privileges for identity in kubeconfig in cluster-1
vela auth grant-privileges --kubeconfig ./example.kubeconfig --for-cluster cluster-1`))
)
// NewGrantPrivilegesCommand grant privileges to given identity
func NewGrantPrivilegesCommand(f velacmd.Factory, streams util.IOStreams) *cobra.Command {
o := &GrantPrivilegesOptions{IOStreams: streams}
cmd := &cobra.Command{
Use: "grant-privileges",
DisableFlagsInUseLine: true,
Short: i18n.T("Grant privileges for user/group/serviceaccount"),
Long: grantPrivilegesLong,
Example: grantPrivilegesExample,
Annotations: map[string]string{
types.TagCommandType: types.TypeCD,
},
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
o.Complete(f, cmd)
cmdutil.CheckErr(o.Validate(f, cmd))
cmdutil.CheckErr(o.Run(f, cmd))
},
}
cmd.Flags().StringVarP(&o.User, "user", "u", o.User, "The user to grant privileges.")
cmd.Flags().StringSliceVarP(&o.Groups, "group", "g", o.Groups, "The group to grant privileges.")
cmd.Flags().StringVarP(&o.ServiceAccount, "serviceaccount", "", o.ServiceAccount, "The serviceaccount to grant privileges.")
cmd.Flags().StringVarP(&o.KubeConfig, "kubeconfig", "", o.KubeConfig, "The kubeconfig to grant privileges. If set, it will override all the other identity flags.")
cmd.Flags().StringSliceVarP(&o.GrantClusters, "for-cluster", "", o.GrantClusters, "The clusters privileges to grant. If empty, the control plane will be used.")
cmd.Flags().StringSliceVarP(&o.GrantNamespaces, "for-namespace", "", o.GrantNamespaces, "The namespaces privileges to grant. If empty, cluster-scoped privileges will be granted.")
cmd.Flags().BoolVarP(&o.ReadOnly, "readonly", "", o.ReadOnly, "If set, only read privileges of resources will be granted. Otherwise, read/write privileges will be granted.")
cmd.Flags().BoolVarP(&o.CreateNamespace, "create-namespace", "", o.CreateNamespace, "If set, non-exist namespace will be created automatically.")
cmdutil.CheckErr(cmd.RegisterFlagCompletionFunc(
"serviceaccount", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if strings.TrimSpace(o.User) != "" {
return nil, cobra.ShellCompDirectiveNoFileComp
}
namespace := velacmd.GetNamespace(f, cmd)
return velacmd.GetServiceAccountForCompletion(cmd.Context(), f, namespace, toComplete)
}))
return velacmd.NewCommandBuilder(f, cmd).
WithNamespaceFlag(velacmd.UsageOption("The namespace of the serviceaccount. This flag only works when `--serviceaccount` is set.")).
WithStreams(streams).
WithResponsiveWriter().
Build()
}
|
package sfen
import (
"fmt"
"io"
"strings"
"unicode"
)
type posParser struct {
r io.RuneScanner
}
func newPosParser(s string) *posParser {
return &posParser{
r: strings.NewReader(s),
}
}
func (p *posParser) read() (rune, error) {
r, _, err := p.r.ReadRune()
return r, err
}
var sfenPieceBW = sfenPiece + strings.ToLower(sfenPiece)
func runeToPiece(r rune) (Player, PieceType) {
idx := strings.IndexRune(sfenPieceBW, r)
if idx == -1 {
return Player_NULL, Piece_NULL
}
var pl Player
switch idx / len(sfenPiece) {
case 0:
pl = Player_BLACK
case 1:
pl = Player_WHITE
}
return pl, PieceType(idx % len(sfenPiece))
}
func (p *posParser) parseBoard() ([9][9]*Piece, error) {
var board [9][9]*Piece
for _, y := range PosYs {
var promoted bool
var skip int
for _, x := range PosXs {
if skip > 0 {
skip--
continue
}
redo:
r, err := p.read()
if err != nil {
return board, err
}
p := &Piece{}
if r == '/' {
goto redo
} else if r == '+' {
promoted = true
goto redo
} else if unicode.IsDigit(r) {
skip = int(r-'0') - 1
continue
} else {
pl, pi := runeToPiece(r)
if pl == Player_NULL || pi == Piece_NULL {
return board, fmt.Errorf("unknown Piece: %c", r)
}
p.Player = pl
p.Type = pi
p.Promoted = promoted
}
board[y][x] = p
promoted = false
}
}
if _, err := p.read(); err == nil {
return board, fmt.Errorf("remain")
}
return board, nil
}
func parseCaptured(s string) []*Piece {
var ret []*Piece
if s == "-" {
return ret
}
count := 0
for _, r := range []rune(s) {
if unicode.IsDigit(r) {
if count != 0 {
count *= 10
}
count += int(r - '0')
continue
}
pl, pi := runeToPiece(r)
if pl == Player_NULL || pi == Piece_NULL {
return nil
}
if count == 0 {
count = 1
}
for i := 0; i < count; i++ {
ret = append(ret, &Piece{Player: pl, Type: pi})
}
count = 0
}
return ret
}
|
package message
import (
"fmt"
"html/template"
"net/http"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"github.com/totalsynthesis/autoromance/lib/schedule"
)
//go:generate go-bindata -pkg $GOPACKAGE view.html
var tmpl = map[string]*template.Template{}
var page_data = struct {
FormEndpoint string
CurrentMessages []*Message
}{
FormEndpoint: "/message",
CurrentMessages: []*Message{},
}
// Applies routes as a group to the gin.Engine.
// Accepts any parameters necessary for this component to function properly.
func ApplyRoutes(r *gin.RouterGroup, scheduler *schedule.Client, m ...gin.HandlerFunc) {
for _, mware := range m {
r.Use(mware)
}
r.Use(func(c *gin.Context) {
c.Set("scheduling-client", scheduler)
})
r.GET("/", RenderMessagePage)
r.POST("/email", get_messaging_client(ScheduleMessage, "email-client"))
r.POST("/sms", get_messaging_client(ScheduleMessage, "sms-client"))
}
// GenerateTemplates parses templates for this component against the base template passed in.
func GenerateTemplates(base *template.Template) *template.Template {
tbytes := MustAsset("view.html")
login_template, err := base.New("body").Parse(string(tbytes))
if err != nil {
panic(errors.Wrap(err, "could not parse template").Error())
}
tmpl["view.html"] = login_template
return login_template
}
// RenderTemplate returns an http.HandlerFunc that will execute the template into the response.
func RenderTemplate(name string) gin.HandlerFunc {
return func(c *gin.Context) {
t, ok := tmpl[name]
if !ok {
http.Error(
c.Writer,
errors.New("could not fetch template "+name).Error(),
http.StatusInternalServerError,
)
}
data, _ := c.Get("template_data")
err := t.Execute(c.Writer, data)
if err != nil {
http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
}
}
}
// get_messaging_client prepares the correct messaging client according to client_name.
func get_messaging_client(fn gin.HandlerFunc, client_name string) gin.HandlerFunc {
return func(c *gin.Context) {
client, ok := c.Get(client_name)
if !ok {
c.Error(fmt.Errorf("could not get client %q from context", client_name))
fn(c)
}
c.Set("messaging-client", client)
fn(c)
}
}
|
package loadbalancer
import (
"errors"
"github.com/Highway-Project/highway/pkg/service"
"github.com/Highway-Project/highway/pkg/service/random"
)
var loadBalancerConstructors map[string]func() (service.LoadBalancer, error)
func init() {
loadBalancerConstructors = make(map[string]func() (service.LoadBalancer, error))
_ = RegisterLoadBalancer("random", random.New)
}
func RegisterLoadBalancer(name string, constructor func() (service.LoadBalancer, error)) error {
if _, exists := loadBalancerConstructors[name]; exists {
return errors.New("LoadBalancer with this name exists: " + name)
}
loadBalancerConstructors[name] = constructor
return nil
}
func NewLoadBalancer(name string) (service.LoadBalancer, error) {
constructor, exists := loadBalancerConstructors[name]
if !exists {
return nil, errors.New("LoadBalancer with this name does not exists: " + name)
}
lb, err := constructor()
if err != nil {
return nil, err
}
return lb, nil
}
|
package stack
import (
"fmt"
)
// Stack ,,,
type Stack struct {
top *component
capacity int
length int
}
// Push ...
func (s *Stack) Push(data interface{}) error {
if s.capacity <= s.length {
return &stackOverflowError{}
}
s.top = &component{
data: data,
next: s.top,
}
s.length++
return nil
}
// Pop ...
func (s *Stack) Pop() {
if s.top != nil {
s.top = s.top.next
s.length--
}
}
// Top ...
func (s *Stack) Top() interface{} {
return s.top.data
}
// Print ...
func (s *Stack) Print() {
if s.top == nil {
fmt.Println("{ }")
return
}
var temp *component = s.top
fmt.Print("{ ")
for {
fmt.Print(temp.data, " ")
if temp.next == nil {
break
}
temp = temp.next
}
fmt.Println("}")
}
// NewStack ...
func NewStack(cap int) *Stack {
return &Stack{
top: nil,
capacity: cap,
length: 0,
}
}
type component struct {
data interface{}
next *component
}
|
package main
import (
"fmt"
"html"
"net/http"
"github.com/gorilla/mux"
)
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}
func TodoIndex(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
w.WriteHeader(http.StatusOK)
}
func TodoShow(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
todoId := vars["todoId"]
fmt.Fprintln(w, "Todo show:", todoId)
}
func TodoCreate(w http.ResponseWriter, r *http.Request) {
}
func TodoEdit(w http.ResponseWriter, r *http.Request) {
}
func TodoDelete(w http.ResponseWriter, r *http.Request) {
}
|
package types
import (
"grm-service/common"
)
const (
DataCreated = "created"
DataSubscribed = "subscribed"
DataShared = "shared"
ClassMarket = "market"
ClassUeser = "user"
)
// 数据类型
type DataType struct {
Name string `json:"name" description:"name of datatype"`
Label string `json:"label" description:"label of datatype"`
Parent string `json:"parent" description:"parent of datatype"`
IsObsoleted bool `json:"is_obsoleted" description:"status of datatype"`
Extensions string `json:"extension" description:"extensions of datatype"`
CreateTime string `json:"create_time" description:"create_time of datatype"`
Metas interface{} `json:"metas,omitempty" description:"metas of datatype"`
Description string `json:"description" description:"dataset description"`
}
// 数据类型集合
type DataTypeList []DataType
// 元元数据
type Meta struct {
Type string `json:"type" description:"name of datatype"`
Label string `json:"label" description:"label of datatype"`
DataMeta []GroupMeta `json:"metadata" description:"metas of data type"`
ChildMeta []Meta `json:"childmeta,omitempty" description:"metas of child type"`
}
type MetaValue struct {
Name string `json:"name"`
Title string `json:"title"`
Value interface{} `json:"value"`
Type string `json:"type"`
Required bool `json:"required"`
ReadOnly bool `json:"readonly"`
Query bool `json:"query"`
Classify bool `json:"classify"`
IsModified bool `json:"is_modified"`
}
type GroupMeta struct {
Group string `json:"group" description:"name of group"`
Label string `json:"label" description:"label of group"`
Values []MetaValue `json:"value" description:"metas of group"`
}
// 更新元元数据信息
type MetaFieldReq struct {
Group string `json:"group"`
Name string `json:"name"`
Title string `json:"title"`
Type string `json:"type"`
Required bool `json:"required"`
ReadOnly bool `json:"readonly"`
//Query bool `json:"query"`
Classify bool `json:"classify"`
}
// 数据集
type DataSet struct {
ID string `json:"id,omitempty" description:"identifier of the dataset"`
Name string `json:"name" description:"name of the dataset"`
User string `json:"user" description:"user id of the dataset"`
Type string `json:"type" description:"dataset type"`
Class string `json:"class" description:"dataset of market"`
CreateTime string `json:"create_time,omitempty"`
Description string `json:"description" description:"dataset description"`
}
// 数据集集合
type DataSetList []DataSet
// 数据图层
type UpdateLayerReq struct {
Name string `json:"layer_name"`
Style string `json:"style_sld"`
Description string `json:"description"`
IsDefault bool `json:"is_default"`
}
// 数据信息
type DataInfo struct {
DataId string `json:"data_id"`
DataName string `json:"data_name"`
DataType string `json:"data_type"`
SubType string `json:"sub_type"`
Path string `json:"path"`
Size string `json:"size"`
ViewCnt string `json:"view_cnt"`
DataTime string `json:"data_time"`
CreateTime string `json:"create_time"`
DeleteTime string `json:"delete_time"`
Status string `json:"status"`
DataSource string `json:"data_source"`
Abstract string `json:"abstract"`
Description string `json:"description"`
SnapShot string `json:"snapshot"`
Thumb string `json:"thumb"`
Tags string `json:"tags"`
Owner common.UserInfo `json:"owner"`
DataUrl string `json:"data_url"`
Storage string `json:"storage"`
Attribute []interface{} `json:"attribute"`
}
type SnapshotReq struct {
Image string `json:"image"`
FileName string `json:"file_name,omitempty"`
}
// 更新数据信息
type UpdateDataInfoReq struct {
Abstract string `json:"abstract" description:"abstract or \"omit\""`
Description string `json:"description" description:"description or \"omit\""`
Tags string `json:"tags" description:"tags or \"omit\""`
}
type UpdateMeta struct {
Group string `json:"group"`
Metas []struct {
Field string `json:"field"`
Value interface{} `json:"value"`
} `json:"fields"`
}
type UpdateDataMetaReq struct {
Metas []UpdateMeta `json:"metas"`
}
// 表格内容
type Row struct {
Rows []interface{} `json:"row"`
}
type TableData struct {
Total int `json:"total"`
Datas []Row `json:"table"`
}
type DataSearch struct {
DataId string `json:"data_id,omitempty"`
DataType string `json:"data_type"`
Order string `json:"order,omitempty"`
Limit string `json:"limit,omitempty"`
Offset string `json:"offset,omitempty"`
Sort string `json:"sort,omitempty"`
Key string `json:"key,omitempty"`
}
// 子对象
type SubGroup struct {
Count int64 `json:"count"`
Datas map[string]string `json:"datas"`
}
type DataSubObj struct {
Group map[string]*SubGroup `json:"groups"`
}
// 数据评论
type Comment struct {
Id string `json:"id"`
DataId string `json:"data_id"`
CreateTime string `json:"create_time"`
ToUser *common.UserInfo `json:"reply_user,omitempty"`
FromUser *common.UserInfo `json:"user"`
Content string `json:"content"`
}
|
package main
import (
"log"
"github.com/ramezanius/crypex/exchange/hitbtc"
)
var HitBTC *hitbtc.HitBTC
func main() {
HitBTC = hitbtc.New()
HitBTC.SetStreams(func(response interface{}) {
log.Println("HitBTC[Candles] received:", response)
}, func(response interface{}) {
log.Println("HitBTC[Reports] received:", response)
})
HitBTC.PublicKey = "YOUR_HITBTC_PUBLIC_KEY"
HitBTC.SecretKey = "YOUR_HITBTC_SECRET_KEY"
SubscribeReports()
SubscribeCandles(hitbtc.CandlesParams{
Symbol: hitbtc.BTC + hitbtc.USD,
Period: hitbtc.Period1Minute,
})
}
func SubscribeReports() {
defer func() {
err := HitBTC.UnsubscribeReports()
if err != nil {
log.Fatal(err)
}
}()
err := HitBTC.SubscribeReports()
if err != nil {
log.Panic(err)
}
}
func SubscribeCandles(params hitbtc.CandlesParams) {
defer func() {
err := HitBTC.UnsubscribeCandles(params)
if err != nil {
log.Fatal(err)
}
}()
err := HitBTC.SubscribeCandles(params)
if err != nil {
log.Panic(err)
}
}
|
// Copyright 2020 Ant Group. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
package rule
import (
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"github.com/dragonflyoss/image-service/contrib/nydusify/pkg/checker/tool"
"github.com/pkg/errors"
"github.com/pkg/xattr"
"github.com/sirupsen/logrus"
"lukechampine.com/blake3"
)
// FilesystemRule compares file metadata and data in the two mountpoints:
// Mounted by Nydusd for Nydus image,
// Mounted by Overlayfs for OCI image.
type FilesystemRule struct {
NydusdConfig tool.NydusdConfig
Source string
SourceMountPath string
}
// Node records file metadata and file data hash.
type Node struct {
Path string
Size int64
Mode os.FileMode
Xattrs map[string][]byte
Hash []byte
}
func (node *Node) String() string {
return fmt.Sprintf(
"Path: %s, Size: %d, Mode: %d, Xattrs: %v, Hash: %s",
node.Path, node.Size, node.Mode, node.Xattrs, hex.EncodeToString(node.Hash),
)
}
func (rule *FilesystemRule) Name() string {
return "Filesystem"
}
func hashFile(path string) ([]byte, error) {
hasher := blake3.New(32, nil)
file, err := os.Open(path)
if err != nil {
return nil, errors.Wrap(err, "open file before hashing file")
}
defer file.Close()
buf := make([]byte, 2<<15) // 64KB
for {
n, err := file.Read(buf)
if err == io.EOF || n == 0 {
break
}
if err != nil {
return nil, errors.Wrap(err, "read file during hashing file")
}
if _, err := hasher.Write(buf); err != nil {
return nil, errors.Wrap(err, "calculate hash of file")
}
}
return hasher.Sum(nil), nil
}
func getXattrs(path string) (map[string][]byte, error) {
xattrs := make(map[string][]byte)
names, err := xattr.LList(path)
if err != nil {
return nil, err
}
for _, name := range names {
data, err := xattr.LGet(path, name)
if err != nil {
return nil, err
}
xattrs[name] = data
}
return xattrs, nil
}
func (rule *FilesystemRule) walk(rootfs string) (map[string]Node, error) {
nodes := map[string]Node{}
if err := filepath.Walk(rootfs, func(path string, info os.FileInfo, err error) error {
if err != nil {
logrus.Warnf("Failed to stat in mountpoint: %s", err)
return nil
}
rootfsPath, err := filepath.Rel(rootfs, path)
if err != nil {
return err
}
rootfsPath = filepath.Join("/", rootfsPath)
var size int64
if !info.IsDir() {
// Ignore directory size check
size = info.Size()
}
mode := info.Mode()
xattrs, err := getXattrs(path)
if err != nil {
logrus.Warnf("Failed to get xattr: %s", err)
}
// Calculate file data hash if the `backend-type` option be specified,
// this will cause that nydusd read data from backend, it's network load
var hash []byte
if rule.NydusdConfig.BackendType != "" && info.Mode().IsRegular() {
hash, err = hashFile(path)
if err != nil {
return err
}
}
node := Node{
Path: rootfsPath,
Size: size,
Mode: mode,
Xattrs: xattrs,
Hash: hash,
}
nodes[rootfsPath] = node
return nil
}); err != nil {
return nil, err
}
return nodes, nil
}
func (rule *FilesystemRule) mountSourceImage() (*tool.Image, error) {
logrus.Infof("Mounting source image to %s", rule.SourceMountPath)
if err := os.MkdirAll(rule.SourceMountPath, 0755); err != nil {
return nil, errors.Wrap(err, "create mountpoint directory of source image")
}
image := &tool.Image{
Source: rule.Source,
Rootfs: rule.SourceMountPath,
}
if err := image.Pull(); err != nil {
return nil, errors.Wrap(err, "pull source image")
}
if err := image.Mount(); err != nil {
return nil, errors.Wrap(err, "mount source image")
}
return image, nil
}
func (rule *FilesystemRule) mountNydusImage() (*tool.Nydusd, error) {
logrus.Infof("Mounting Nydus image to %s", rule.NydusdConfig.MountPath)
if err := os.MkdirAll(rule.NydusdConfig.BlobCacheDir, 0755); err != nil {
return nil, errors.Wrap(err, "create blob cache directory for Nydusd")
}
if err := os.MkdirAll(rule.NydusdConfig.MountPath, 0755); err != nil {
return nil, errors.Wrap(err, "create mountpoint directory of Nydus image")
}
nydusd, err := tool.NewNydusd(rule.NydusdConfig)
if err != nil {
return nil, errors.Wrap(err, "create Nydusd daemon")
}
if err := nydusd.Mount(); err != nil {
return nil, errors.Wrap(err, "mount Nydus image")
}
return nydusd, nil
}
func (rule *FilesystemRule) verify() error {
logrus.Infof("Verifying filesystem for source and Nydus image")
validate := true
sourceNodes := map[string]Node{}
// Concurrently walk the rootfs directory of source and Nydus image
walkErr := make(chan error)
go func() {
var err error
sourceNodes, err = rule.walk(rule.SourceMountPath)
walkErr <- err
}()
nydusNodes, err := rule.walk(rule.NydusdConfig.MountPath)
if err != nil {
return errors.Wrap(err, "walk rootfs of Nydus image")
}
if err := <-walkErr; err != nil {
return errors.Wrap(err, "walk rootfs of source image")
}
for path, sourceNode := range sourceNodes {
nydusNode, exist := nydusNodes[path]
if !exist {
logrus.Warnf("File not found in Nydus image: %s", path)
validate = false
continue
}
delete(nydusNodes, path)
if path != "/" && !reflect.DeepEqual(sourceNode, nydusNode) {
logrus.Warnf("File not match in Nydus image: %s <=> %s", sourceNode.String(), nydusNode.String())
validate = false
}
}
for path := range nydusNodes {
logrus.Warnf("File not found in source image: %s", path)
validate = false
}
if !validate {
return fmt.Errorf("Failed to verify source image and Nydus image")
}
return nil
}
func (rule *FilesystemRule) Validate() error {
// Skip filesystem validation if no source image be specified
if rule.Source == "" {
return nil
}
image, err := rule.mountSourceImage()
if err != nil {
return err
}
defer image.Umount()
nydusd, err := rule.mountNydusImage()
if err != nil {
return err
}
defer nydusd.Umount()
if err := rule.verify(); err != nil {
return err
}
return nil
}
|
package apps
import (
"fmt"
"os"
"sort"
"text/tabwriter"
"time"
)
type Formation struct {
Type string `json:"type"`
Size string `json:"size"`
Quantity uint8 `json:"quantity"`
}
func (app *App) FormationLoad() error {
var (
data []Formation
formation map[string]Formation
)
err := app.HttpV3("GET", nil, &data, "/apps/%s/formation", app.AppName)
if err != nil {
return err
}
formation = make(map[string]Formation, len(data))
for _, typ := range data {
formation[typ.Type] = typ
}
app.formation = formation
return nil
}
func (app *App) FormationBreak() error {
var (
tabw = tabwriter.NewWriter(os.Stdout, 8, 8, 1, ' ', 0)
)
fmt.Println("Break formation:")
err := app.FormationLoad()
if err != nil {
return err
}
// sort keys
keys := make([]string, 0, len(app.formation))
for key := range app.formation {
keys = append(keys, key)
}
sort.Strings(keys)
// scale formation
for _, key := range keys {
formation := app.formation[key]
if formation.Quantity == 0 {
fmt.Fprintf(tabw, " - %s\tquantity=%d\tsize=%s\n",
formation.Type, formation.Quantity, formation.Size)
continue
}
formation.Quantity = 0
err = app.HttpV3("PATCH", &formation, nil, "/apps/%s/formation/%s", app.AppName, formation.Type)
if err != nil {
fmt.Fprintf(tabw, " - %s\tquantity=%d\tsize=%s\t\x1b[31;40;4;5m(failed to pause)\x1b[0m\n error: %s\n",
formation.Type, formation.Quantity, formation.Size, err)
} else {
fmt.Fprintf(tabw, " - %s\tquantity=%d\tsize=%s\t\x1b[32m(paused)\x1b[0m\n",
formation.Type, formation.Quantity, formation.Size)
}
}
tabw.Flush()
if err = app.wait_until_dynos_are_down(); err != nil {
return err
}
return nil
}
func (app *App) FormationRestore() error {
var (
tabw = tabwriter.NewWriter(os.Stdout, 8, 8, 1, ' ', 0)
count = 0
)
fmt.Println("Restore formation:")
prev_formation := app.formation
err := app.FormationLoad()
if err != nil {
return err
}
for key := range app.formation {
prev, ok := prev_formation[key]
if !ok {
continue
}
formation := app.formation[key]
formation.Quantity = prev.Quantity
app.formation[key] = formation
}
// sort keys
keys := make([]string, 0, len(app.formation))
for key := range app.formation {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
formation := app.formation[key]
count += int(formation.Quantity)
if formation.Quantity == 0 {
fmt.Fprintf(tabw, " - %s\tquantity=%d\tsize=%s\n",
formation.Type, formation.Quantity, formation.Size)
continue
}
err := app.HttpV3("PATCH", &formation, nil, "/apps/%s/formation/%s", app.AppName, formation.Type)
if err != nil {
fmt.Fprintf(tabw, " - %s\tquantity=%d\tsize=%s\t\x1b[31;40;4;5m(failed to restore)\x1b[0m\n error: %s\n",
formation.Type, formation.Quantity, formation.Size, err)
} else {
fmt.Fprintf(tabw, " - %s\tquantity=%d\tsize=%s\t\x1b[32m(restored)\x1b[0m\n",
formation.Type, formation.Quantity, formation.Size)
}
}
tabw.Flush()
if err := app.wait_until_dynos_are_up(count); err != nil {
return err
}
return nil
}
func (app *App) wait_until_dynos_are_down() error {
if app.config.DryRun {
return nil
}
deadline := time.Now().Add(5 * time.Minute)
for time.Now().Before(deadline) {
ok, err := app.are_all_dynos_down()
if err != nil {
time.Sleep(10 * time.Second)
continue
}
if ok {
return nil
}
time.Sleep(1 * time.Second)
}
return fmt.Errorf("formation: unable to stop dynos")
}
func (app *App) wait_until_dynos_are_up(count int) error {
if app.config.DryRun {
return nil
}
deadline := time.Now().Add(5 * time.Minute)
for time.Now().Before(deadline) {
ok, err := app.are_all_dynos_up(count)
if err != nil {
time.Sleep(10 * time.Second)
continue
}
if ok {
return nil
}
time.Sleep(1 * time.Second)
}
return fmt.Errorf("formation: unable to start dynos")
}
func (app *App) are_all_dynos_down() (bool, error) {
var (
data []struct {
State string `json:"state"`
}
)
err := app.HttpV3("GET", nil, &data, "/apps/%s/dynos", app.AppName)
if err != nil {
return false, err
}
if len(data) == 0 {
return true, nil
}
return false, nil
}
func (app *App) are_all_dynos_up(count int) (bool, error) {
var (
data []struct {
AttachUrl *string `json:"attach_url"`
State string `json:"state"`
}
)
err := app.HttpV3("GET", nil, &data, "/apps/%s/dynos", app.AppName)
if err != nil {
return false, err
}
for _, dyno := range data {
if dyno.AttachUrl == nil {
if dyno.State == "up" {
count--
}
}
}
return count == 0, nil
}
|
package main
import "testing"
func TestEncode(t *testing.T) {
tests := []struct {
input string
output string
error string
}{
{"aabbbcadddd", "2a3b1c1a4d", ""},
{"aaaaaaaaaa", "10a", ""},
{"ab", "1a1b", ""},
{"aa", "2a", ""},
{"a", "1a", ""},
{"__+", "2_1+", ""},
{"", "", ""},
{"1a", "", "String cannot contain numbers"},
}
for _, test := range tests {
result, err := Encode(test.input)
if result != test.output {
t.Errorf("%s should have returned %s", test.input, test.output)
}
if err != nil && err.Error() != test.error {
t.Errorf("Expected error: %s", test.error)
}
}
}
|
package main
import "fmt"
// `MetaOwn` adalah metode yang akan diteken nantinya
// umumnya/yang paling dekat digunakan antar
// struct yang bermacam2 dg kebutuhan data yang mirip/sama
type MetaOwn interface {
// mendaftarkan `declared lambda function` sbg kontrak interface MetaOwn
GetName() string //dengan return string :D
GetBorn() string
// karena tiap2 dari kontrak bersifat dinamik(didalam sistem)
// maka fungsi harus tetap diterapkan scr eksplisit
// untuk fungsi spesifik yang memiliki nilai return spesifik
// contoh
// func *lambda(args1 typeofArg1) signature type{
// return args1.obj
// }
}
// fungsi kontrak yang turut terdeklarasi scr eksplisit
// mempergunakan/memfungsikan kontrak yang telah dideklarasikan
// dan dilanjut mempointing kontrak ke spesifik struct/method lain2
//membuat fungsi `Getname()` dan `GetBorn()` dengan return nilai `string`
func (user Person) GetName() string {
// meta `GetName()` dipointing ke `struct Person.Name`
return user.Name
}
func (user Person) GetBorn() string {
// meta `GetBorn()` dipointing ke `struct Person.Lahir`
return user.Lahir
}
// ============================================
// fungsi yang akan dipanggil
// dengan `MetaOwn` sbg args1
func ucapPagi(meta MetaOwn) {
// mengambil/menggunakan metode `GetName()`
// dari `meta` yang ada didalam kontrak `MetaOwn`
fmt.Println("Pagi, Namaku adalah: ", meta.GetName())
}
func dimanaLahir(meta MetaOwn) {
// konsep sama. cuma dari metode kontrak GetBorn dengan return nilai ttp string
fmt.Println("Saya lahir di:", meta.GetBorn())
}
// ============================================
// ============================================
// ============================================
// COL (Collection of Field) orang
// yang berisikan data nama,lahir, alamat
type Person struct {
Name string
Lahir string
// Alamat string
}
// ============================================
// ============================================
func main() {
var user1 Person // `user1` adalah object/data berjenis Person
user1.Name = "budi"
user1.Lahir = "Yogyakarta"
// fungsi yang akan dipanggil
ucapPagi(user1)
dimanaLahir(user1)
}
|
package service
import (
"log"
"github.com/rudeigerc/broker-gateway/mapper"
"github.com/rudeigerc/broker-gateway/model"
)
type Trade struct {
}
func (t Trade) NewTrade(trade *model.Trade) {
m := mapper.NewMapper()
err := m.Create(trade)
if err != nil {
log.Printf("[service.order.NewOrder] [ERROR] %s", err)
}
}
func (t Trade) Trades() []model.Trade {
m := mapper.NewMapper()
var trades []model.Trade
err := m.FindWithLimit(&trades, -1)
if err != nil {
log.Printf("[service.trade.Trades] [ERROR] %s", err)
}
return trades
}
func (t Trade) TradeByID(uuid string) model.Trade {
m := mapper.NewMapper()
trade := model.Trade{}
err := m.WhereByUUID(&trade, "trade_id", uuid)
if err != nil {
log.Printf("[service.order.OrderByID] [ERROR] %s", err)
}
return trade
}
func (t Trade) TradesSnapshot() map[string][]model.Trade {
m := mapper.NewMapper()
futuresIDs, err := m.FutureIDs()
if err != nil {
log.Printf("[service.trade.TradesSnapshot] [ERROR] %s", err)
}
tradesMap := make(map[string][]model.Trade)
for _, futuresID := range futuresIDs {
var trades []model.Trade
err := m.FindByFuturesID(&trades, futuresID)
if err != nil {
log.Printf("[service.trade.TradesSnapshot] [ERROR] %s", err)
}
tradesMap[futuresID] = trades
}
return tradesMap
}
func (t Trade) TradesWithPage(page int) (int, []model.Trade) {
m := mapper.NewMapper()
var (
trades []model.Trade
total int
)
err := m.FindWithPage(&trades, page, &total)
if err != nil {
log.Printf("[service.trade.OrdersWithPage] [ERROR] %s", err)
}
return total, trades
}
func (t Trade) TradesWithCondition(firmID int, futuresID string, traderName string, page int) (int, []model.Trade) {
m := mapper.NewMapper()
var (
trades []model.Trade
total int
err error
)
if firmID != -1 {
err = m.FindTradesWithCondition(&trades, firmID, futuresID, traderName, page, &total)
} else {
err = m.FindTrades(&trades, futuresID, traderName, page, &total)
}
if err != nil {
log.Printf("[service.trade.TradesWithCondition] [ERROR] %s", err)
}
return total, trades
}
|
package main
import "fmt"
func makesquare(nums []int) bool {
sums := make([]int, 4)
sum := 0
for _, n := range nums {
sum += n
}
if sum % 4 != 0 {
return false
}
sum /= 4
return dfs(nums, 0, sums, sum)
}
func dfs(nums []int, i int, sums []int, sum int) bool {
if i == len(nums) {
//fmt.Println(sums)
if sums[0] == 0 {
return false
}
for j:=1; j<4; j++ {
if sums[0] != sums[j] {
return false
}
}
return true
}
for j := 0; j < 4; j++ {
//fmt.Println(i, j)
sums[j] += nums[i]
if sums[j] > sum {
sums[j] -= nums[i]
continue
}
if dfs(nums, i+1, sums, sum) {
return true
}
sums[j] -= nums[i]
}
return false
}
func main() {
fmt.Println(makesquare([]int{1,2,3,4,5,6,7,8,9,10,5,4,3,2,1}))
fmt.Println(makesquare([]int{1,1,2,2,2}))
fmt.Println(makesquare([]int{2,2,2,2,2,2}))
fmt.Println(makesquare([]int{3,3,3,3,4}))
} |
package v1
import (
"context"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
)
type ConfigMapGetter interface {
ConfigMap(namespace string)
}
type ConfigMapInterface interface {
Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.ConfigMap, error)
Create(ctx context.Context, configMapData *v1.ConfigMap, opts metav1.CreateOptions) (*v1.ConfigMap, error)
Update(ctx context.Context, configMapData *v1.ConfigMap, opts metav1.UpdateOptions) (*v1.ConfigMap, error)
Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error
Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)
}
type configMap struct {
client *kubernetes.Clientset
ns string
}
func newConfigMap(c *kubernetes.Clientset, ns string) *configMap {
return &configMap{
client: c,
ns: ns,
}
}
func (c *configMap) Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.ConfigMap, error) {
return c.client.CoreV1().
ConfigMaps(c.ns).
Get(ctx, name, opts)
}
func (c *configMap) Create(ctx context.Context, configMapData *v1.ConfigMap, opts metav1.CreateOptions) (*v1.ConfigMap, error) {
return c.client.CoreV1().
ConfigMaps(c.ns).
Create(ctx, configMapData, opts)
}
func (c *configMap) Update(ctx context.Context, configMapData *v1.ConfigMap, opts metav1.UpdateOptions) (*v1.ConfigMap, error) {
return c.client.CoreV1().
ConfigMaps(c.ns).
Update(ctx, configMapData, opts)
}
func (c *configMap) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {
return c.client.CoreV1().
ConfigMaps(c.ns).
Delete(ctx, name, &opts)
}
func (c *configMap) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {
return c.client.CoreV1().
ConfigMaps(c.ns).
Watch(ctx, opts)
}
|
package unbufferedchannels
import (
"sync"
)
/*work package is to show how you can use an unbuffered channel
to create a pool of goroutines that will perform and control
the amount of work that gets done concurrently. This is a better
approach than using a buffered channel of some arbitrary
static size that acts as a queue of work and throwing
a bunch of goroutines at it.
Unbuffered channels provide a guarantee that data has been
exchanged between two goroutines. This approach of using an unbuffered
channel allows the user to know when the pool is performing the work,
and the channel pushes back when it can’t accept any more work because
it’s busy. No work is ever lost or stuck in a queue that has no guarantee
it will ever be worked on.*/
type Worker interface {
Task()
}
//Pool provides a pool of goroutines that execute any Work tasks submitted
type Pool struct {
work chan Worker
wg sync.WaitGroup
}
//New createes a new work pool
func New(maxGoroutines int) *Pool {
p := Pool{
work: make(chan Worker),
}
for i := 0; i < maxGoroutines; i++ {
go func() {
for w := range p.work {
w.Task()
}
p.wg.Done()
}()
}
return &p
}
//Run submits work to the pools
func (p *Pool) Run(w Worker) {
p.work <- w
}
//Shutdown wiats for goroutines to shutdown
func (p *Pool) Shutdown() {
close(p.work)
p.wg.Wait()
}
|
package main
import (
"fmt"
"io"
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/tuanden0/simple_api/internal/models"
)
const ADDR string = ":8000"
func main() {
// Disable Console Color, you don't need console color when writing the logs to file.
gin.DisableConsoleColor()
// Logging to a file.
f, _ := os.Create("gin.log")
// Use the following code if you need to write the logs to file and console at the same time.
gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
router := gin.New()
// LoggerWithFormatter middleware will write the logs to gin.DefaultWriter
// By default gin.DefaultWriter = os.Stdout
router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
// your custom format
return fmt.Sprintf("%s - [%s]\t\"%s\t%s\t%s\t%d\t%s\t%s\"\n",
param.ClientIP,
param.TimeStamp.Format(time.RFC1123),
param.Method,
param.Path,
param.Request.Proto,
param.StatusCode,
param.Latency,
param.ErrorMessage,
)
}))
router.Use(gin.Recovery())
models.ConnectDatabase()
router.Run(ADDR)
}
|
package base
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"github.com/bwmarrin/discordgo"
)
func (b *Base) GetColor(guild, id string) (int, error) {
b.lock.RLock()
dat, exists := b.dat[guild]
b.lock.RUnlock()
if exists {
col, exists := dat.UserColors[id]
if exists {
return col, nil
}
}
mem, err := b.dg.State.Member(guild, id)
if err != nil {
mem, err = b.dg.GuildMember(guild, id)
if err != nil {
fmt.Println(err)
return 0, err
}
}
roles := make([]*discordgo.Role, len(mem.Roles))
for i, roleID := range mem.Roles {
role, err := b.GetRole(roleID, guild)
if err != nil {
return 0, err
}
roles[i] = role
}
sorted := discordgo.Roles(roles)
sort.Sort(sorted)
for _, role := range sorted {
if role.Color != 0 {
return role.Color, nil
}
}
return 0, errors.New("eod: color not found")
}
func (b *Base) GetRole(id string, guild string) (*discordgo.Role, error) {
role, err := b.dg.State.Role(guild, id)
if err == nil {
return role, nil
}
roles, err := b.dg.GuildRoles(guild)
if err != nil {
return nil, err
}
for _, role := range roles {
if role.ID == id {
return role, nil
}
}
return nil, errors.New("eod: role not found")
}
func (b *Base) SaveInv(guild string, user string, newmade bool, recalculate ...bool) {
b.lock.RLock()
dat, exists := b.dat[guild]
b.lock.RUnlock()
if !exists {
return
}
inv, _ := dat.GetInv(user, true)
dat.Lock.RLock()
data, err := json.Marshal(inv.Elements)
dat.Lock.RUnlock()
if err != nil {
return
}
if newmade {
m := "made+1"
if len(recalculate) > 0 {
count := 0
for val := range inv.Elements {
creator := ""
elem, res := dat.GetElement(val)
if res.Exists {
creator = elem.Creator
}
if creator == user {
count++
}
}
m = strconv.Itoa(count)
inv.MadeCnt = count
} else {
inv.MadeCnt++
}
dat.SetInv(user, inv)
b.db.Exec(fmt.Sprintf("UPDATE eod_inv SET inv=?, count=?, made=%s WHERE guild=? AND user=?", m), data, len(inv.Elements), guild, user)
return
}
b.db.Exec("UPDATE eod_inv SET inv=?, count=? WHERE guild=? AND user=?", data, len(inv.Elements), guild, user)
}
|
package data
import (
"crypto/md5"
"fmt"
"time"
)
// Event data respresentation
type Event struct {
ID string
User string
Domain string
Action string
Timestamp time.Time
}
// Hydrate populates event record with additional derived data
func (e *Event) Hydrate() {
if e.ID == "" {
s := fmt.Sprintf("%s-%s-%s", e.User, e.Action, e.Timestamp)
e.ID = fmt.Sprintf("%x", md5.Sum([]byte(s)))
}
}
|
package rpcd
import (
"github.com/Cloud-Foundations/Dominator/dom/herd"
"github.com/Cloud-Foundations/Dominator/lib/log"
"github.com/Cloud-Foundations/Dominator/lib/srpc"
"github.com/Cloud-Foundations/Dominator/lib/srpc/serverutil"
)
type rpcType struct {
herd *herd.Herd
logger log.Logger
*serverutil.PerUserMethodLimiter
}
func Setup(herd *herd.Herd, logger log.Logger) {
rpcObj := &rpcType{
herd: herd,
logger: logger,
PerUserMethodLimiter: serverutil.NewPerUserMethodLimiter(
map[string]uint{
"ClearSafetyShutoff": 1,
}),
}
srpc.RegisterNameWithOptions("Dominator", rpcObj,
srpc.ReceiverOptions{
PublicMethods: []string{
"ClearSafetyShutoff",
}})
}
|
package controllers
import (
"github.com/astaxie/beego"
. "hello/models"
"fmt"
"encoding/json"
)
type MyJsonData struct {
Name string
Age int
}
type MyController struct {
beego.Controller
}
func (this *MyController) Get() {
// this.Ctx.WriteString("hes")
myData := &MyJsonData{Name : "name", Age : 100}
// var jsonString string
value, _ := json.Marshal(myData)
this.Data["json"] = string(value)
this.ServeJSON()
fmt.Println(string(value))
}
func getAll() []User {
users:=make([]User, 2, 2)
users[0] = User{UserName:"name1", Pwd:"100"}
users[1] = User{UserName:"name2", Pwd:"100"}
return users
}
func (this *MyController) GetUser() {
// id := this.GetString(":id")
// this.Ctx.WriteString(id)
// fmt.Println(models.GetUser(id))
// var myData myJsonData
myData := getAll()
// var jsonString string
value, _ := json.Marshal(myData)
this.Data["json"] = string(value)
this.ServeJSON()
fmt.Println(string(value))
// if err != nil {
// this.Data["json"] = string(value)
// this.ServeJSON()
// }
}
// func (this *MyController) SaveTestUser {
// SaveTestUser()
// }
func (this *MyController) GetAllUser() {
myData := GetAllUser()
value, _ := json.Marshal(myData)
this.Data["json"] = string(value)
this.ServeJSON()
}
|
package main_test
import (
"testing"
)
func TestCreate(t *testing.T) {
testCases := []struct {
desc string
path string
verb string
expected int
}{
{
desc: "Create a new payment",
path: "/payments",
verb: "POST",
expected: 201,
/*
## Notes
- If your API uses POST to create a resource, be sure to include a Location header in the response that includes the URL of the newly-created resource, along with a 201 status code — that is part of the HTTP standard.
*/
},
{
desc: "Create a new payment on a pre-existing ID",
path: "/payments/1234-5678-abcd",
verb: "POST",
expected: 409,
},
{
desc: "Create a new payment on a non-existent valid ID",
path: "/payments/1234-5678-abcd",
verb: "POST",
expected: 404,
},
{
desc: "Create a new payment on an invalid ID",
path: "/payments/my-payment-id",
verb: "POST",
expected: 404,
},
}
for _, tC := range testCases {
t.Run(tC.desc, func(t *testing.T) {
})
}
}
func TestRead(t *testing.T) {
testCases := []struct {
desc string
path string
verb string
expected int
}{
{
desc: "Read the entire collection of existing payments",
path: "/payments",
verb: "GET",
expected: 200,
},
{
desc: "Read a limited collection of existing payments",
path: "/payments?offset=2&limit=2",
verb: "GET",
expected: 200,
},
{
desc: "Read a single existing payment",
path: "/payments/1234-5678-abcd",
verb: "GET",
expected: 200,
},
{
desc: "Read a non-existent payment at a valid ID",
path: "/payments/1234-5678-abcd",
verb: "GET",
expected: 404,
},
{
desc: "Read a non-existent payment at an invalid ID",
path: "/payments/my-payment-id",
verb: "GET",
expected: 404,
},
}
for _, tC := range testCases {
t.Run(tC.desc, func(t *testing.T) {
})
}
}
func TestUpdate(t *testing.T) {
testCases := []struct {
desc string
path string
verb string
expected int
}{
{
desc: "Update all existing payments",
path: "/payments",
verb: "PUT",
expected: 405,
},
{
desc: "Update an existing payment",
path: "/payments/1234-5678-abcd",
verb: "PUT",
expected: 204, // update is OK, but response has no body/content
},
{
desc: "Update a non-existent payment at a valid ID",
path: "/payments/1234-5678-abcd",
verb: "PUT",
expected: 404,
},
{
desc: "Update a non-existent payment at an invalid ID",
path: "/payments/1234-5678-abcd",
verb: "PUT",
expected: 404,
},
}
for _, tC := range testCases {
t.Run(tC.desc, func(t *testing.T) {
})
}
}
func TestDelete(t *testing.T) {
testCases := []struct {
desc string
path string
verb string
expected int
}{
{
desc: "Delete all existing payments",
path: "/payments",
verb: "DELETE",
expected: 405,
},
{
desc: "Delete an existing payment at a valid ID",
path: "/payments/1234-5678-abcd",
verb: "DELETE",
expected: 200,
},
{
desc: "Delete a non-existent payment at a valid ID",
path: "/payments/1234-5678-abcd",
verb: "DELETE",
expected: 404,
},
{
desc: "Delete a non-existent payment at an invalid ID",
path: "/payments/my-payment-id",
verb: "DELETE",
expected: 404,
},
}
for _, tC := range testCases {
t.Run(tC.desc, func(t *testing.T) {
})
}
}
|
package server
import (
"strconv"
"github.com/Tanibox/tania-core/src/helper/validationhelper"
"github.com/Tanibox/tania-core/src/assets/domain"
)
func (rv *RequestValidation) ValidateReservoirName(name string) (string, error) {
if name == "" {
return "", NewRequestValidationError(REQUIRED, "name")
}
if !validationhelper.IsAlphanumSpaceHyphenUnderscore(name) {
return "", NewRequestValidationError(ALPHANUMERIC, "name")
}
return name, nil
}
func (rv *RequestValidation) ValidateCapacity(waterSourceType, capacity string) (float32, error) {
if waterSourceType == domain.TapType {
return 0, nil
}
if capacity == "" {
return 0, NewRequestValidationError(REQUIRED, "capacity")
}
if !validationhelper.IsFloat(capacity) {
return 0, NewRequestValidationError(FLOAT, "capacity")
}
c, err := strconv.ParseFloat(capacity, 32)
if err != nil {
return 0, NewRequestValidationError(PARSE_FAILED, "capacity")
}
return float32(c), nil
}
func (rv *RequestValidation) ValidateType(t string) (string, error) {
if t == "" {
return "", NewRequestValidationError(REQUIRED, "type")
}
if !validationhelper.IsAlpha(t) {
return "", NewRequestValidationError(ALPHA, "type")
}
if t != domain.BucketType && t != domain.TapType {
return "", NewRequestValidationError(INVALID_OPTION, "type")
}
return t, nil
}
|
package msg_test
import (
"OrgTimer/msg"
"fmt"
"testing"
"time"
)
func genMsgs(baseTime time.Time, number int) (res msg.MsgList) {
for i := 0; i < number; i++ {
msg := msg.NewOrgMsg(fmt.Sprintf("title[%v]", i), "", baseTime.Add(time.Hour))
res = append(res, &msg)
}
return res
}
func TestMergeTerminal(t *testing.T) {
baseTime := time.Now()
tMsgs := msg.NewTerminalMsg("t", "", baseTime)
oldMsgs := genMsgs(baseTime, 4)
oriMsgs := append(oldMsgs, &tMsgs)
oldMsgs = append(oldMsgs, &tMsgs)
newMsgs := genMsgs(baseTime, 4)
oldMsgs.Merge(newMsgs)
if !oldMsgs.EqualsAll(oriMsgs) {
t.Errorf("wrong, ori:%v, merged:%v", oriMsgs.ToString(), oldMsgs.ToString())
}
}
func TestMergeRemoved(t *testing.T) {
baseTime := time.Now()
oldMsgs := genMsgs(baseTime, 4)
newMsgs := genMsgs(baseTime, 3)
oldMsgs.Merge(newMsgs)
if !oldMsgs.EqualsAll(newMsgs) {
t.Errorf("wrong, ori:%v, merged:%v", genMsgs(baseTime, 4).ToString(), oldMsgs.ToString())
}
}
func TestMergeActiv(t *testing.T) {
baseTime := time.Now()
oldMsgs := genMsgs(baseTime, 4)
oldMsgs[0].Activate()
oriMsgs := genMsgs(baseTime, 4)
oriMsgs[0].Activate()
if !oldMsgs[0].IsActiv() {
t.Errorf("msg:%v should be activ", oldMsgs[0].ToString())
}
newMsgs := genMsgs(baseTime, 3)
resMsgs := genMsgs(baseTime, 3)
resMsgs[0].Activate()
oldMsgs.Merge(newMsgs)
if !oldMsgs.EqualsAll(resMsgs) {
t.Errorf("wrong, oldMsgs:%v, merged:%v, resMsgs:%v", oriMsgs.ToString(), oldMsgs.ToString(), resMsgs.ToString())
}
}
func TestMergeInit(t *testing.T) {
baseTime := time.Now()
var oldMsgs msg.MsgList
newMsgs := genMsgs(baseTime, 3)
resMsgs := genMsgs(baseTime, 3)
// resMsgs[0].Activate()
oldMsgs.Merge(newMsgs)
if !oldMsgs.EqualsAll(resMsgs) {
t.Errorf("wrong, oldMsgs:%v, merged:%v, resMsgs:%v", genMsgs(baseTime, 0).ToString(), oldMsgs.ToString(), resMsgs.ToString())
}
}
func TestClean(t *testing.T) {
baseTime := time.Now()
oldMsgs := genMsgs(baseTime, 4)
newMsgs := genMsgs(baseTime, 4)
newMsgs[3].Cancel()
newMsgs.Clean()
if !newMsgs.EqualsAll(genMsgs(baseTime, 3)) {
t.Errorf("wrong, old:%v, merged:%v", oldMsgs.ToString(), newMsgs.ToString())
}
}
|
package main
import (
database "goql/dao"
handlers "goql/handlers"
"log"
"net/http"
)
func main() {
database.Connect()
http.HandleFunc("/add", handlers.AddUser) // curl -s -D - -H "Content-Type: application/json;charset=utf-8" -X POST http://localhost:8080/json -d '{"bookID": 3232, "bookName": "Cime Tempestose", "author": "Gigi Bom"}'
http.HandleFunc("/get", handlers.GetAllUsers) // curl -H "Authorization: superSecretToken" http://localhost:8080/token
log.Fatal(http.ListenAndServe(":8080", nil))
} |
package main
import (
"fmt"
"sync"
"github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter10/atomic"
)
func main() {
o := atomic.NewOrdinal()
m := atomic.NewSafeMap()
o.Init(1123)
fmt.Println("initial ordinal is:", o.GetOrdinal())
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
m.Set(fmt.Sprint(i), "success")
o.Increment()
}(i)
}
wg.Wait()
for i := 0; i < 10; i++ {
v, err := m.Get(fmt.Sprint(i))
if err != nil || v != "success" {
panic(err)
}
}
fmt.Println("final ordinal is:", o.GetOrdinal())
fmt.Println("all keys found and marked as: 'success'")
}
|
package main
import (
"net"
current "github.com/containernetworking/cni/pkg/types/100"
"github.com/pkg/errors"
)
// getIPs iterates a result and returns all the IP addresses
// associated with it
func getIPs(r *current.Result) ([]*net.IPNet, error) {
var (
ips []*net.IPNet
)
if len(r.IPs) < 1 {
return nil, ErrNoIPAddressFound
}
if len(r.IPs) == 1 {
return append(ips, &r.IPs[0].Address), nil
}
for _, ip := range r.IPs {
if ip.Address.IP != nil && ip.Interface != nil {
if isInterfaceIndexSandox(*ip.Interface, r) {
ips = append(ips, &ip.Address)
} else {
return nil, errors.Errorf("unable to check if interface has a sandbox due to index being out of range")
}
}
}
if len(ips) < 1 {
return nil, ErrNoIPAddressFound
}
return ips, nil
}
// isInterfaceIndexSandox determines if the given interface index has the sandbox
// attribute and the value is greater than 0
func isInterfaceIndexSandox(idx int, r *current.Result) bool {
if idx >= 0 && idx < len(r.Interfaces) {
return len(r.Interfaces[idx].Sandbox) > 0
}
return false
}
// getInterfaceAddresses gets all globalunicast IP addresses for a given
// interface
func getInterfaceAddresses(nameConf dnsNameFile) ([]string, error) {
var nameservers []string
nic, err := net.InterfaceByName(nameConf.NetworkInterface)
if err != nil {
return nil, err
}
addrs, err := nic.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
return nil, err
}
if ip.IsGlobalUnicast() {
nameservers = append(nameservers, ip.String())
}
}
return nameservers, nil
}
|
package pathfileops
import (
"errors"
"fmt"
"io"
"math"
"os"
"path"
fp "path/filepath"
"strings"
"time"
)
/*
'filehelper.go' - Contains type 'FileHelper' and related data structures.
The 'FileHelper' type provides methods used in managing files and
directories.
The Source Repository for this source code file is :
https://github.com/MikeAustin71/pathfilego.git
'FileHelper' is a dependency of 'DirMgr' and 'FileMgr'. 'FileMgr'
is located in source file 'filemanager.go'. 'DirMgr' is located
in 'dirmanager.go'.
*/
// FileHelper - The methods associated with this type provide
// generalized file creation, management and maintenance utilities.
//
// 'FileHelper' is a dependency for types 'DirMgr' and 'FileMgr'.
type FileHelper struct {
Input string
Output string
}
// AddPathSeparatorToEndOfPathStr - Receives a path string as an input
// parameter. If the last character of the path string is not a path
// separator, this method will add a path separator to the end of that
// path string and return it to the calling method.
//
func (fh FileHelper) AddPathSeparatorToEndOfPathStr(pathStr string) (string, error) {
ePrefix := "FileHelper.AddPathSeparatorToEndOfPathStr() "
errCode := 0
lStr := 0
errCode, lStr, pathStr = fh.isStringEmptyOrBlank(pathStr)
if errCode == -1 {
return "", errors.New(ePrefix + "Error: Input parameter 'pathStr' is an empty string!")
}
if errCode == -2 {
return "", errors.New(ePrefix + "Error: Input parameter 'pathStr' consists of blank spaces!")
}
if pathStr[lStr-1] == os.PathSeparator {
return pathStr, nil
}
var newPathStr string
if pathStr[lStr-1] == '/' && '/' != os.PathSeparator {
newPathStr = pathStr[0 : lStr-1]
newPathStr += string(os.PathSeparator)
return newPathStr, nil
}
if pathStr[lStr-1] == '\\' && '\\' != os.PathSeparator {
newPathStr = pathStr[0 : lStr-1]
newPathStr += string(os.PathSeparator)
return newPathStr, nil
}
newPathStr = pathStr + string(os.PathSeparator)
return newPathStr, nil
}
// AdjustPathSlash will standardize path
// separators according to operating system
func (fh FileHelper) AdjustPathSlash(path string) string {
errCode := 0
errCode, _, path = fh.isStringEmptyOrBlank(path)
if errCode == -1 {
return ""
}
if errCode == -2 {
return ""
}
if os.PathSeparator != '\\' {
return strings.ReplaceAll(path, "\\", string(os.PathSeparator))
}
if os.PathSeparator != '/' {
return strings.ReplaceAll(path, "/", string(os.PathSeparator))
}
return fp.FromSlash(path)
}
// AreSameFile - Compares two paths or path/file names to determine if they are
// the same and equivalent.
//
// An error will be triggered if one or both of the input parameters, 'pathFile1'
// and 'pathFile2' are empty/blank strings.
//
// If the path file input parameters identify the same file, this method returns
// 'true'.
//
// The two input parameters 'pathFile1' and 'pathFile2' will be converted to their
// absolute paths before comparisons are applied.
//
func (fh FileHelper) AreSameFile(pathFile1, pathFile2 string) (bool, error) {
ePrefix := "FileHelper.AreSameFile() "
var pathFile1DoesExist, pathFile2DoesExist bool
var fInfoPathFile1, fInfoPathFile2 FileInfoPlus
var err error
pathFile1,
pathFile1DoesExist,
fInfoPathFile1,
err = fh.doesPathFileExist(pathFile1,
PreProcPathCode.AbsolutePath(), // Convert To Absolute Path
ePrefix,
"pathFile1")
if err != nil {
return false, err
}
pathFile2,
pathFile2DoesExist,
fInfoPathFile2,
err = fh.doesPathFileExist(pathFile2,
PreProcPathCode.AbsolutePath(), // Convert To Absolute Path
ePrefix,
"pathFile2")
if err != nil {
return false, err
}
pathFile1 = strings.ToLower(pathFile1)
pathFile2 = strings.ToLower(pathFile2)
if pathFile1DoesExist && pathFile2DoesExist {
if os.SameFile(fInfoPathFile1.GetOriginalFileInfo(), fInfoPathFile2.GetOriginalFileInfo()) ||
pathFile1 == pathFile2 {
// pathFile1 and pathFile2 are the same
// path and file name.
return true, nil
}
return false, nil
}
if pathFile1 == pathFile2 {
return true, nil
}
return false, nil
}
// ChangeFileMode changes the file mode of an existing file designated by input
// parameter 'pathFileName'. The os.FileMode value to which the mode will be changed
// is extracted from input parameter 'filePermission'.
//
// If the file does Not exist, an error is triggered.
//
// If the method succeeds and the file's mode is changed, an error value of 'nil' is
// returned.
//
func (fh FileHelper) ChangeFileMode(pathFileName string, filePermission FilePermissionConfig) error {
ePrefix := "FileHelper.ChangeFileMode() "
var err error
var filePathDoesExist bool
pathFileName,
filePathDoesExist,
_,
err = fh.doesPathFileExist(
pathFileName,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"pathFileName")
if err != nil {
return err
}
if !filePathDoesExist {
return fmt.Errorf("ERROR: 'pathFileName' DOES NOT EXIST!\n"+
"pathFileName='%v'\n", pathFileName)
}
err = filePermission.IsValid()
if err != nil {
return fmt.Errorf(ePrefix+
"ERROR: Input parameter 'filePermission' is INVALID!\n"+
"Error='%v'\n", err.Error())
}
newOsFileMode, err := filePermission.GetFileMode()
if err != nil {
return fmt.Errorf(ePrefix+
"Error returned by filePermission.GetFileMode().\nError='%v'\n",
err.Error())
}
err = os.Chmod(pathFileName, newOsFileMode)
if err != nil {
changeModeTxt, _ := filePermission.GetPermissionTextCode()
changeModeValue := filePermission.GetPermissionFileModeValueText()
return fmt.Errorf(ePrefix+
"Error returned by os.Chmod(pathFileName, newOsFileMode).\n"+
"pathFileName='%v'\nnewOsFileMode Text='%v'\nnewOsFileModeValue='%v'\nError='%v'",
pathFileName, changeModeTxt, changeModeValue, err.Error())
}
return nil
}
// ChangeFileTimes - is a wrapper for os.Chtimes(). This method will set new access and
// modification times for a designated file.
//
// If the path and file name do not exist, this method will return an error.
//
// If successful, the access and modification times for the target file will be changed to
// to those specified by input parameters, 'newAccessTime' and 'newModTime'.
//
func (fh FileHelper) ChangeFileTimes(pathFileName string, newAccessTime, newModTime time.Time) error {
ePrefix := "FileHelper.ChangeFileTimes() "
var err error
var filePathDoesExist bool
var fInfo FileInfoPlus
pathFileName,
filePathDoesExist,
fInfo,
err = fh.doesPathFileExist(pathFileName,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"pathFileName")
if err != nil {
return err
}
if !filePathDoesExist {
return fmt.Errorf(ePrefix+
"ERROR: 'pathFileName' DOES NOT EXIST!\n"+
"pathFileName='%v'\n", pathFileName)
}
if fInfo.IsDir() {
return fmt.Errorf(ePrefix+
"ERROR: 'pathFileName' is a directory path and NOT a file!\n"+
"pathFileName='%v'\n", pathFileName)
}
tDefault := time.Time{}
if newAccessTime == tDefault {
return fmt.Errorf(ePrefix+
"Error: Input parameter 'newAccessTime' is INVALID!\nnewAccessTime='%v'",
newAccessTime)
}
if newModTime == tDefault {
return fmt.Errorf(ePrefix+
"Error: Input parameter 'newModTime' is INVALID!\nnewModTime='%v'",
newModTime)
}
err = os.Chtimes(pathFileName, newAccessTime, newModTime)
if err != nil {
return fmt.Errorf(ePrefix+
"ERROR returned by os.Chtimes(pathFileName,newAccessTime, newModTime)\n"+
"newAccessTime='%v'\nnewModTime='%v'\nError='%v'\n",
newAccessTime.Format("2006-01-02 15:04:05.000000000 -0700 MST"),
newModTime.Format("2006-01-02 15:04:05.000000000 -0700 MST"),
err.Error())
}
return nil
}
// ChangeWorkingDir - Changes the current working directory to the
// named directory passed in input parameter, 'dirPath'. If there
// is an error, it will be of type *PathError.
func (fh FileHelper) ChangeWorkingDir(dirPath string) error {
ePrefix := "FileHelper.ChangeWorkingDir() "
errCode := 0
errCode, _, dirPath = fh.isStringEmptyOrBlank(dirPath)
if errCode == -1 {
return errors.New(ePrefix + "Error: Input parameter 'dirPath' is an empty string!")
}
if errCode == -2 {
return errors.New(ePrefix + "Error: Input parameter 'dirPath' consists of blank spaces!")
}
err := os.Chdir(dirPath)
if err != nil {
return fmt.Errorf(ePrefix+"Error returned by os.Chdir(dirPath). "+
"dirPath='%v' Error='%v'", dirPath, err)
}
return nil
}
// CleanDirStr - Cleans and formats a directory string.
//
// Examples:
//
// dirName = '/someDir/xt_dirmgr_01_test.go' returns "./someDir"
//
// dirName = '../dir1/dir2/fileName.ext' returns "../dir1/dir2"
//
// dirName = 'fileName.ext' returns "" isEmpty = true
//
// dirName = 'xt_dirmgr_01_test.go' returns "" isEmpty = true
//
// dirName = '../dir1/dir2/' returns "../dir1/dir2"
//
// dirName = '../../../dir1/' returns '../../../dir1'
//
// dirName = '../dir1/dir2/filename.ext' returns "../dir1/dir2"
//
// dirName = '../dir1/dir2/.git' returns "../dir1/dir2"
//
// dirName = 'somevalidcharacters' returns "./somevalidchracters"
//
func (fh FileHelper) CleanDirStr(dirNameStr string) (returnedDirName string, isEmpty bool, err error) {
ePrefix := "FileHelper.CleanDirStr() "
returnedDirName = ""
isEmpty = true
err = nil
var pathDoesExist bool
var fInfo FileInfoPlus
var adjustedDirName string
adjustedDirName,
pathDoesExist,
fInfo,
err = fh.doesPathFileExist(dirNameStr,
PreProcPathCode.PathSeparator(), // Convert to os Path Separators
ePrefix,
"dirNameStr")
if err != nil {
returnedDirName = ""
isEmpty = true
return returnedDirName, isEmpty, err
}
lAdjustedDirName := len(adjustedDirName)
osPathSepStr := string(os.PathSeparator)
if strings.Contains(adjustedDirName, osPathSepStr+osPathSepStr) {
returnedDirName = ""
isEmpty = true
err = fmt.Errorf(ePrefix+
"Error: Invalid Directory string.\n"+
"Directory string contains invalid Path Separators.\n"+
"adjustedDirName='%v'\n",
adjustedDirName)
return returnedDirName, isEmpty, err
}
if strings.Contains(adjustedDirName, "...") {
returnedDirName = ""
isEmpty = true
err = fmt.Errorf(ePrefix+
"Error: Invalid Directory string.\n"+
"Directory string contains invalid dots.\n"+
"adjustedDirName='%v'\n",
adjustedDirName)
return returnedDirName, isEmpty, err
}
absPath, err := fh.MakeAbsolutePath(adjustedDirName)
if err != nil {
err = fmt.Errorf(ePrefix+"Error occurred while convert path "+
"to absolute path!\n"+
"dirPath='%v'\nError='%v'\n",
adjustedDirName, err.Error())
returnedDirName = ""
isEmpty = true
return returnedDirName, isEmpty, err
}
volName := fp.VolumeName(absPath)
volumeIdx := strings.Index(adjustedDirName, volName)
if strings.ToLower(volName) == strings.ToLower(adjustedDirName) {
returnedDirName = adjustedDirName
if len(returnedDirName) == 0 {
isEmpty = true
} else {
isEmpty = false
}
err = nil
return returnedDirName, isEmpty, err
}
isAbsPath := false
if strings.ToLower(absPath) == strings.ToLower(adjustedDirName) {
isAbsPath = true
}
dotPlusOsPathSepStr := "." + osPathSepStr
if pathDoesExist {
// The path exists
if fInfo.IsDir() {
// The path exists and it is a directory
returnedDirName = adjustedDirName
} else {
// The path exists but it is
// a File Name and NOT a directory name.
adjustedDirName = adjustedDirName[0 : lAdjustedDirName-len(fInfo.Name())]
lAdjustedDirName = len(adjustedDirName)
if lAdjustedDirName < 1 {
returnedDirName = ""
} else {
returnedDirName = adjustedDirName
}
}
lAdjustedDirName = len(returnedDirName)
if lAdjustedDirName == 0 {
isEmpty = true
err = nil
return returnedDirName, isEmpty, err
}
if returnedDirName[lAdjustedDirName-1] == os.PathSeparator {
// Last character in path is a Path Separator
if lAdjustedDirName >= 2 &&
returnedDirName[lAdjustedDirName-2] == '.' {
// The char immediately preceding the Path Separator
// in the last char position is a dot.
// Keep the path separator
returnedDirName = adjustedDirName
} else {
// The char immediately preceding the Path Separator in
// the last char position is NOT a dot. Delete the
// trailing path separator
returnedDirName = returnedDirName[0 : lAdjustedDirName-1]
}
}
lAdjustedDirName = len(returnedDirName)
if returnedDirName[0] != '.' &&
returnedDirName[0] != os.PathSeparator &&
volumeIdx == -1 &&
!isAbsPath {
// First letter in path is a character
// Add a leading dot
returnedDirName = dotPlusOsPathSepStr + returnedDirName
} else if returnedDirName[0] == os.PathSeparator &&
volumeIdx == -1 &&
!isAbsPath {
returnedDirName = "." + returnedDirName
}
if len(returnedDirName) == 0 {
isEmpty = true
} else {
isEmpty = false
}
err = nil
return returnedDirName, isEmpty, err
} // End of pathDoesExist == true
// The Path DOES NOT EXIST ON DISK
firstCharIdx, lastCharIdx, err2 :=
fh.GetFirstLastNonSeparatorCharIndexInPathStr(adjustedDirName)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned by fh."+
"GetFirstLastNonSeparatorCharIndexInPathStr(adjustedDirName).\n"+
"adjustedDirName='%v'\nError='%v'\n",
adjustedDirName, err2.Error())
returnedDirName = ""
isEmpty = true
return returnedDirName, isEmpty, err
}
interiorDotPathIdx := strings.LastIndex(adjustedDirName, "."+string(os.PathSeparator))
if interiorDotPathIdx > firstCharIdx {
err = fmt.Errorf(ePrefix+
"Error: INVALID PATH. Invalid interior relative path detected!\n"+
"adjustedDirName='%v'\n",
adjustedDirName)
returnedDirName = ""
isEmpty = true
return returnedDirName, isEmpty, err
}
slashIdxs, err2 := fh.GetPathSeparatorIndexesInPathStr(adjustedDirName)
if err2 != nil {
err = fmt.Errorf("Error returned by fh."+
"GetPathSeparatorIndexesInPathStr(adjustedDirName).\n"+
"adjusteDirName='%v'\nError='%v'\n",
adjustedDirName, err2.Error())
returnedDirName = ""
isEmpty = true
return returnedDirName, isEmpty, err
}
lSlashIdxs := len(slashIdxs)
dotIdxs, err2 := fh.GetDotSeparatorIndexesInPathStr(adjustedDirName)
if err2 != nil {
err = fmt.Errorf("Error returned by fh."+
"GetDotSeparatorIndexesInPathStr(adjustedDirName).\n"+
"adjustedDirName='%v'\nError='%v'\n",
adjustedDirName, err2.Error())
returnedDirName = ""
isEmpty = true
return returnedDirName, isEmpty, err
}
lDotIdxs := len(dotIdxs)
if lDotIdxs == 0 && lSlashIdxs == 0 && lastCharIdx == -1 {
// Option # 1
// There are no valid characters in the string
returnedDirName = ""
} else if lDotIdxs == 0 && lSlashIdxs == 0 && lastCharIdx > -1 {
// Option # 2
// String consists only of eligible alphanumeric characters
// "sometextstring"
returnedDirName = dotPlusOsPathSepStr + adjustedDirName
} else if lDotIdxs == 0 && lSlashIdxs > 0 && lastCharIdx == -1 {
// Option # 3
// There no dots no characters but string does contain
// slashes
if lSlashIdxs > 1 {
returnedDirName = ""
} else {
// lSlashIdxs must be '1'
returnedDirName = dotPlusOsPathSepStr
}
} else if lDotIdxs == 0 && lSlashIdxs > 0 && lastCharIdx > -1 {
// Option # 4
// strings contains slashes and characters but no dots.
returnedDirName = adjustedDirName
} else if lDotIdxs > 0 && lSlashIdxs == 0 && lastCharIdx == -1 {
// Option # 5
// dots only. Must be "." or ".."
// Add trailing path separator
returnedDirName = adjustedDirName + osPathSepStr
} else if lDotIdxs > 0 && lSlashIdxs == 0 && lastCharIdx > -1 {
// Option # 6
// Dots and characters only. No slashes.
// Maybe 'fileName.ext'
returnedDirName = ""
} else if lDotIdxs > 0 && lSlashIdxs > 0 && lastCharIdx == -1 {
// Option # 7
// Dots and slashes, but no characters.
returnedDirName = adjustedDirName
} else {
// Option # 8
// MUST BE lDotIdxs > 0 && lSlashIdxs > 0 && lastCharIdx > -1
// Has dots, slashes and characters
returnedDirName = adjustedDirName
// If there is a dot after the last path separator
// and there is a character following the dot.
// Therefore, this is a filename extension, NOT a directory
if dotIdxs[lDotIdxs-1] > slashIdxs[lSlashIdxs-1] &&
dotIdxs[lDotIdxs-1] < lastCharIdx {
returnedDirName = adjustedDirName[0:slashIdxs[lSlashIdxs-1]]
}
}
lAdjustedDirName = len(returnedDirName)
if lAdjustedDirName == 0 {
isEmpty = true
err = nil
return returnedDirName, isEmpty, err
}
if returnedDirName[lAdjustedDirName-1] == os.PathSeparator {
// Last character in path is a Path Separator
if lAdjustedDirName >= 2 &&
returnedDirName[lAdjustedDirName-2] == '.' {
// The char immediately preceding the Path Separator
// is a dot. Keep the path separator
// do nothing
lAdjustedDirName = len(returnedDirName)
} else {
returnedDirName = returnedDirName[0 : lAdjustedDirName-1]
}
}
lAdjustedDirName = len(returnedDirName)
if returnedDirName[0] != '.' &&
returnedDirName[0] != os.PathSeparator &&
volumeIdx == -1 &&
!isAbsPath {
// First letter in path is a character
// Add a leading dot
returnedDirName = dotPlusOsPathSepStr + returnedDirName
} else if returnedDirName[0] == os.PathSeparator &&
volumeIdx == -1 &&
!isAbsPath {
returnedDirName = "." + returnedDirName
}
if len(returnedDirName) == 0 {
isEmpty = true
} else {
isEmpty = false
}
err = nil
return returnedDirName, isEmpty, err
}
// CleanFileNameExtStr - Cleans up a file name extension string.
//
// Example:
// fileNameExt = '../dir1/dir2/fileName.ext'
// returns "fileName.ext" and isEmpty=false
//
// fileNameExt = 'fileName.ext"
// returns "fileName.ext" and isEmpty=false
//
// fileNameExt = "../filesfortest/newfilesfortest/" (actually exists on disk)
// returns "" and isEmpty=true and error = nil
//
// fileNameExt = '../dir1/dir2/'
// returns "" and isEmpty=true
//
// fileNameExt = '../filesfortest/newfilesfortest/newerFileForTest_01'
// returns "newerFileForTest_01" and isEmpty=false
//
// fileNameExt = '../filesfortest/newfilesfortest/.gitignore'
// returns ".gitignore" and isEmpty=false
//
func (fh FileHelper) CleanFileNameExtStr(
fileNameExtStr string) (returnedFileNameExt string, isEmpty bool, err error) {
ePrefix := "FileHelper.CleanFileNameExtStr() "
returnedFileNameExt = ""
isEmpty = true
err = nil
var pathDoesExist bool
var fInfo FileInfoPlus
var adjustedFileNameExt string
adjustedFileNameExt,
pathDoesExist,
fInfo,
err = fh.doesPathFileExist(fileNameExtStr,
PreProcPathCode.PathSeparator(), // Convert to os Path Separators
ePrefix,
"fileNameExtStr")
if err != nil {
returnedFileNameExt = ""
isEmpty = true
return returnedFileNameExt, isEmpty, err
}
osPathSepStr := string(os.PathSeparator)
if strings.Contains(adjustedFileNameExt, osPathSepStr+osPathSepStr) {
returnedFileNameExt = ""
isEmpty = true
err = fmt.Errorf(ePrefix+
"Error: Invalid Directory string.\n"+
"Directory string contains invalid Path Separators.\n"+
"adjustedFileNameExt='%v' ",
adjustedFileNameExt)
return returnedFileNameExt, isEmpty, err
}
if strings.Contains(adjustedFileNameExt, "...") {
err = fmt.Errorf(ePrefix+"Error: Invalid Directory string. Contains invalid dots.\n"+
"adjustedFileNameExt='%v'\n", adjustedFileNameExt)
return
}
// Find out if the file name extension path
// actually exists.
if pathDoesExist {
// The path exists
if fInfo.IsDir() {
// The path exists and it is a directory.
// There is no File Name present.
returnedFileNameExt = ""
isEmpty = true
err = nil
return
} else {
// The path exists and it is a valid
// file name.
returnedFileNameExt = fInfo.Name()
isEmpty = false
err = nil
return
}
} // End of if pathDoesExist
firstCharIdx, lastCharIdx, err :=
fh.GetFirstLastNonSeparatorCharIndexInPathStr(adjustedFileNameExt)
if firstCharIdx == -1 || lastCharIdx == -1 {
err = fmt.Errorf(ePrefix+"File Name Extension string contains no "+
"valid file name characters!\n"+
"adjustedFileNameExt='%v'\n",
adjustedFileNameExt)
return
}
// The file name extension path does not exist
interiorDotPathIdx := strings.LastIndex(adjustedFileNameExt, "."+string(os.PathSeparator))
if interiorDotPathIdx > firstCharIdx {
err = fmt.Errorf(ePrefix+"Error: INVALID PATH. "+
"Invalid interior relative path detected!\n"+
"adjustedFileNameExt='%v'\n", adjustedFileNameExt)
return
}
slashIdxs, err := fh.GetPathSeparatorIndexesInPathStr(adjustedFileNameExt)
if err != nil {
err = fmt.Errorf(ePrefix+"Error returned from fh.GetPathSeparatorIndexesInPathStr"+
"(adjustedFileNameExt).\n"+
"adustedFileNameExt='%v'\nError='%v'\n",
adjustedFileNameExt, err.Error())
return
}
lSlashIdxs := len(slashIdxs)
if lSlashIdxs == 0 {
returnedFileNameExt = adjustedFileNameExt
isEmpty = false
err = nil
return
}
dotIdxs, err2 := fh.GetDotSeparatorIndexesInPathStr(adjustedFileNameExt)
if err2 != nil {
err = fmt.Errorf("Error returned by fh."+
"GetDotSeparatorIndexesInPathStr(adjustedDirName).\n"+
"adjustedFileNameExt='%v'\nError='%v'\n",
adjustedFileNameExt, err2.Error())
returnedFileNameExt = ""
isEmpty = true
return returnedFileNameExt, isEmpty, err
}
lDotIdxs := len(dotIdxs)
// Option # 1
if lDotIdxs == 0 && lSlashIdxs == 0 && lastCharIdx == -1 {
// There are no valid characters in the string
returnedFileNameExt = ""
} else if lDotIdxs == 0 && lSlashIdxs == 0 && lastCharIdx > -1 {
// Option # 2
// String consists only of eligible alphanumeric characters
// "sometextstring"
returnedFileNameExt = adjustedFileNameExt
} else if lDotIdxs == 0 && lSlashIdxs > 0 && lastCharIdx == -1 {
// Option # 3
// There no dots no characters but string does contain
// slashes
returnedFileNameExt = ""
} else if lDotIdxs == 0 && lSlashIdxs > 0 && lastCharIdx > -1 {
// Option # 4
// strings contains slashes and characters but no dots.
if lastCharIdx < slashIdxs[lSlashIdxs-1] {
// Example: ../dir1/dir2/
returnedFileNameExt = ""
} else {
// Must be lastCharIdx > slashIdxs[lSlashIdxs-1]
// Example: ../dir1/dir2/filename
returnedFileNameExt = adjustedFileNameExt[slashIdxs[lSlashIdxs-1]+1:]
}
} else if lDotIdxs > 0 && lSlashIdxs == 0 && lastCharIdx == -1 {
// Option # 5
// dots only. Must be "." or ".."
// The is no file name
returnedFileNameExt = ""
} else if lDotIdxs > 0 && lSlashIdxs == 0 && lastCharIdx > -1 {
// Option # 6
// Dots and characters only. No slashes.
// Maybe 'fileName.ext'
returnedFileNameExt = adjustedFileNameExt
} else if lDotIdxs > 0 && lSlashIdxs > 0 && lastCharIdx == -1 {
// Option # 7
// Dots and slashes, but no characters.
returnedFileNameExt = ""
} else {
// Option # 8
// MUST BE lDotIdxs > 0 && lSlashIdxs > 0 && lastCharIdx > -1
// We have dots, slashes and characters
if lastCharIdx > slashIdxs[lSlashIdxs-1] {
// The last char comes after the last slash.
// Take everything after the last slash
returnedFileNameExt = adjustedFileNameExt[slashIdxs[lSlashIdxs-1]+1:]
} else {
// The last character comes before the last
// slash. There is no file name here.
returnedFileNameExt = ""
}
}
if len(returnedFileNameExt) == 0 {
isEmpty = true
} else {
isEmpty = false
}
err = nil
return
}
// CleanPathStr - Wrapper Function for filepath.Clean()
// See: https://golang.org/pkg/path/filepath/#Clean
// Clean returns the shortest path name equivalent to path
// by purely lexical processing. It applies the following rules
// iteratively until no further processing can be done:
//
// 1. Replace multiple Separator elements with a single one.
//
// 2. Eliminate each . path name element (the current directory).
//
// 3. Eliminate each inner .. path name element (the parent directory)
// along with the non-.. element that precedes it.
//
// 4. Eliminate .. elements that begin a rooted path:
// that is, replace "/.." by "/" at the beginning of a path,
// assuming Separator is '/'.'
//
// The returned path ends in a slash only if it represents a root
// directory, such as "/" on Unix or `C:\` on Windows.
// Finally, any occurrences of slash are replaced by Separator.
// If the result of this process is an empty string,
// Clean returns the string ".".
//
func (fh FileHelper) CleanPathStr(pathStr string) string {
return fp.Clean(pathStr)
}
// ConsolidateErrors - Receives an array of errors and converts them
// to a single error which is returned to the caller. Multiple errors
// are separated by a new line character.
//
// If the length of the error array is zero, this method returns nil.
//
func (fh FileHelper) ConsolidateErrors(errs []error) error {
lErrs := len(errs)
if lErrs == 0 {
return nil
}
errStr := ""
for i := 0; i < lErrs; i++ {
if errs[i] == nil {
continue
}
tempStr := fmt.Sprintf("%v", errs[i].Error())
tempStr = strings.TrimLeft(strings.TrimRight(tempStr, " "), " ")
strLen := len(tempStr)
for strings.HasSuffix(tempStr,"\n") &&
strLen > 1 {
tempStr = tempStr[0:strLen-1]
strLen--
}
if i == (lErrs - 1) {
errStr += fmt.Sprintf("%v", tempStr)
} else if i == 0 {
errStr = fmt.Sprintf("\n%v\n\n", tempStr)
} else {
errStr += fmt.Sprintf("%v\n\n", tempStr)
}
}
return fmt.Errorf("%v", errStr)
}
// ConvertDecimalToOctal - Utility routine to convert a decimal (base 10)
// numeric value to an octal (base 8) numeric value. Useful in
// evaluating 'os.FileMode' values and associated constants.
//
// Reference:
// https://www.cloudhadoop.com/2018/12/golang-example-convertcast-octal-to.html
//
// ------------------------------------------------------------------------
//
// Usage:
//
// initialDecimalValue := 511
// expectedOctalValue := 777
//
// actualOctalValue := ConvertDecimalToOctal(initialDecimalValue)
//
// 'actualOctalValue' is now equal to integer value '777'.
//
// ------------------------------------------------------------------------
//
// Warning:
//
// In the Go Programming Language, if you initialize an integer with a leading
// zero (e.g. x:= int(0777)), than number ('0777') is treated as an octal value
// and converted to a decimal value. Therefore, x:= int(0777) will mean that 'x'
// is set equal to 511. If you set x:= int(777), x will be set equal to '777'.
//
func (fh FileHelper) ConvertDecimalToOctal(number int) int {
octal := 0
counter := 1
remainder := 0
for number != 0 {
remainder = number % 8
number = number / 8
octal += remainder * counter
counter *= 10
}
return octal
}
// ConvertOctalToDecimal - Utility routine to convert an octal (base 8)
// numeric value to a decimal (base 10) numeric value. Useful in
// evaluating 'os.FileMode' values and associated constants.
//
// Reference:
// https://www.cloudhadoop.com/2018/12/golang-example-convertcast-octal-to.html
//
// ------------------------------------------------------------------------
//
// Usage:
//
// expectedDecimalValue := 511
// initialOctalValue := 777
// actualDecimalValue := FileHelper{}.ConvertOctalToDecimal(initialOctalValue)
//
// actualDecimalValue is now equal to integer value, '511'.
//
// ------------------------------------------------------------------------
//
// Warning:
//
// In the Go Programming Language, if you initialize an integer with a leading
// zero (e.g. x:= int(0777)), than number ('0777') is treated as an octal value
// and converted to a decimal value. Therefore, x:= int(0777) will mean that 'x'
// is set equal to 511. If you set x:= int(777), x will be set equal to '777'.
//
func (fh FileHelper) ConvertOctalToDecimal(number int) int {
decimal := 0
counter := 0.0
remainder := 0
for number != 0 {
remainder = number % 10
decimal += remainder * int(math.Pow(8.0, counter))
number = number / 10
counter++
}
return decimal
}
// CopyFileByLinkByIo - Copies a file from source to destination
// using one of two techniques.
//
// First, this method will attempt to copy the designated
// file by means of creating a new destination file and using
// "io.Copy(out, in)" to copy the contents. This is accomplished
// by calling 'FileHelper.CopyFileByIo()'. If the call to
// 'FileHelper.CopyFileByIo()' fails, this method will attempt
// a second copy method.
//
// The second attempt to to copy the designated file will be
// accomplished by creating a 'hard link' to the source file.
// The second, 'hard link', attempt will call method,
// 'FileHelper.CopyFileByLink()'.
//
// If that 'hard link' operation fails, this method will call
// 'FileHelper.CopyFileByIo()'.
//
// If both attempted file copy operations fail, an error will be
// returned.
//
// See: https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
//
func (fh FileHelper) CopyFileByIoByLink(src, dst string) (err error) {
ePrefix := "FileHelper.CopyFileByIoByLink() "
err = fh.CopyFileByIo(src, dst)
if err == nil {
return err
}
// fh.CopyFileByIo() failed. Try
// fh.CopyFileByLink()
errX := fh.CopyFileByLink(src, dst)
if errX != nil {
err = fmt.Errorf(ePrefix+
"Error: After Copy By IO failed, an error was returned "+
"by fh.CopyFileByLink(src, dst)\n"+
"src='%v'\ndst='%v'\nError='%v'\n", src, dst, errX)
return err
}
err = nil
return err
}
// CopyFileByLinkByIo - Copies a file from source to destination
// using one of two techniques.
//
// First, this method will attempt to copy the designated
// file by means of creating a 'hard link' to the source file.
// The 'hard link' attempt will call 'FileHelper.CopyFileByLink()'.
//
// If that 'hard link' operation fails, this method will call
// 'FileHelper.CopyFileByIo()'.
//
// CopyFileByIo() will create a new destination file and attempt
// to write the contents of the source file to the new destination
// file using "io.Copy(out, in)".
//
// If both attempted file copy operations fail, an error will be
// returned.
//
// See: https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
//
func (fh FileHelper) CopyFileByLinkByIo(src, dst string) (err error) {
ePrefix := "FileHelper.CopyFileByLinkByIo() "
err = fh.CopyFileByLink(src, dst)
if err == nil {
return err
}
// Copy by Link Failed. Try CopyFileByIo()
errX := fh.CopyFileByIo(src, dst)
if errX != nil {
err = fmt.Errorf(ePrefix+
"Error: After Copy By Link failed, an error was returned by fh.CopyFileByIo(src, dst).\n"+
"src='%v'\ndst='%v'\nError='%v'\n",
src, dst, errX)
return err
}
err = nil
return err
}
// CopyFileByLink - Copies a file from source to destination
// by means of creating a 'hard link' to the source file,
// "os.Link(src, dst)".
//
// Note: This method of copying files does not create a new
// destination file and write the contents of the source file
// to destination file. (See CopyFileByIo Below). Instead, this
// method performs the copy operation by creating a hard symbolic
// link to the source file.
//
// By creating a 'linked' file, changing the contents of one file
// will be reflected in the second. The two linked files are
// 'mirrors' of each other.
//
// Consider using CopyFileByIo() if the 'mirror' feature causes problems.
//
// "os.Link(src, dst)" is the only method employed to copy a
// designated file. If "os.Link(src, dst)" fails, an err is returned.
//
// See: https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
//
// REQUIREMENT: The destination Path must previously exist. The destination file
// need NOT exist as it will be created. If the destination file currently
// exists, it will first be deleted and a new linked file will be crated.
//
func (fh FileHelper) CopyFileByLink(src, dst string) (err error) {
ePrefix := "FileHelper.CopyFileByLink() "
err = nil
var err2 error
var srcFileDoesExist, dstFileDoesExist bool
var srcFInfo, dstFInfo FileInfoPlus
src,
srcFileDoesExist,
srcFInfo,
err = fh.doesPathFileExist(src,
PreProcPathCode.AbsolutePath(), // Covert to Absolute Path
ePrefix,
"src")
if err != nil {
return err
}
dst,
dstFileDoesExist,
dstFInfo,
err = fh.doesPathFileExist(dst,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"dst")
if err != nil {
return err
}
areSameFile, err2 := fh.AreSameFile(src, dst)
if err2 != nil {
err = fmt.Errorf(ePrefix+"Error occurred during path file name comparison.\n"+
"Source File:'%v'\n"+
"Destination File:'%v'\n"+
"Error='%v'\n",
src, dst, err2.Error())
return err
}
if areSameFile {
err = fmt.Errorf(ePrefix+"Error: The source and destination file"+
" are the same - equivalent.\n"+
"Source File:'%v'\nDestination File:'%v'\n",
src, dst)
return err
}
if !srcFileDoesExist {
err = fmt.Errorf(ePrefix+
"Error: Input parameter 'src' file DOES NOT EXIST!\n"+
"src='%v'\n", src)
return err
}
if srcFInfo.IsDir() {
err = fmt.Errorf(ePrefix+"ERROR: Source File (src) is a 'Directory' NOT A FILE!\n"+
"Source File (src)='%v'\n", src)
return err
}
if !srcFInfo.Mode().IsRegular() {
// cannot copy non-regular files (e.g., directories,
// symlinks, devices, etc.)
err = fmt.Errorf(ePrefix+
"Error: Non-regular source file.\n"+
"Source File Name='%v'\n"+
"Source File Mode='%v'\n",
srcFInfo.Name(), srcFInfo.Mode().String())
return err
}
// If the destination file does NOT exist - this is not a problem
// because the destination file will be created later.
if dstFileDoesExist {
// The destination file exists. This IS a problem. Link will
// fail when attempting to create a link to an existing file.
if dstFInfo.IsDir() {
err = fmt.Errorf(ePrefix+
"Error: The destination file ('dst') is NOT A FILE.\n"+
"It is a DIRECTORY!\n"+
"Destination File ('dst') = '%v'\n",
dst)
return err
}
if !dstFInfo.Mode().IsRegular() {
err = fmt.Errorf(ePrefix+
"Error: The destination file ('dst') is NOT A REGULAR FILE.\n"+
"Destination File ('dst') = '%v'\n",
dst)
return err
}
err2 = os.Remove(dst)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error: The target destination file exists and could NOT be deleted! \n"+
"destination file='%v'\nError='%v'\n", dst, err2.Error())
return err
}
dst,
dstFileDoesExist,
_,
err = fh.doesPathFileExist(dst,
PreProcPathCode.None(), // Apply no pre-processing conversion to 'dst'
ePrefix,
"dst")
if err != nil {
return err
}
if dstFileDoesExist {
err = fmt.Errorf(ePrefix+"Error: Deletion of preexisting "+
"destination file failed!\n"+
"The copy link operation cannot proceed!\n"+
"destination file='%v' ", dst)
return err
}
}
err2 = os.Link(src, dst)
if err2 != nil {
err = fmt.Errorf(ePrefix+"- os.Link(src, dst) FAILED!\n"+
"src='%v'\ndst='%v'\nError='%v'\n",
src, dst, err2.Error())
return err
}
dst,
dstFileDoesExist,
_,
err2 = fh.doesPathFileExist(dst,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"dst")
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error: After Copy By Link Operation, a non-path error was returned on 'dst'.\n"+
"Error='%v'", err2.Error())
return err
}
if !dstFileDoesExist {
err = fmt.Errorf(ePrefix+
"Error: After Copy By Link Operation, the destination file DOES NOT EXIST!\n"+
"Destination File= dst = %v", dst)
return err
}
err = nil
return err
}
// CopyFileByIo - Copies file from source path and file name to destination
// path and file name.
//
// Reference:
// https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
//
// Note: Unlike the method CopyFileByLink above, this method does
// NOT rely on the creation of symbolic links. Instead, a new destination
// file is created and the contents of the source file are written to
// the new destination file using "io.Copy()".
//
// "io.Copy()" is the only method used to copy the designated source
// file. If this method fails, an error is returned.
//
// If source file is equivalent to the destination file, no action will
// be taken and no error will be returned.
//
// If the destination file does not exist, this method will create.
// However, it will NOT create the destination directory. If the
// destination directory does NOT exist, this method will abort
// the copy operation and return an error.
//
func (fh FileHelper) CopyFileByIo(src, dst string) (err error) {
ePrefix := "FileHelper.CopyFileByIo() "
err = nil
var err2, err3 error
var srcFileDoesExist, dstFileDoesExist bool
var srcFInfo, dstFileInfo FileInfoPlus
src,
srcFileDoesExist,
srcFInfo,
err = fh.doesPathFileExist(src,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"src")
if err != nil {
return err
}
if !srcFileDoesExist {
err = fmt.Errorf(ePrefix+"Error: Source File DOES NOT EXIST!\n"+
"src='%v'\n", src)
return err
}
dst,
dstFileDoesExist,
dstFileInfo,
err = fh.doesPathFileExist(dst,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"dst")
if err != nil {
return err
}
areSameFile, err2 := fh.AreSameFile(src, dst)
if err2 != nil {
err = fmt.Errorf(ePrefix+"Error occurred during path file name comparison.\n"+
"Source File:'%v'\nDestination File:'%v'\nError='%v'\n",
src, dst, err2.Error())
return err
}
if areSameFile {
err = fmt.Errorf(ePrefix+"Error: The source and destination file "+
"are the same - equivalent.\n"+
"Source File:'%v'\nDestination File:'%v'\n",
src, dst)
return err
}
if srcFInfo.IsDir() {
err = fmt.Errorf(ePrefix+"Error: Source File is 'Directory' and NOT a file!\n"+
"Source File='%v'\n", src)
return err
}
if !srcFInfo.Mode().IsRegular() {
// cannot copy non-regular files (e.g., directories,
// symlinks, devices, etc.)
err = fmt.Errorf(ePrefix+"Error non-regular source file ='%v'\n"+
"source file Mode='%v'\n",
srcFInfo.Name(), srcFInfo.Mode().String())
return err
}
if dstFileDoesExist && dstFileInfo.Mode().IsDir() {
err = fmt.Errorf(ePrefix+
"Error: 'dst' is a Directory and NOT a File!\n"+
"dst='%v'", dst)
return err
}
if dstFileDoesExist && !dstFileInfo.Mode().IsRegular() {
err = fmt.Errorf(ePrefix+
"Error: 'dst' is NOT a 'Regular' File!\n"+
"dst='%v'\n", dst)
return err
}
// If the destination file does NOT exist, this is not a problem
// since it will be created later. If the destination 'Path' does
// not exist, an error return will be triggered.
// Create a new destination file and copy source
// file contents to the destination file.
// First, open the source file
inSrcPtr, err2 := os.Open(src)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned from os.Open(src) src='%v' Error='%v'",
src, err2.Error())
return err
}
// Next, 'Create' the destination file
// If the destination file previously exists,
// it will be truncated.
outDestPtr, err2 := os.Create(dst)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned from os.Create(destinationFile)\n"+
"destinationFile='%v'\nError='%v'\n",
dst, err2.Error())
_ = inSrcPtr.Close()
return err
}
bytesCopied, err2 := io.Copy(outDestPtr, inSrcPtr)
if err2 != nil {
_ = inSrcPtr.Close()
_ = outDestPtr.Close()
err = fmt.Errorf(ePrefix+
"Error returned from io.Copy(destination, source) \n"+
"destination='%v'\n"+
"source='%v'\nError='%v'\n",
dst, src, err2.Error())
return err
}
errs := make([]error, 0)
// flush file buffers inSrcPtr memory
err2 = outDestPtr.Sync()
if err2 != nil {
err3 = fmt.Errorf(ePrefix+
"Error returned from outDestPtr.Sync()\n"+
"outDestPtr=destination='%v'\nError='%v'\n",
dst, err2.Error())
errs = append(errs, err3)
}
err2 = inSrcPtr.Close()
if err2 != nil {
err3 = fmt.Errorf(ePrefix+
"Error returned from inSrcPtr.Close()\n"+
"inSrcPtr=source='%v'\nError='%v'\n",
src, err2.Error())
errs = append(errs, err3)
}
inSrcPtr = nil
err2 = outDestPtr.Close()
if err2 != nil {
err3 = fmt.Errorf(ePrefix+
"Error returned from outDestPtr.Close()\noutDestPtr=destination='%v'\nError='%v'\n",
dst, err2.Error())
errs = append(errs, err3)
}
outDestPtr = nil
if len(errs) > 0 {
return fh.ConsolidateErrors(errs)
}
_,
dstFileDoesExist,
dstFileInfo,
err2 = fh.doesPathFileExist(dst,
PreProcPathCode.None(), // Do NOT alter path
ePrefix,
"dst")
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error: After Copy IO operation, dst "+
"generated non-path error!\n"+
"dst='%v'\nError='%v'\n",
dst, err2.Error())
return err
}
if !dstFileDoesExist {
err = fmt.Errorf(ePrefix+
"ERROR: After Copy IO operation, the destination file DOES NOT EXIST!\n"+
"Destination File = 'dst' = '%v'\n", dst)
return err
}
srcFileSize := srcFInfo.Size()
if bytesCopied != srcFileSize {
err = fmt.Errorf(ePrefix+
"Error: Bytes Copied does NOT equal bytes "+
"in source file!\n"+
"Source File Bytes='%v' Bytes Coped='%v'\n"+
"Source File=src='%v'\nDestination File=dst='%v'\n",
srcFileSize, bytesCopied,
src, dst)
return err
}
err = nil
if dstFileInfo.Size() != srcFileSize {
err = fmt.Errorf(ePrefix+
"\nError: Bytes is source file do NOT equal bytes "+
"in destination file!\n"+
"Source File Bytes='%v' Destination File Bytes='%v'\n"+
"Source File=src='%v'\nDestination File=dst='%v'\n",
srcFileSize, dstFileInfo.Size(),
src, dst)
return err
}
return err
}
// CreateFile - Wrapper function for os.Create. If the path component of input
// parameter 'pathFileName' does not exist, a type *PathError will be returned.
//
// This method will 'create' the file designated by input parameter 'pathFileName'.
// 'pathFileName' should consist of a valid path, file name. The file name may consist
// of a file name and file extension or simply a file name.
//
// If successful, this method will return a valid pointer to a type 'os.File' and
// an error value of 'nil'.
//
func (fh FileHelper) CreateFile(pathFileName string) (*os.File, error) {
ePrefix := "FileHelper.CreateFile() "
errCode := 0
errCode, _, pathFileName = fh.isStringEmptyOrBlank(pathFileName)
if errCode == -1 {
return nil, errors.New(ePrefix + "Error: Input parameter 'pathFileName' is an empty string!")
}
if errCode == -2 {
return nil, errors.New(ePrefix + "Error: Input parameter 'pathFileName' consists of blank spaces!")
}
var err error
pathFileName, err = fh.MakeAbsolutePath(pathFileName)
if err != nil {
return nil,
fmt.Errorf(ePrefix+
"Error returned by fh.MakeAbsolutePath(pathFileName)\n"+
"pathFileName='%v'\nError='%v'\n",
pathFileName, err.Error())
}
filePtr, err := os.Create(pathFileName)
if err != nil {
return nil, fmt.Errorf(ePrefix+
"Error returned from os.Create(pathFileName)\n"+
"pathFileName='%v'\nError='%v'\n",
pathFileName, err.Error())
}
return filePtr, nil
}
// DeleteDirFile - Wrapper function for Remove.
// Remove removes the named file or directory.
// If there is an error, it will be a Non-Path Error.
//
func (fh FileHelper) DeleteDirFile(pathFile string) error {
ePrefix := "FileHelper.DeleteDirFile() "
var fileDoesExist bool
var err error
pathFile, fileDoesExist, _, err = fh.doesPathFileExist(
pathFile,
PreProcPathCode.AbsolutePath(), // Convert to Absolute File Path
ePrefix,
"pathFile")
if err != nil {
return err
}
if !fileDoesExist {
// Doesn't exist. Nothing to do.
return nil
}
err = os.Remove(pathFile)
if err != nil {
return fmt.Errorf(ePrefix+
"Error returned from os.Remove(pathFile).\n"+
"pathFile='%v'\nError='%v'",
pathFile, err.Error())
}
_, fileDoesExist, _, err = fh.doesPathFileExist(
pathFile,
PreProcPathCode.None(), // Apply No Pre-Processing. Take no action
ePrefix,
"pathFile")
if err != nil {
return fmt.Errorf("After attempted deletion, file error occurred!\n"+
"pathFile='%v'\n"+
"%v", pathFile, err.Error())
}
if fileDoesExist {
// File STILL Exists! ERROR!
return fmt.Errorf("ERROR: After attempted deletion, file still exists!\n"+
"pathFile='%v'\n", pathFile)
}
return nil
}
// DeleteDirPathAll - Wrapper function for RemoveAll. This method removes path
// and any children it contains. It removes everything it can but returns the
// first error it encounters. If the path does not exist, this method takes no
// action and returns nil (no error).
//
// Consider the following Example:
// 1. D:\T08\x294_1\x394_1\x494_1 is a directory path that currently exists and
// contains files.
// 2. Call DeleteDirPathAll("D:\\T08\\x294_1")
// 3. Upon return from method DeleteDirPathAll():
// a. Deletion Results:
// Directory D:\T08\x294_1\x394_1\x494_1 and any files in the 'x494_1' directory are deleted
// Directory D:\T08\x294_1\x394_1\ and any files in the 'x394_1' directory are deleted
// Directory D:\T08\x294_1\ and any files in the 'x294_1' directory are deleted
//
// b. The Parent Path 'D:\T08' and any files in that parent path 'D:\T08'
// directory are unaffected and continue to exist.
//
func (fh FileHelper) DeleteDirPathAll(pathDir string) error {
ePrefix := "FileHelper.DeleteDirPathAll() "
var err, err2 error
var pathFileDoesExist bool
pathDir,
pathFileDoesExist,
_,
err = fh.doesPathFileExist(pathDir,
PreProcPathCode.AbsolutePath(), // Convert To Absolute Path
ePrefix,
"pathDir")
if err != nil {
return err
}
if !pathFileDoesExist {
// Doesn't exist. Nothing to do.
return nil
}
for i := 0; i < 3; i++ {
err = nil
err2 = os.RemoveAll(pathDir)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned by os.RemoveAll(pathDir).\n"+
"pathDir='%v'\nError='%v'",
pathDir, err2.Error())
}
if err == nil {
break
}
time.Sleep(50 * time.Millisecond)
}
if err != nil {
return err
}
pathDir,
pathFileDoesExist,
_,
err = fh.doesPathFileExist(pathDir,
PreProcPathCode.None(), // Apply No Pre-Processing. Take No Action.
ePrefix,
"pathDir")
if err != nil {
return err
}
if pathFileDoesExist {
// Path still exists. Something is wrong.
return fmt.Errorf("Delete Failed! 'pathDir' still exists!\n"+
"pathDir='%v'\n", pathDir)
}
return nil
}
// DoesFileExist - Returns a boolean value designating whether the passed
// file name exists.
//
// This method does not differentiate between Path Errors and Non-Path
// Errors returned by os.Stat(). The method only returns a boolean
// value.
//
// If a Non-Path Error is returned by os.Stat(), this method will
// classify the file as "Does NOT Exist" and return a value of
// false.
//
// For a more granular test of whether a file exists, see method
// FileHelper.DoesThisFileExist().
func (fh FileHelper) DoesFileExist(pathFileName string) bool {
_, pathFileDoesExist, _, nonPathError :=
fh.doesPathFileExist(
pathFileName,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
"",
"pathFileName")
if !pathFileDoesExist || nonPathError != nil {
return false
}
return true
}
// DeleteFilesWalkDirectory - This method 'walks' the directory tree searching
// for files which match the file selection criteria specified by input parameter
// 'fileSelectCriteria'. When a file matching said 'fileSelectCriteria' is found,
// that file is deleted.
//
// IMPORTANT: This method deletes files!
//
// This method returns file information on files deleted.
//
// If a file matches the File Selection Criteria ('fileSelectCriteria') it is deleted
// and its file information is recorded in the returned DirectoryDeleteFileInfo instance,
// DirectoryDeleteFileInfo.DeletedFiles.
//
// By the way, if ALL the file selection criterion are set to zero values or 'Inactive',
// then ALL FILES in the directory are selected, deleted and returned in the field,
// 'DirectoryDeleteFileInfo.DeletedFiles'.
//
// ------------------------------------------------------------------------
//
// Input Parameter:
//
// startPath string - A string consisting of the starting path or
// or directory from which the file search
// operation will commence.
//
// fileSelectCriteria FileSelectionCriteria -
// This input parameter should be configured with the desired file
// selection criteria. Files matching this criteria will be returned as
// 'Found Files'. If file 'fileSelectCriteria' is uninitialized (FileSelectionCriteria{}).
// all directories the 'startPath' will be searched and all files within those
// directories will be deleted.
//
//
// _______________________________________________________________________________________________
// type FileSelectionCriteria struct {
// FileNamePatterns []string // An array of strings containing File Name Patterns
// FilesOlderThan time.Time // Match files with older modification date times
// FilesNewerThan time.Time // Match files with newer modification date times
// SelectByFileMode FilePermissionConfig // Match file mode (os.FileMode).
// SelectCriterionMode FileSelectCriterionMode // Specifies 'AND' or 'OR' selection mode
// }
//
// The FileSelectionCriteria type allows for configuration of single or multiple file
// selection criterion. The 'SelectCriterionMode' can be used to specify whether the
// file must match all, or any one, of the active file selection criterion.
//
// Elements of the FileSelectionCriteria Type are described below:
//
// FileNamePatterns []string - An array of strings which may define one or more
// search patterns. If a file name matches any one of the
// search pattern strings, it is deemed to be a 'match'
// for the search pattern criterion.
//
// Example Patterns:
// FileNamePatterns = []string{"*.log"}
// FileNamePatterns = []string{"current*.txt"}
// FileNamePatterns = []string{"*.txt", "*.log"}
//
// If this string array has zero length or if
// all the strings are empty strings, then this
// file search criterion is considered 'Inactive'
// or 'Not Set'.
//
//
// FilesOlderThan time.Time - This date time type is compared to file
// modification date times in order to determine
// whether the file is older than the 'FilesOlderThan'
// file selection criterion. If the file is older than
// the 'FilesOlderThan' date time, that file is considered
// a 'match' for this file selection criterion.
//
// If the value of 'FilesOlderThan' is set to time zero,
// the default value for type time.Time{}, then this
// file selection criterion is considered to be 'Inactive'
// or 'Not Set'.
//
// FilesNewerThan time.Time - This date time type is compared to the file
// modification date time in order to determine
// whether the file is newer than the 'FilesNewerThan'
// file selection criterion. If the file modification date time
// is newer than the 'FilesNewerThan' date time, that file is
// considered a 'match' for this file selection criterion.
//
// If the value of 'FilesNewerThan' is set to time zero,
// the default value for type time.Time{}, then this
// file selection criterion is considered to be 'Inactive'
// or 'Not Set'.
//
// SelectByFileMode FilePermissionConfig -
// Type FilePermissionConfig encapsulates an os.FileMode. The file
// selection criterion allows for the selection of files by File Mode.
// File modes are compared to the value of 'SelectByFileMode'. If the
// File Mode for a given file is equal to the value of 'SelectByFileMode',
// that file is considered to be a 'match' for this file selection
// criterion. Examples for setting SelectByFileMode are shown as follows:
//
// fsc := FileSelectionCriteria{}
// err = fsc.SelectByFileMode.SetByFileMode(os.FileMode(0666))
// err = fsc.SelectByFileMode.SetFileModeByTextCode("-r--r--r--")
//
// SelectCriterionMode FileSelectCriterionMode -
// This parameter selects the manner in which the file selection
// criteria above are applied in determining a 'match' for file
// selection purposes. 'SelectCriterionMode' may be set to one of
// two constant values:
//
// _____________________________________________________________________
//
// FileSelectCriterionMode(0).ANDSelect() -
// File selected if all active selection criteria
// are satisfied.
//
// If this constant value is specified for the file selection mode,
// then a given file will not be judged as 'selected' unless all of
// the active selection criterion are satisfied. In other words, if
// three active search criterion are provided for 'FileNamePatterns',
// 'FilesOlderThan' and 'FilesNewerThan', then a file will NOT be
// selected unless it has satisfied all three criterion in this example.
//
// FileSelectCriterionMode(0).ORSelect() -
// File selected if any active selection criterion is satisfied.
//
// If this constant value is specified for the file selection mode,
// then a given file will be selected if any one of the active file
// selection criterion is satisfied. In other words, if three active
// search criterion are provided for 'FileNamePatterns', 'FilesOlderThan'
// and 'FilesNewerThan', then a file will be selected if it satisfies any
// one of the three criterion in this example.
//
// _____________________________________________________________________
//
//
// ------------------------------------------------------------------------
//
// IMPORTANT:
//
// If all of the file selection criterion in the FileSelectionCriteria object are
// 'Inactive' or 'Not Set' (set to their zero or default values), then all of
// the files processed in the directory tree will be deleted and returned in the
// the file manager collection, DirectoryDeleteFileInfo.DeletedFiles.
//
// Example:
// FileNamePatterns = ZERO Length Array
// filesOlderThan = time.Time{}
// filesNewerThan = time.Time{}
//
// In this example, all of the selection criterion are
// 'Inactive' and therefore all of the files encountered
// in the target directory will be selected and returned
// as 'Found Files'.
//
// This same effect can be achieved by simply creating an
// empty file selection instance:
//
// FileSelectionCriteria{}
//
//
// ------------------------------------------------------------------------
//
// Return Values:
//
// DirectoryDeleteFileInfo -
// If successful, files matching the file selection criteria input
// parameter shown above will be deleted and returned in a
// 'DirectoryDeleteFileInfo' object. The file manager
// 'DirectoryDeleteFileInfo.DeletedFiles' contains information on all files
// deleted during this operation.
//
// Note: It is a good idea to check the returned field 'DirectoryTreeInfo.ErrReturns'
// to determine if any internal system errors were encountered while processing
// the directory tree.
//
// __________________________________________________________________________________________________
//
// type DirectoryDeleteFileInfo struct {
//
// StartPath string // The starting path or directory for the file search
//
// Directories DirMgrCollection // Directory Manager instances found during the
// // directory tree search.
// DeletedFiles FileMgrCollection // Contains File Managers for Deleted Files matching
// // file selection criteria.
// ErrReturns []error // Internal System errors encountered during the search
// // and file deletion operations.
// FileSelectCriteria FileSelectionCriteria // The File Selection Criteria submitted as an
// // input parameter to this method.
// }
//
// __________________________________________________________________________________________________
//
// error - If a program execution error is encountered during processing, it will
// be returned as an 'error' type. Also, see the comment on 'DirectoryDeleteFileInfo.ErrReturns',
// above.
//
func (fh FileHelper) DeleteFilesWalkDirectory(
startPath string, fileSelectCriteria FileSelectionCriteria) (DirectoryDeleteFileInfo, error) {
ePrefix := "FileHelper.DeleteFilesWalkDirectory() "
deleteFilesInfo := DirectoryDeleteFileInfo{}
errCode := 0
errCode, _, startPath = fh.isStringEmptyOrBlank(startPath)
if errCode == -1 {
return deleteFilesInfo,
errors.New(ePrefix + "Error: Input parameter 'startPath' is an empty string!")
}
if errCode == -2 {
return deleteFilesInfo,
errors.New(ePrefix + "Error: Input parameter 'startPath' consists of blank spaces!")
}
startPath = fh.AdjustPathSlash(startPath)
strLen := len(startPath)
if startPath[strLen-1] == os.PathSeparator {
startPath = startPath[0:strLen-1]
}
var err error
startPath, err = fh.MakeAbsolutePath(startPath)
if err != nil {
return deleteFilesInfo,
fmt.Errorf(ePrefix+"Error returned by fh.MakeAbsolutePath(startPath). "+
"startPath='%v' Error='%v' ", startPath, err.Error())
}
if !fh.DoesFileExist(startPath) {
return deleteFilesInfo, fmt.Errorf(ePrefix+
"Error - startPath DOES NOT EXIST! startPath='%v'", startPath)
}
deleteFilesInfo.StartPath = startPath
deleteFilesInfo.DeleteFileSelectCriteria = fileSelectCriteria
err = fp.Walk(deleteFilesInfo.StartPath, fh.makeFileHelperWalkDirDeleteFilesFunc(&deleteFilesInfo))
if err != nil {
return deleteFilesInfo,
fmt.Errorf(ePrefix+
"Error returned from fp.Walk(deleteFilesInfo.StartPath, fh.makeFileHelperWalkDirFindFilesFunc"+
"(&deleteFilesInfo)). startPath='%v' Error='%v'", startPath, err.Error())
}
return deleteFilesInfo, nil
}
// DoesFileInfoExist - returns a boolean value indicating
// whether the path and file name passed to the function
// actually exists.
//
// If the file actually exists, the function will return
// the associated FileInfo structure.
//
// If 'pathFileName' does NOT exist, 'doesFInfoExist' will
// be set to'false', 'fInfo' will be set to 'nil' and the
// returned error value will be 'nil'.
//
func (fh FileHelper) DoesFileInfoExist(
pathFileName string) (doesFInfoExist bool, fInfo os.FileInfo, err error) {
ePrefix := "FileHelper.DoesFileInfoExist() "
doesFInfoExist = false
fInfo = nil
fInfoPlus := FileInfoPlus{}
pathFileName,
doesFInfoExist,
fInfoPlus,
err = fh.doesPathFileExist(
pathFileName,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"pathFileName")
if err != nil {
doesFInfoExist = false
return doesFInfoExist, fInfo, err
}
if !doesFInfoExist {
err = nil
fInfo = nil
return doesFInfoExist, fInfo, err
}
fInfo = fInfoPlus.GetOriginalFileInfo()
return doesFInfoExist, fInfo, err
}
// DoesStringEndWithPathSeparator - Returns 'true' if the string ends with a
// valid Path Separator. ('/' or '\' depending on the operating system)
//
func (fh FileHelper) DoesStringEndWithPathSeparator(pathStr string) bool {
errCode := 0
lenStr := 0
errCode, lenStr, pathStr = fh.isStringEmptyOrBlank(pathStr)
if errCode < 0 {
return false
}
if pathStr[lenStr-1] == '\\' || pathStr[lenStr-1] == '/' || pathStr[lenStr-1] == os.PathSeparator {
return true
}
return false
}
// DoesThisFileExist - Returns a boolean value signaling whether the path and file name
// represented by input parameter, 'pathFileName', does in fact exist. Unlike the similar
// method FileHelper.DoesFileExist(), this method returns an error in the case of
// Non-Path errors associated with 'pathFileName'.
//
// Non-Path errors may arise for a variety of reasons, but the most common is associated
// with 'access denied' situations.
//
func (fh FileHelper) DoesThisFileExist(pathFileName string) (pathFileNameDoesExist bool,
nonPathError error) {
ePrefix := "FileHelper.DoesThisFileExist() "
pathFileNameDoesExist = false
nonPathError = nil
_, pathFileNameDoesExist, _, nonPathError =
fh.doesPathFileExist(
pathFileName,
PreProcPathCode.AbsolutePath(), // Skip Absolute Path Conversion
ePrefix,
"pathFileName")
if nonPathError != nil {
pathFileNameDoesExist = false
return pathFileNameDoesExist, nonPathError
}
return pathFileNameDoesExist, nonPathError
}
// FilterFileName - Utility method designed to determine whether a file described by a filePath string
// and an os.FileInfo object meets any one of three criteria: A string pattern match, a modification time
// which is older than the 'findFileOlderThan' parameter or a modification time which is newer than the
// 'findFileNewerThan' parameter.
//
// If the three search criteria are all set the their 'zero' or default values, the no selection filter is
// applied and all files are deemed to be a match for the selection criteria ('isMatchedFile=true').
//
// Three selection criterion are applied to the file name (info.Name()).
//
// If a given selection criterion is set to a zero value, then that criterion is defined as 'not set'
// and therefore not used in determining determining whether a file is a 'match'.
//
// If a given criterion is set to a non-zero value, then that criterion is defined as 'set' and the file
// information must comply with that criterion in order to be judged as a match ('isMatchedFile=true').
//
// If none of the three criterion are 'set', then all files are judged as matched ('isMatchedFile=true').
//
// If one of the three criterion is 'set', then a file must comply with that one criterion in order to
// be judged as matched ('isMatchedFile=true').
//
// If two criteria are 'set', then the file must comply with both of those criterion in order to be judged
// as matched ('isMatchedFile=true').
//
// If three criteria are 'set', then the file must comply with all three criterion in order to be judged
// as matched ('isMatchedFile=true').
//
func (fh *FileHelper) FilterFileName(
info os.FileInfo,
fileSelectionCriteria FileSelectionCriteria) (isMatchedFile bool, err error) {
ePrefix := "FileHelper.FilterFileName() "
isMatchedFile = false
err = nil
if info == nil {
err = errors.New(ePrefix + "Input parameter 'info' is 'nil' and INVALID!")
return isMatchedFile, err
}
isPatternSet, isPatternMatch, err2 := fh.SearchFilePatternMatch(info, fileSelectionCriteria)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned from fh.SearchFilePatternMatch(info, fileSelectionCriteria).\n"+
"info.Name()='%v'\nError='%v'\n", info.Name(), err2.Error())
isMatchedFile = false
return
}
isFileOlderThanSet, isFileOlderThanMatch, err2 := fh.SearchFileOlderThan(info, fileSelectionCriteria)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned from dMgr.searchFileOlderThan(info, fileSelectionCriteria)\n"+
"fileSelectionCriteria.FilesOlderThan='%v' info.Name()='%v'\nError='%v'\n",
fileSelectionCriteria.FilesOlderThan, info.Name(), err2.Error())
isMatchedFile = false
return
}
isFileNewerThanSet, isFileNewerThanMatch, err2 := fh.SearchFileNewerThan(info, fileSelectionCriteria)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned from dMgr.searchFileNewerThan(info, fileSelectionCriteria).\n"+
"fileSelectionCriteria.FilesNewerThan='%v' info.Name()='%v'\nError='%v'\n",
fileSelectionCriteria.FilesNewerThan, info.Name(), err2.Error())
isMatchedFile = false
return
}
isFileModeSearchSet, isFileModeSearchMatch, err2 := fh.SearchFileModeMatch(info, fileSelectionCriteria)
if err2 != nil {
fileModeTxt := fileSelectionCriteria.SelectByFileMode.GetPermissionFileModeValueText()
err = fmt.Errorf(ePrefix+
"Error returned from dMgr.searchFileModeMatch(info, fileSelectionCriteria).\n"+
"fileSelectionCriteria.SelectByFileMode='%v'\n"+
"info.Name()='%v' Error='%v'\n",
fileModeTxt,
info.Name(), err2.Error())
isMatchedFile = false
return
}
// If no file selection criterion are set, then always select the file
if !isPatternSet && !isFileOlderThanSet && !isFileNewerThanSet && !isFileModeSearchSet {
isMatchedFile = true
err = nil
return
}
// If using the AND File Select Criterion Mode, then for criteria that
// are set and active, they must all be 'matched'.
if fileSelectionCriteria.SelectCriterionMode == FileSelectMode.ANDSelect() {
if isPatternSet && !isPatternMatch {
isMatchedFile = false
err = nil
return
}
if isFileOlderThanSet && !isFileOlderThanMatch {
isMatchedFile = false
err = nil
return
}
if isFileNewerThanSet && !isFileNewerThanMatch {
isMatchedFile = false
err = nil
return
}
if isFileModeSearchSet && !isFileModeSearchMatch {
isMatchedFile = false
err = nil
return
}
isMatchedFile = true
err = nil
return
} // End of fileSelectMode.ANDSelect()
// Must be fileSelectMode.ORSelect() Mode
// If ANY of the section criterion are active and 'matched', then
// classify the file as matched.
if isPatternSet && isPatternMatch {
isMatchedFile = true
err = nil
return
}
if isFileOlderThanSet && isFileOlderThanMatch {
isMatchedFile = true
err = nil
return
}
if isFileNewerThanSet && isFileNewerThanMatch {
isMatchedFile = true
err = nil
return
}
if isFileModeSearchSet && isFileModeSearchMatch {
isMatchedFile = true
err = nil
return
}
isMatchedFile = false
err = nil
return
}
// FindFilesInPath - Will apply a search pattern to files and directories
// in the path designated by input parameter, 'pathName'. If the files
// and or directory names match the input parameter, 'fileSearchPattern'
// they will be returned in an array of strings.
//
// Be Advised! The names returned in the string array may consist of both
// files and directory names, depending on the specified, 'fileSearchPattern'.
//
// This method uses the "path/filepath" function, 'Glob'. Reference:
// https://golang.org/pkg/path/filepath/#Glob
//
// The File matching patterns depend on the 'go' "path/filepath" function,
// 'Match'. Reference
// https://golang.org/pkg/path/filepath/#Match
//
// Note: This method will NOT search sub-directories. It will return the names
// of directories existing in the designated, 'pathName', depending on the
// 'fileSearchPattern' passed as an input parameter.
//
// If Input Parameters 'pathName' or 'fileSearchPattern' are empty strings or consist
// of all space characters, this method will return an error.
//
// Example 'fileSearchPattern' values:
// "*" = Returns all files and directories (everything)
// "*.*" = Returns files which have a file extension
// "*.txt" = Returns only files with a "txt" file extension
//
func (fh FileHelper) FindFilesInPath(pathName, fileSearchPattern string) ([]string, error) {
ePrefix := "FileHelper.FindFilesInPath() "
var pathDoesExist bool
var fInfo FileInfoPlus
var err error
var errCode int
pathName,
pathDoesExist,
fInfo,
err = fh.doesPathFileExist(pathName,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"pathName")
if err != nil {
return []string{}, err
}
errCode, _, fileSearchPattern = fh.isStringEmptyOrBlank(fileSearchPattern)
if errCode == -1 {
return []string{},
errors.New(ePrefix + "Error: Input parameter 'fileSearchPattern' is " +
"an empty string!\n")
}
if errCode == -2 {
return []string{},
errors.New(ePrefix + "Error: Input parameter 'fileSearchPattern' consists " +
"of blank spaces!\n")
}
if !pathDoesExist {
return []string{},
fmt.Errorf(ePrefix+"Error: Input parameter 'pathName' DOES NOT EXIST!\n"+
"pathName='%v'\n", pathName)
}
if !fInfo.IsDir() {
return []string{},
fmt.Errorf(ePrefix+"Error: The path exists, but it NOT a directory!\n"+
"pathName='%v' ", pathName)
}
// fInfo is a Directory.
searchStr := fh.JoinPathsAdjustSeparators(pathName, fileSearchPattern)
results, err := fp.Glob(searchStr)
if err != nil {
return []string{},
fmt.Errorf(ePrefix+
"Error returned by fp.Glob(searchStr).\n"+
"searchStr='%v'\nError='%v'\n",
searchStr, err.Error())
}
return results, nil
}
// FindFilesWalkDirectory - This method returns file information on files residing in a specified
// directory tree identified by the input parameter, 'startPath'.
//
// This method 'walks the directory tree' locating all files in the directory tree which match
// the file selection criteria submitted as input parameter, 'fileSelectCriteria'.
//
// If a file matches the File Selection Criteria, it is included in the returned field,
// 'DirectoryTreeInfo.FoundFiles'. By the way, if ALL the file selection criterion are set to zero values
// or 'Inactive', then ALL FILES in the directory are selected and returned in the field,
// 'DirectoryTreeInfo.FoundFiles'.
//
// ------------------------------------------------------------------------
//
// Input Parameter:
//
// startPath string - A string consisting of the starting path or
// or directory from which the find files search
// operation will commence.
//
// fileSelectCriteria FileSelectionCriteria -
// This input parameter should be configured with the desired file
// selection criteria. Files matching this criteria will be returned as
// 'Found Files'. If file 'fileSelectCriteria' is uninitialized (FileSelectionCriteria{}).
// all directories and files will be returned from the 'startPath'
//
//
// _______________________________________________________________________________________________
// type FileSelectionCriteria struct {
// FileNamePatterns []string // An array of strings containing File Name Patterns
// FilesOlderThan time.Time // Match files with older modification date times
// FilesNewerThan time.Time // Match files with newer modification date times
// SelectByFileMode FilePermissionConfig // Match file mode (os.FileMode).
// SelectCriterionMode FileSelectCriterionMode // Specifies 'AND' or 'OR' selection mode
// }
//
// The FileSelectionCriteria type allows for configuration of single or multiple file
// selection criterion. The 'SelectCriterionMode' can be used to specify whether the
// file must match all, or any one, of the active file selection criterion.
//
// Elements of the FileSelectionCriteria Type are described below:
//
// FileNamePatterns []string - An array of strings which may define one or more
// search patterns. If a file name matches any one of the
// search pattern strings, it is deemed to be a 'match'
// for the search pattern criterion.
//
// Example Patterns:
// FileNamePatterns = []string{"*.log"}
// FileNamePatterns = []string{"current*.txt"}
// FileNamePatterns = []string{"*.txt", "*.log"}
//
// If this string array has zero length or if
// all the strings are empty strings, then this
// file search criterion is considered 'Inactive'
// or 'Not Set'.
//
//
// FilesOlderThan time.Time - This date time type is compared to file
// modification date times in order to determine
// whether the file is older than the 'FilesOlderThan'
// file selection criterion. If the file is older than
// the 'FilesOlderThan' date time, that file is considered
// a 'match' for this file selection criterion.
//
// If the value of 'FilesOlderThan' is set to time zero,
// the default value for type time.Time{}, then this
// file selection criterion is considered to be 'Inactive'
// or 'Not Set'.
//
// FilesNewerThan time.Time - This date time type is compared to the file
// modification date time in order to determine
// whether the file is newer than the 'FilesNewerThan'
// file selection criterion. If the file modification date time
// is newer than the 'FilesNewerThan' date time, that file is
// considered a 'match' for this file selection criterion.
//
// If the value of 'FilesNewerThan' is set to time zero,
// the default value for type time.Time{}, then this
// file selection criterion is considered to be 'Inactive'
// or 'Not Set'.
//
// SelectByFileMode FilePermissionConfig -
// Type FilePermissionConfig encapsulates an os.FileMode. The file
// selection criterion allows for the selection of files by File Mode.
// File modes are compared to the value of 'SelectByFileMode'. If the
// File Mode for a given file is equal to the value of 'SelectByFileMode',
// that file is considered to be a 'match' for this file selection
// criterion. Examples for setting SelectByFileMode are shown as follows:
//
// fsc := FileSelectionCriteria{}
// err = fsc.SelectByFileMode.SetByFileMode(os.FileMode(0666))
// err = fsc.SelectByFileMode.SetFileModeByTextCode("-r--r--r--")
//
// SelectCriterionMode FileSelectCriterionMode -
// This parameter selects the manner in which the file selection
// criteria above are applied in determining a 'match' for file
// selection purposes. 'SelectCriterionMode' may be set to one of
// two constant values:
//
// _____________________________________________________________________
//
// FileSelectCriterionMode(0).ANDSelect() -
// File selected if all active selection criteria
// are satisfied.
//
// If this constant value is specified for the file selection mode,
// then a given file will not be judged as 'selected' unless all of
// the active selection criterion are satisfied. In other words, if
// three active search criterion are provided for 'FileNamePatterns',
// 'FilesOlderThan' and 'FilesNewerThan', then a file will NOT be
// selected unless it has satisfied all three criterion in this example.
//
// FileSelectCriterionMode(0).ORSelect() -
// File selected if any active selection criterion is satisfied.
//
// If this constant value is specified for the file selection mode,
// then a given file will be selected if any one of the active file
// selection criterion is satisfied. In other words, if three active
// search criterion are provided for 'FileNamePatterns', 'FilesOlderThan'
// and 'FilesNewerThan', then a file will be selected if it satisfies any
// one of the three criterion in this example.
//
// _____________________________________________________________________
//
//
// ------------------------------------------------------------------------
//
// IMPORTANT:
//
// If all of the file selection criterion in the FileSelectionCriteria object are
// 'Inactive' or 'Not Set' (set to their zero or default values), then all of
// the files processed in the directory tree will be selected and returned as
// 'Found Files'.
//
// Example:
// FileNamePatterns = ZERO Length Array
// filesOlderThan = time.Time{}
// filesNewerThan = time.Time{}
//
// In this example, all of the selection criterion are
// 'Inactive' and therefore all of the files encountered
// in the target directory will be selected and returned
// as 'Found Files'.
//
// This same effect can be achieved by simply creating an
// empty file selection instance:
//
// FileSelectionCriteria{}
//
//
// ------------------------------------------------------------------------
//
// Return Values:
//
// DirectoryTreeInfo - If successful, files matching the file selection criteria input
// parameter shown above will be returned in a 'DirectoryTreeInfo'
// object. The field 'DirectoryTreeInfo.FoundFiles' contains information
// on all the files in the specified directory tree which match the file selection
// criteria.
//
// Note: It is a good idea to check the returned field 'DirectoryTreeInfo.ErrReturns'
// to determine if any internal system errors were encountered while processing
// the directory tree.
//
// __________________________________________________________________________________________________
//
// type DirectoryTreeInfo struct {
// StartPath string // The starting path or directory for the file search
// dirMgrs []DirMgr // dirMgrs found during directory tree search
// FoundFiles []FileWalkInfo // Found Files matching file selection criteria
// ErrReturns []string // Internal System errors encountered
// FileSelectCriteria FileSelectionCriteria // The File Selection Criteria submitted as an
// // input parameter to this method.
// }
//
// __________________________________________________________________________________________________
//
// error - If a program execution error is encountered during processing, it will
// be returned as an 'error' type. Also, see the comment on 'DirectoryTreeInfo.ErrReturns',
// above.
//
func (fh FileHelper) FindFilesWalkDirectory(
startPath string,
fileSelectCriteria FileSelectionCriteria) (DirectoryTreeInfo, error) {
ePrefix := "FileHelper.FindFilesWalkDirectory() "
findFilesInfo := DirectoryTreeInfo{}
errCode := 0
errCode, _, startPath = fh.isStringEmptyOrBlank(startPath)
if errCode == -1 {
return findFilesInfo,
errors.New(ePrefix + "Error: Input parameter 'startPath' is an empty string!")
}
if errCode == -2 {
return findFilesInfo,
errors.New(ePrefix + "Error: Input parameter 'startPath' consists of blank spaces!")
}
startPath = fh.RemovePathSeparatorFromEndOfPathString(startPath)
var err error
startPath, err = fh.MakeAbsolutePath(startPath)
if err != nil {
return findFilesInfo,
fmt.Errorf(ePrefix+"Error returned by fh.MakeAbsolutePath(startPath). "+
"startPath='%v' Error='%v' ", startPath, err.Error())
}
if !fh.DoesFileExist(startPath) {
return findFilesInfo, fmt.Errorf(ePrefix+
"Error - startPath DOES NOT EXIST! startPath='%v'", startPath)
}
findFilesInfo.StartPath = startPath
findFilesInfo.FileSelectCriteria = fileSelectCriteria
err = fp.Walk(findFilesInfo.StartPath, fh.makeFileHelperWalkDirFindFilesFunc(&findFilesInfo))
if err != nil {
return findFilesInfo,
fmt.Errorf(ePrefix+
"Error returned from fp.Walk(findFilesInfo.StartPath, fh.makeFileHelperWalkDirFindFilesFunc"+
"(&findFilesInfo)). startPath='%v' Error='%v'", startPath, err.Error())
}
return findFilesInfo, nil
}
// GetAbsCurrDir - Returns the absolute path of the current working
// directory.
//
// The current work directory is determined by a call to os.Getwd().
// 'Getwd()' returns a rooted path name corresponding to the current directory.
// If the current directory can be reached via multiple paths (due to
// symbolic links), 'Getwd()' may return any one of them.
//
func (fh FileHelper) GetAbsCurrDir() (string, error) {
ePrefix := "FileHelper.GetAbsCurrDir() "
dir, err := os.Getwd()
if err != nil {
return "", fmt.Errorf(ePrefix+
"Error returned from os.Getwd().\nError='%v'\n",
err.Error())
}
absDir, err := fh.MakeAbsolutePath(dir)
if err != nil {
return "", fmt.Errorf(ePrefix+
"Error returned by fh.MakeAbsolutePath(dir).\nError='%v'\n",
err.Error())
}
return absDir, nil
}
// GetAbsPathFromFilePath - Supply a string containing both the path file name and extension.
// This method will then return the absolute value of that path, file name and file extension.
//
func (fh FileHelper) GetAbsPathFromFilePath(filePath string) (string, error) {
ePrefix := "FileHelper.GetAbsPathFromFilePath() "
errCode := 0
errCode, _, filePath = fh.isStringEmptyOrBlank(filePath)
if errCode == -1 {
return "",
errors.New(ePrefix + "Error: Input parameter 'filePath' is an empty string!")
}
if errCode == -2 {
return "",
errors.New(ePrefix + "Error: Input parameter 'filePath' consists of blank spaces!")
}
testFilePath := fh.AdjustPathSlash(filePath)
errCode, _, testFilePath = fh.isStringEmptyOrBlank(testFilePath)
if errCode < 0 {
return "",
errors.New(ePrefix +
"Error: After adjusting path Separators, filePath resolves to an empty string!")
}
absPath, err := fh.MakeAbsolutePath(testFilePath)
if err != nil {
return "",
fmt.Errorf(ePrefix+
"Error returned from fh.MakeAbsolutePath(testFilePath). "+
"testFilePath='%v' Error='%v' ",
testFilePath, err.Error())
}
return absPath, nil
}
// GetCurrentDir - Wrapper function for Getwd(). Getwd returns a
// rooted path name corresponding to the current directory.
// If the current directory can be reached via multiple paths
// (due to symbolic links), Getwd may return any one of them.
func (fh FileHelper) GetCurrentDir() (string, error) {
ePrefix := "FileHelper.GetCurrentDir()"
currDir, err := os.Getwd()
if err != nil {
return "",
fmt.Errorf(ePrefix+"Error returned by os.Getwd(). Error='%v' ",
err.Error())
}
return currDir, nil
}
// GetDotSeparatorIndexesInPathStr - Returns an array of integers representing the
// indexes of dots ('.') located in input parameter 'pathStr'.
//
func (fh FileHelper) GetDotSeparatorIndexesInPathStr(pathStr string) ([]int, error) {
ePrefix := "FileHelper.GetDotSeparatorIndexesInPathStr() "
errCode := 0
lPathStr := 0
errCode, lPathStr, pathStr = fh.isStringEmptyOrBlank(pathStr)
if errCode == -1 {
return []int{},
errors.New(ePrefix +
"Error: Input parameter 'pathStr' is an empty string!\n")
}
if errCode == -2 {
return []int{},
errors.New(ePrefix +
"Error: Input parameter 'pathStr' consists of blank spaces!\n")
}
var dotIdxs []int
for i := 0; i < lPathStr; i++ {
rChar := pathStr[i]
if rChar == '.' {
dotIdxs = append(dotIdxs, i)
}
}
return dotIdxs, nil
}
// GetExecutablePathFileName - Gets the path and file name of the
// executable that started the current process.
//
// This executable path and file name is generated by a call to
// os.Executable().
//
// os.Executable() returns the path name for the executable that started
// the current process. There is no guarantee that the path is still
// pointing to the correct executable. If a symlink was used to start
// the process, depending on the operating system, the result might
// be the symlink or the path it pointed to. If a stable result is
// needed, path/filepath.EvalSymlinks might help.
//
// Executable returns an absolute path unless an error occurred.
//
// The main use case is finding resources located relative to an
// executable.
//
// Executable is not supported on nacl.
//
func (fh FileHelper) GetExecutablePathFileName() (string, error) {
ePrefix := "FileHelper.GetExecutablePathFileName() "
ex, err := os.Executable()
if err != nil {
return "",
fmt.Errorf(ePrefix+"Error returned by os.Executable(). Error='%v' ",
err.Error())
}
return ex, err
}
// GetFileExt - Returns the File Extension with
// the dot. If there is no File Extension an empty
// string is returned (NO dot included). If the returned
// File Extension is an empty string, the returned
// parameter 'isEmpty' is set equal to 'true'.
//
// When an extension is returned in the 'ext' variable, this
// extension includes a leading dot. Example: '.txt'
//
// Example:
//
// Actual File Name Plus Extension: "newerFileForTest_01.txt"
// Returned File Extension: "txt"
//
// Actual File Name Plus Extension: "newerFileForTest_01"
// Returned File Extension: ""
//
// Actual File Name Plus Extension: ".gitignore"
// Returned File Extension: ""
//
func (fh FileHelper) GetFileExtension(
pathFileNameExt string) (ext string, isEmpty bool, err error) {
ePrefix := "FileHelper.GetFileExt() "
ext = ""
isEmpty = true
err = nil
errCode := 0
errCode, _, pathFileNameExt = fh.isStringEmptyOrBlank(pathFileNameExt)
if errCode == -1 {
err =
errors.New(ePrefix + "Error: Input parameter 'pathFileNameExt' is an empty string!")
return ext, isEmpty, err
}
if errCode == -2 {
err =
errors.New(ePrefix + "Error: Input parameter 'pathFileNameExt' consists of blank spaces!")
return ext, isEmpty, err
}
testPathFileNameExt := fh.AdjustPathSlash(pathFileNameExt)
errCode, _, testPathFileNameExt = fh.isStringEmptyOrBlank(testPathFileNameExt)
if errCode < 0 {
err = errors.New(ePrefix +
"Error: Cleaned version of 'pathFileNameExt', 'testPathFileNameExt' is an empty string!")
return ext, isEmpty, err
}
dotIdxs, err2 := fh.GetDotSeparatorIndexesInPathStr(testPathFileNameExt)
if err2 != nil {
ext = ""
isEmpty = true
err = fmt.Errorf(ePrefix+
"Error returned from fh.GetDotSeparatorIndexesInPathStr(testPathFileNameExt).\n"+
"testPathFileNameExt='%v'\nError='%v'\n", testPathFileNameExt, err2)
return ext, isEmpty, err
}
lenDotIdxs := len(dotIdxs)
// Deal with case where the pathFileNameExt contains
// no dots.
if lenDotIdxs == 0 {
ext = ""
isEmpty = true
err = nil
return ext, isEmpty, err
}
firstGoodCharIdx, lastGoodCharIdx, err2 :=
fh.GetFirstLastNonSeparatorCharIndexInPathStr(testPathFileNameExt)
if err2 != nil {
ext = ""
isEmpty = true
err = fmt.Errorf(ePrefix+
"Error returned from fh.GetFirstLastNonSeparatorCharIndexInPathStr(testPathFileNameExt).\n"+
"testPathFileNameExt='%v'\nError='%v'\n",
testPathFileNameExt, err2)
return ext, isEmpty, err
}
// Deal with the case where pathFileNameExt contains no
// valid alpha numeric characters
if firstGoodCharIdx == -1 || lastGoodCharIdx == -1 {
ext = ""
isEmpty = true
err = nil
return ext, isEmpty, err
}
slashIdxs, err2 := fh.GetPathSeparatorIndexesInPathStr(testPathFileNameExt)
if err2 != nil {
ext = ""
isEmpty = true
err = fmt.Errorf(ePrefix+
"Error returned from fh.GetPathSeparatorIndexesInPathStr(testPathFileNameExt). "+
"testPathFileNameExt='%v' Error='%v'", testPathFileNameExt, err2)
return ext, isEmpty, err
}
lenSlashIdxs := len(slashIdxs)
if lenSlashIdxs == 0 &&
lenDotIdxs == 1 &&
dotIdxs[lenDotIdxs-1] == 0 {
// deal with the case .gitignore
ext = ""
isEmpty = true
err = nil
return ext, isEmpty, err
}
if lenSlashIdxs == 0 {
ext = testPathFileNameExt[dotIdxs[lenDotIdxs-1]:]
isEmpty = false
err = nil
return ext, isEmpty, err
}
// lenDotIdxs and lenSlasIdxs both greater than zero
if dotIdxs[lenDotIdxs-1] > slashIdxs[lenSlashIdxs-1] &&
dotIdxs[lenDotIdxs-1] < lastGoodCharIdx {
ext = testPathFileNameExt[dotIdxs[lenDotIdxs-1]:]
isEmpty = false
err = nil
return ext, isEmpty, err
}
ext = ""
isEmpty = true
err = nil
return ext, isEmpty, err
}
// GetFileInfo - Wrapper function for os.Stat(). This method
// can be used to return FileInfo data on a specific file. If the file
// does NOT exist, an error will be triggered.
//
// This method is similar to FileHelper.DoesFileInfoExist().
//
// type FileInfo interface {
// Name() string // base name of the file
// Size() int64 // length in bytes for regular files; system-dependent for others
// Mode() FileMode // file mode bits
// ModTime() time.Time // modification time
// IsDir() bool // abbreviation for Mode().IsDir()
// Sys() interface{} // underlying data source (can return nil)
// }
//
func (fh FileHelper) GetFileInfo(pathFileName string) (os.FileInfo, error) {
ePrefix := "FileHelper.GetFileInfo() "
var pathDoesExist bool
var fInfo FileInfoPlus
var err error
pathFileName,
pathDoesExist,
fInfo,
err = fh.doesPathFileExist(pathFileName,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"pathFileName")
if err != nil {
return nil, err
}
if !pathDoesExist {
return nil, fmt.Errorf(ePrefix+
"Error: Input parameter 'pathFileName' does NOT exist!\n"+
"pathFileName='%v'\n",
pathFileName)
}
return fInfo.GetOriginalFileInfo(), nil
}
// GetFileLastModificationDate - Returns the last modification'
// date/time on a specific file. If input parameter 'customTimeFmt'
// string is empty, a default time format will be used to format the
// returned time string.
//
// The default date time format is:
// "2006-01-02 15:04:05.000000000"
//
func (fh FileHelper) GetFileLastModificationDate(
pathFileName string,
customTimeFmt string) (time.Time, string, error) {
ePrefix := "FileHelper.GetFileLastModificationDate() "
const fmtDateTimeNanoSecondStr = "2006-01-02 15:04:05.000000000 -0700 MST"
var zeroTime time.Time
var pathFileNameDoesExist bool
var fInfo FileInfoPlus
var err error
var errCode int
pathFileName,
pathFileNameDoesExist,
fInfo,
err = fh.doesPathFileExist(pathFileName,
PreProcPathCode.AbsolutePath(), // Skip Convert to Absolute Path
ePrefix,
"pathFileName")
if err != nil {
return zeroTime, "", err
}
if !pathFileNameDoesExist {
return zeroTime, "",
fmt.Errorf(ePrefix+"ERROR: 'pathFileName' DOES NOT EXIST!\n"+
"pathFileName='%v'\n", pathFileName)
}
errCode, _, customTimeFmt = fh.isStringEmptyOrBlank(customTimeFmt)
fmtStr := customTimeFmt
if errCode < 0 {
fmtStr = fmtDateTimeNanoSecondStr
}
return fInfo.ModTime(), fInfo.ModTime().Format(fmtStr), nil
}
// GetFileMode - Returns the mode (os.FileMode) for the file designated by
// input parameter 'pathFileName'. If the file does not exist, an error
// is triggered.
//
// The 'os.FileMode' is returned via type 'FilePermissionCfg' which includes
// methods necessary to interpret the 'os.FileMode'.
//
func (fh FileHelper) GetFileMode(pathFileName string) (FilePermissionConfig, error) {
ePrefix := "FileHelper.GetFileMode() "
var pathFileNameDoesExist bool
var fInfo FileInfoPlus
var err error
pathFileName,
pathFileNameDoesExist,
fInfo,
err = fh.doesPathFileExist(pathFileName,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"pathFileName")
if err != nil {
return FilePermissionConfig{}, err
}
if !pathFileNameDoesExist {
return FilePermissionConfig{},
fmt.Errorf(ePrefix+
"ERROR: 'pathFileName' DOES NOT EXIST!\n"+
"pathFileName='%v'\n", pathFileName)
}
fPermCfg, err := FilePermissionConfig{}.NewByFileMode(fInfo.Mode())
if err != nil {
return FilePermissionConfig{},
fmt.Errorf(ePrefix+
"Error returned by FilePermissionConfig{}.NewByFileMode(fInfo.Mode()).\n"+
"fInfo.Mode()='%v'\nError='%v'\n",
fInfo.Mode(), err.Error())
}
return fPermCfg, nil
}
// GetFileNameWithExt - This method expects to receive a valid directory path and file
// name or file name plus extension. It then extracts the File Name and Extension from
// the file path and returns it as a string.
//
// ------------------------------------------------------------------------
//
// Input Parameters:
//
// pathFileNameExt string - This input parameter is expected to contain a properly formatted directory
// path and File Name. The File Name may or may not include a File Extension.
// The directory path must include the correct delimiters such as path Separators
// ('/' or'\'), dots ('.') and in the case of Windows, a volume designation
// (Example: 'F:').
//
// ------------------------------------------------------------------------
//
// Return Values:
//
// fNameExt string - If successful, this method will the return value 'fNameExt' equal to the
// File Name and File Extension extracted from the input file path, 'pathFileNameExt'.
// Example 'fNameExt' return value: 'someFilename.txt'
//
// If the File Extension is not present, only the File Name will be returned.
// Example return value with no file extension: 'someFilename'.
//
// isEmpty bool - If this method CAN NOT parse out a valid File Name and Extension from
// input parameter string 'pathFileNameExt', return value 'fNameExt' will
// be set to an empty string and return value 'isEmpty' will be set to 'true'.
//
// err error - If an error is encountered during processing, 'err' will return a properly
// formatted 'error' type.
//
// Note that if this method cannot parse out a valid File Name and Extension
// due to an improperly formatted directory path and file name string
// (Input Parameter: 'pathFileNameExt'), 'fNameExt' will be set to an empty string,
// 'isEmpty' will be set to 'true' and 'err' return 'nil'. In this situation, no
// error will be returned.
//
func (fh FileHelper) GetFileNameWithExt(
pathFileNameExt string) (fNameExt string, isEmpty bool, err error) {
ePrefix := "FileHelper.GetFileNameWithExt "
fNameExt = ""
isEmpty = true
err = nil
errCode := 0
errCode, _, pathFileNameExt = fh.isStringEmptyOrBlank(pathFileNameExt)
if errCode == -1 {
err =
errors.New(ePrefix + "Error: Input parameter 'pathFileNameExt' is an empty string!")
return fNameExt, isEmpty, err
}
if errCode == -2 {
err =
errors.New(ePrefix + "Error: Input parameter 'pathFileNameExt' consists of blank spaces!")
return fNameExt, isEmpty, err
}
testPathFileNameExt := fh.AdjustPathSlash(pathFileNameExt)
volName := fh.GetVolumeName(testPathFileNameExt)
if volName != "" {
testPathFileNameExt = strings.TrimPrefix(testPathFileNameExt, volName)
}
lTestPathFileNameExt := 0
errCode, lTestPathFileNameExt, testPathFileNameExt = fh.isStringEmptyOrBlank(testPathFileNameExt)
if errCode < 0 {
err = errors.New(ePrefix +
"Error: Cleaned version of 'pathFileNameExt', 'testPathFileNameExt' is an empty string!")
return fNameExt, isEmpty, err
}
firstCharIdx, lastCharIdx, err2 := fh.GetFirstLastNonSeparatorCharIndexInPathStr(testPathFileNameExt)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned by fh.GetFirstLastNonSeparatorCharIndexInPathStr(testPathFileNameExt). "+
"testPathFileNameExt='%v' Error='%v'", testPathFileNameExt, err2.Error())
return fNameExt, isEmpty, err
}
// There are no alpha numeric characters present.
// Therefore, there is no file name and extension
if firstCharIdx == -1 || lastCharIdx == -1 {
isEmpty = true
err = nil
return fNameExt, isEmpty, err
}
slashIdxs, err2 := fh.GetPathSeparatorIndexesInPathStr(testPathFileNameExt)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned by fh.GetPathSeparatorIndexesInPathStr(testPathFileNameExt). "+
"testPathFileNameExt='%v' Error='%v'", testPathFileNameExt, err2.Error())
return fNameExt, isEmpty, err
}
dotIdxs, err2 := fh.GetDotSeparatorIndexesInPathStr(testPathFileNameExt)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned by fh.GetDotSeparatorIndexesInPathStr(testPathFileNameExt). "+
"testPathFileNameExt='%v' Error='%v'", testPathFileNameExt, err2.Error())
return fNameExt, isEmpty, err
}
lSlashIdxs := len(slashIdxs)
lDotIdxs := len(dotIdxs)
if lSlashIdxs > 0 {
// This string has path separators
// Last char is a path separator. Therefore,
// there is no file name and extension.
if slashIdxs[lSlashIdxs-1] == lTestPathFileNameExt-1 {
fNameExt = ""
} else if lastCharIdx > slashIdxs[lSlashIdxs-1] {
fNameExt = testPathFileNameExt[slashIdxs[lSlashIdxs-1]+1:]
} else {
fNameExt = ""
}
if len(fNameExt) == 0 {
isEmpty = true
} else {
isEmpty = false
}
err = nil
return fNameExt, isEmpty, err
}
// There are no path separators lSlashIdxs == 0
if lDotIdxs > 0 {
// This string has one or more dot separators ('.')
fNameExt = ""
if firstCharIdx > dotIdxs[lDotIdxs-1] {
// Example '.txt' - Valid File name and extension
// such as '.gitignore'
fNameExt = testPathFileNameExt[dotIdxs[lDotIdxs-1]:]
} else if firstCharIdx < dotIdxs[lDotIdxs-1] {
fNameExt = testPathFileNameExt[firstCharIdx:]
}
if len(fNameExt) == 0 {
isEmpty = true
} else {
isEmpty = false
}
err = nil
return fNameExt, isEmpty, err
}
// Must be lSlashIdxs == 0 && lDotIdxs == 0
// There are no path Separators and there are
// no dot separators ('.').
fNameExt = testPathFileNameExt[firstCharIdx:]
if len(fNameExt) == 0 {
isEmpty = true
} else {
isEmpty = false
}
err = nil
return fNameExt, isEmpty, err
}
// GetFileNameWithoutExt - returns the file name
// without the path or extension. If the returned
// File Name is an empty string, isEmpty is set to true.
//
//
// Example:
//
// Actual Path Plus File Name: = "./pathfilego/003_filehelper/common/xt_dirmgr_01_test.go"
// Returned File Name: = "dirmgr_01_test"
//
// Actual File Name Plus Extension: "newerFileForTest_01.txt"
// Returned File Name: "newerFileForTest_01"
//
// Actual File Name Plus Extension: "newerFileForTest_01"
// Returned File Name: "newerFileForTest_01"
//
// Actual File Name Plus Extension: ".gitignore"
// Returned File Name: ".gitignore"
//
//
func (fh FileHelper) GetFileNameWithoutExt(
pathFileNameExt string) (fName string, isEmpty bool, err error) {
ePrefix := "FileHelper.GetFileNameWithoutExt() "
fName = ""
isEmpty = true
err = nil
errCode := 0
errCode, _, pathFileNameExt = fh.isStringEmptyOrBlank(pathFileNameExt)
if errCode == -1 {
err =
errors.New(ePrefix + "Error: Input parameter 'pathFileNameExt' is an empty string!")
return fName, isEmpty, err
}
if errCode == -2 {
err =
errors.New(ePrefix + "Error: Input parameter 'pathFileNameExt' consists of blank spaces!")
return fName, isEmpty, err
}
testPathFileNameExt := fh.AdjustPathSlash(pathFileNameExt)
errCode, _, testPathFileNameExt = fh.isStringEmptyOrBlank(testPathFileNameExt)
if errCode < 0 {
err = errors.New(ePrefix +
"Error: Adjusted path version of 'pathFileNameExt', 'testPathFileNameExt' is an empty string!")
return fName, isEmpty, err
}
fileNameExt, isFileNameExtEmpty, err2 := fh.GetFileNameWithExt(testPathFileNameExt)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned from fh.GetFileNameWithExt(testPathFileNameExt) testPathFileNameExt='%v' Error='%v'",
testPathFileNameExt, err2.Error())
return fName, isEmpty, err
}
if isFileNameExtEmpty {
isEmpty = true
fName = ""
err = nil
return fName, isEmpty, err
}
dotIdxs, err2 := fh.GetDotSeparatorIndexesInPathStr(fileNameExt)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned from fh.GetDotSeparatorIndexesInPathStr(fileNameExt). fileNameExt='%v' Error='%v'",
fileNameExt, err2.Error())
return fName, isEmpty, err
}
lDotIdxs := len(dotIdxs)
if lDotIdxs == 1 &&
dotIdxs[lDotIdxs-1] == 0 {
// Outlier Case: .gitignore
fName = fileNameExt[0:]
if fName == "" {
isEmpty = true
} else {
isEmpty = false
}
err = nil
return fName, isEmpty, err
}
// Primary Case: filename.ext
if lDotIdxs > 0 {
fName = fileNameExt[0:dotIdxs[lDotIdxs-1]]
if fName == "" {
isEmpty = true
} else {
isEmpty = false
}
err = nil
return fName, isEmpty, err
}
// Secondary Case: filename
fName = fileNameExt
if fName == "" {
isEmpty = true
} else {
isEmpty = false
}
err = nil
return fName, isEmpty, err
}
// GetFirstLastNonSeparatorCharIndexInPathStr - Basically this method returns
// the first index of the first alpha numeric character in a path string.
//
// Specifically, the character must not be a path Separator ('\', '/') and
// it must not be a dot ('.').
//
// If the first Non-Separator char is found, this method will return
// an integer index which is greater than or equal to zero plus an
// error value of nil.
//
// The first character found will never be part of the volume name.
// Example On Windows: "D:\fDir1\fDir2" - first character index will
// be 3 denoting character 'f'.
//
func (fh FileHelper) GetFirstLastNonSeparatorCharIndexInPathStr(
pathStr string) (firstIdx, lastIdx int, err error) {
ePrefix := "FileHelper.GetFirstNonSeparatorCharIndexInPathStr() "
firstIdx = -1
lastIdx = -1
errCode := 0
errCode, _, pathStr = fh.isStringEmptyOrBlank(pathStr)
if errCode == -1 {
err = errors.New(ePrefix +
"Error: Input parameter 'pathStr' is an empty string!\n")
return firstIdx, lastIdx, err
}
if errCode == -2 {
err = errors.New(ePrefix + "Error: Input parameter 'pathStr' consists of blank spaces!\n")
return firstIdx, lastIdx, err
}
pathStr = fh.AdjustPathSlash(pathStr)
lPathStr := 0
errCode, lPathStr, pathStr = fh.isStringEmptyOrBlank(pathStr)
if errCode < 0 {
err = fmt.Errorf(ePrefix +
"Error: After path Separator adjustment, 'pathStr' is an empty string!\n")
return firstIdx, lastIdx, err
}
// skip the volume name. Don't count
// first characters in the volume name
volName := fp.VolumeName(pathStr)
lVolName := len(volName)
startIdx := 0
if lVolName > 0 {
startIdx = lVolName
}
var rChar rune
forbiddenTextChars := []rune{os.PathSeparator,
'\\',
'/',
'|',
'.',
'&',
'!',
'%',
'$',
'#',
'@',
'^',
'*',
'(',
')',
'-',
'_',
'+',
'=',
'[',
'{',
']',
'}',
'|',
'<',
'>',
',',
'~',
'`',
':',
';',
'"',
'\'',
'\n',
'\t',
'\r'}
lForbiddenTextChars := len(forbiddenTextChars)
for i := startIdx; i < lPathStr; i++ {
rChar = rune(pathStr[i])
isForbidden := false
for j := 0; j < lForbiddenTextChars; j++ {
if rChar == forbiddenTextChars[j] {
isForbidden = true
}
}
if isForbidden == false {
if firstIdx == -1 {
firstIdx = i
}
lastIdx = i
}
}
err = nil
return firstIdx, lastIdx, err
}
// GetLastPathElement - Analyzes a 'pathName' string and returns the last
// element in the path. If 'pathName' ends in a path separator ('/'), this
// method returns an empty string.
//
// Example:
//
// pathName = '../dir1/dir2/fileName.ext' will return "fileName.ext"
// pathName = '../dir1/dir2/' will return ""
// pathName = 'fileName.ext' will return "fileName.ext"
// pathName = '../dir1/dir2/dir3' will return "dir3"
//
func (fh FileHelper) GetLastPathElement(pathName string) (string, error) {
ePrefix := "FileHelper.GetLastPathElement() "
errCode := 0
errCode, _, pathName = fh.isStringEmptyOrBlank(pathName)
if errCode == -1 {
return "",
errors.New(ePrefix +
"Error: Input parameter 'pathName' is an empty string!\n")
}
if errCode == -2 {
return "",
errors.New(ePrefix +
"Error: Input parameter 'pathName' consists of blank spaces!\n")
}
adjustedPath := fh.AdjustPathSlash(pathName)
resultAry := strings.Split(adjustedPath, string(os.PathSeparator))
lResultAry := len(resultAry)
if lResultAry == 0 {
return adjustedPath, nil
}
return resultAry[lResultAry-1], nil
}
// GetPathAndFileNameExt - Breaks out path and fileName+Ext elements from
// a path string. If both path and fileName are empty strings, this method
// returns an error.
func (fh FileHelper) GetPathAndFileNameExt(
pathFileNameExt string) (pathDir, fileNameExt string, bothAreEmpty bool, err error) {
ePrefix := "FileHelper.GetPathAndFileNameExt() "
pathDir = ""
fileNameExt = ""
bothAreEmpty = true
err = nil
errCode := 0
trimmedFileNameExt := ""
errCode, _, trimmedFileNameExt = fh.isStringEmptyOrBlank(pathFileNameExt)
if errCode == -1 {
err = errors.New(ePrefix +
"Error: Input parameter 'pathFileName' is an empty string!\n")
return pathDir, fileNameExt, bothAreEmpty, err
}
if errCode == -2 {
err = errors.New(ePrefix +
"Error: Input parameter 'pathFileName' consists of blank spaces!\n")
return pathDir, fileNameExt, bothAreEmpty, err
}
xFnameExt, isEmpty, err2 := fh.GetFileNameWithExt(trimmedFileNameExt)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned from fh.GetFileNameWithExt(pathFileNameExt).\n"+
"pathFileNameExt='%v'\nError='%v'\n",
pathFileNameExt, err2.Error())
return
}
if isEmpty {
fileNameExt = ""
} else {
fileNameExt = xFnameExt
}
remainingPathStr := strings.TrimSuffix(trimmedFileNameExt, fileNameExt)
if len(remainingPathStr) == 0 {
pathDir = ""
if pathDir == "" && fileNameExt == "" {
bothAreEmpty = true
} else {
bothAreEmpty = false
}
err = nil
return
}
xPath, isEmpty, err2 := fh.GetPathFromPathFileName(remainingPathStr)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned from fh.GetPathFromPathFileName(remainingPathStr).\n"+
"remainingPathStr='%v'\nError='%v'\n",
remainingPathStr, err2.Error())
return
}
if isEmpty {
pathDir = ""
} else {
pathDir = xPath
}
if pathDir == "" && fileNameExt == "" {
bothAreEmpty = true
} else {
bothAreEmpty = false
}
err = nil
return
}
// GetPathFromPathFileName - Returns the path from a path and file name string.
// If the returned path is an empty string, return parameter 'isEmpty' is set to
// 'true'.
//
// ------------------------------------------------------------------------
//
// Input Parameter:
//
// pathFileNameExt string - This is an input parameter. The method expects to
// receive a single, properly formatted path and file
// name string delimited by dots ('.') and path Separators
// ('/' or '\'). On Windows the 'pathFileNameExt' string
// valid volume designations (Example: "D:")
//
// ------------------------------------------------------------------------
//
// Return Values:
//
// path string - This is the directory path extracted from the input parameter
// 'pathFileNameExt'. If successful, the 'path' string that is returned
// by this method WILL NOT include a trailing path separator ('/' or '\'
// depending on the os). Example 'path': "./pathfile/003_filehelper"
//
// isEmpty bool - If the method determines that it cannot extract a valid directory
// path from input parameter 'pathFileNameExt', this boolean value
// will be set to 'true'. Failure to extract a valid directory path
// will occur if the input parameter 'pathFileNameExt' is not properly
// formatted as a valid path and file name.
//
// err error - If a processing error is detected, an error will be returned. Note that
// in the event that this method fails to extract a valid directory path
// 'pathFileNameExt' due to the fact that 'pathFileNameExt' was improperly
// formatted, 'isEmpty' will be set to 'true', but no error will be returned.
//
// If no error occurs, 'err' is set to 'nil'.
//
// ------------------------------------------------------------------------
//
// Examples:
//
// pathFileNameExt = "" returns isEmpty==true err==nil
// pathFileNameExt = "D:\" returns "D:\"
// pathFileNameExt = "." returns ".\"
// pathFileNameExt = "..\" returns "..\"
// pathFileNameExt = "...\" returns ERROR
//
// pathFileNameExt = ".\pathfile\003_filehelper\wt_HowToRunTests.md"
// returns ".\pathfile\003_filehelper"
//
// pathFileNameExt = "someFile.go" returns ""
// pathFileNameExt = "..\dir1\dir2\.git" returns "..\dir1\dir2"
// '.git' is assumed to be a file.
//
func (fh FileHelper) GetPathFromPathFileName(
pathFileNameExt string) (dirPath string, isEmpty bool, err error) {
ePrefix := "FileHelper.GetPathFromPathFileName() "
dirPath = ""
isEmpty = true
err = nil
errCode := 0
errCode, _, pathFileNameExt = fh.isStringEmptyOrBlank(pathFileNameExt)
if errCode == -1 {
err = errors.New(ePrefix +
"Error: Input parameter 'pathFileNameExt' is an empty string!\n")
return dirPath, isEmpty, err
}
if errCode == -2 {
err =
errors.New(ePrefix +
"Error: Input parameter 'pathFileNameExt' consists of blank spaces!\n")
return dirPath, isEmpty, err
}
testPathStr, isDirEmpty, err2 := fh.CleanDirStr(pathFileNameExt)
if err2 != nil {
err = fmt.Errorf(ePrefix+"Error returned by fh.CleanDirStr(pathFileNameExt).\n"+
"pathFileNameExt='%v'\nError='%v'\n",
pathFileNameExt, err2.Error())
return dirPath, isEmpty, err
}
if isDirEmpty {
dirPath = ""
isEmpty = true
err = nil
return dirPath, isEmpty, err
}
lTestPathStr := len(testPathStr)
if lTestPathStr == 0 {
err = errors.New(ePrefix +
"Error: AdjustPathSlash was applied to 'pathStr'.\n" +
"The 'testPathStr' string is a Zero Length string!\n")
return dirPath, isEmpty, err
}
slashIdxs, err2 := fh.GetPathSeparatorIndexesInPathStr(testPathStr)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned by fh.GetPathSeparatorIndexesInPathStr(testPathStr).\n"+
"testPathStr='%v'\nError='%v'\n",
testPathStr, err2.Error())
return dirPath, isEmpty, err
}
lSlashIdxs := len(slashIdxs)
firstGoodChar, lastGoodChar, err2 :=
fh.GetFirstLastNonSeparatorCharIndexInPathStr(testPathStr)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned by fh.GetFirstLastNonSeparatorCharIndexInPathStr("+
"testPathStr).\n"+
"testPathStr='%v'\nError='%v'\n",
testPathStr, err2.Error())
return dirPath, isEmpty, err
}
dotIdxs, err2 := fh.GetDotSeparatorIndexesInPathStr(testPathStr)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned by fh.GetDotSeparatorIndexesInPathStr(testPathStr).\n"+
"testPathStr='%v'\nError='%v'\n",
testPathStr, err2.Error())
return dirPath, isEmpty, err
}
lDotIdxs := len(dotIdxs)
var finalPathStr string
volName := fp.VolumeName(testPathStr)
if testPathStr == volName {
finalPathStr = testPathStr
} else if strings.Contains(testPathStr, "...") {
err = fmt.Errorf(ePrefix+
"Error: PATH CONTAINS INVALID Dot Characters!\n"+
"testPathStr='%v'\n", testPathStr)
return dirPath, isEmpty, err
} else if firstGoodChar == -1 || lastGoodChar == -1 {
absPath, err2 := fh.MakeAbsolutePath(testPathStr)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned from fh.MakeAbsolutePath(testPathStr).\n"+
"testPathStr='%v'\nError='%v'\n",
testPathStr, err2.Error())
return dirPath, isEmpty, err
}
if absPath == "" {
err = fmt.Errorf(ePrefix+
"Error: Could not convert 'testPathStr' to Absolute path!\n"+
"testPathStr='%v'\n",
testPathStr)
return dirPath, isEmpty, err
}
finalPathStr = testPathStr
} else if lSlashIdxs == 0 {
// No path separators but alpha numeric chars are present
dirPath = ""
isEmpty = true
err = nil
return dirPath, isEmpty, err
} else if lDotIdxs == 0 {
//path separators are present but there are no dots in the string
if slashIdxs[lSlashIdxs-1] == lTestPathStr-1 {
// Trailing path separator
finalPathStr = testPathStr[0:slashIdxs[lSlashIdxs-2]]
} else {
finalPathStr = testPathStr
}
} else if dotIdxs[lDotIdxs-1] > slashIdxs[lSlashIdxs-1] {
// format: ./dir1/dir2/fileName.ext
finalPathStr = testPathStr[0:slashIdxs[lSlashIdxs-1]]
} else if dotIdxs[lDotIdxs-1] < slashIdxs[lSlashIdxs-1] {
finalPathStr = testPathStr
} else {
err = fmt.Errorf(ePrefix+
"Error: INVALID PATH STRING.\n"+
"testPathStr='%v'\n", testPathStr)
return dirPath, isEmpty, err
}
if len(finalPathStr) == 0 {
err = fmt.Errorf(ePrefix + "Error: Processed path is a Zero Length String!\n")
return dirPath, isEmpty, err
}
//Successfully isolated and returned a valid
// directory path from 'pathFileNameExt'
dirPath = finalPathStr
if len(dirPath) == 0 {
isEmpty = true
} else {
isEmpty = false
}
err = nil
return dirPath, isEmpty, err
}
// GetPathSeparatorIndexesInPathStr - Returns an array containing the indexes of
// path Separators (Forward slashes or backward slashes depending on operating
// system).
func (fh FileHelper) GetPathSeparatorIndexesInPathStr(
pathStr string) ([]int, error) {
ePrefix := "FileHelper.GetPathSeparatorIndexesInPathStr() "
errCode := 0
lPathStr := 0
errCode, lPathStr, pathStr = fh.isStringEmptyOrBlank(pathStr)
if errCode == -1 {
return []int{},
errors.New(ePrefix +
"Error: Input parameter 'pathStr' is an empty string!\n")
}
if errCode == -2 {
return []int{},
errors.New(ePrefix +
"Error: Input parameter 'pathStr' consists of blank spaces!\n")
}
var slashIdxs []int
for i := 0; i < lPathStr; i++ {
rChar := pathStr[i]
if rChar == os.PathSeparator ||
rChar == '\\' ||
rChar == '/' {
slashIdxs = append(slashIdxs, i)
}
}
return slashIdxs, nil
}
// GetVolumeName - Returns the volume name of associated with
// a given directory path. The method calls the function
// 'path/filepath.VolumeName().
//
// VolumeName() returns the leading volume name if it exists
// in input parameter 'pathStr'.
//
// Given "C:\foo\bar" it returns "C:" on Windows.
// Given "c:\foo\bar" it returns "c:" on Windows.
// Given "\\host\share\foo" it returns "\\host\share" on linux
// On other platforms, it returns "".
//
func (fh FileHelper) GetVolumeName(pathStr string) string {
errCode := 0
errCode, _, pathStr = fh.isStringEmptyOrBlank(pathStr)
if errCode < 0 {
return ""
}
return fp.VolumeName(pathStr)
}
// GetVolumeNameIndex - Analyzes input parameter 'pathStr' to
// determine if it contains a volume name.
// The method calls the function 'path/filepath.VolumeName().
//
// VolumeName() returns the leading volume name if it exists
// in input parameter 'pathStr'.
//
// Given "C:\foo\bar" it returns "C:" on Windows.
// Given "c:\foo\bar" it returns "c:" on Windows.
// Given "\\host\share\foo" it returns "\\host\share" on linux
// On other platforms, it returns "".
//
func (fh FileHelper) GetVolumeNameIndex(
pathStr string) (volNameIndex int, volNameLength int, volNameStr string) {
volNameIndex = -1
volNameLength = 0
volNameStr = ""
errCode := 0
errCode, _, pathStr = fh.isStringEmptyOrBlank(pathStr)
if errCode < 0 {
return volNameIndex, volNameLength, volNameStr
}
volName := fp.VolumeName(pathStr)
if len(volName) == 0 {
return volNameIndex, volNameLength, volNameStr
}
volNameIndex = strings.Index(pathStr, volName)
volNameLength = len(volName)
if volNameLength > 0 {
volNameStr = volName
}
return volNameIndex, volNameLength, volNameStr
}
// IsAbsolutePath - Compares the input parameter 'pathStr' to
// the absolute path representation for 'pathStr' to determine
// whether 'pathStr' represents an absolute path.
//
func (fh FileHelper) IsAbsolutePath(pathStr string) bool {
errCode := 0
errCode, _, pathStr = fh.isStringEmptyOrBlank(pathStr)
if errCode < 0 {
return false
}
// Adjust the path separators for the current operating
// system.
correctDelimPathStr := strings.ToLower(fh.AdjustPathSlash(pathStr))
absPath, err := fh.MakeAbsolutePath(pathStr)
if err != nil {
return false
}
absPath = strings.ToLower(absPath)
if absPath == correctDelimPathStr {
return true
}
return false
}
// IsPathFileString - Returns 'true' if the it is determined that
// input parameter, 'pathFileStr', represents a directory path,
// file name and optionally, a file extension.
//
// If 'pathFileStr' is judged to be a directory path and file name,
// by definition it cannot be solely a directory path.
//
// ------------------------------------------------------------------------
//
// Input Parameter:
//
// pathFileStr string - The string to be analyzed.
//
// Return Values:
//
// pathFileType PathFileTypeCode - Path File Type Code indicating whether the input parameter 'pathFileStr'
// is a Path, a Path and File, a File or "Indeterminate". "Indeterminate"
// signals that the nature of 'pathFileStr' cannot be classified as either
// a Path or a Path and File or a File.
//
// --------------------------------------------------------
// PathFileTypeCodes
// 0 = None
// 1 = Path
// 2 = PathFile
// 3 = File (with no path)
// 4 = Volume
// 5 = Indeterminate - Cannot determine whether string is a Path,
// Path & File or File
//
//
// err error - If an error is encountered during processing, it is returned here. If no error
// occurs, 'err' is set to 'nil'. An error will be triggered if the input parameter
// 'pathFileStr' cannot no alpa numeric characters.
//
func (fh FileHelper) IsPathFileString(
pathFileStr string) (pathFileType PathFileTypeCode,
absolutePathFile string,
err error) {
ePrefix := "FileHelper.IsPathFileString() "
pathFileType = PathFileType.None()
absolutePathFile = ""
err = nil
var pathFileDoesExist bool
var fInfo FileInfoPlus
var correctedPathFileStr string
correctedPathFileStr,
pathFileDoesExist,
fInfo,
err = fh.doesPathFileExist(pathFileStr,
PreProcPathCode.PathSeparator(), // Convert Path Separators to os default Path Separators
ePrefix,
"pathFileStr")
if err != nil {
return pathFileType, absolutePathFile, err
}
if strings.Contains(correctedPathFileStr, "...") {
pathFileType = PathFileType.None()
absolutePathFile = ""
err = fmt.Errorf(ePrefix+
"Error: INVALID PATH STRING!\n"+
"pathFileStr='%v'\n", correctedPathFileStr)
return pathFileType, absolutePathFile, err
}
osPathSepStr := string(os.PathSeparator)
if strings.Contains(correctedPathFileStr, osPathSepStr+osPathSepStr) {
pathFileType = PathFileType.None()
absolutePathFile = ""
err = fmt.Errorf(ePrefix+
"Error: Invalid Path File string.\n"+
"Path File string contains invalid Path Separators.\n"+
"pathFileStr='%v'\n",
correctedPathFileStr)
return pathFileType, absolutePathFile, err
}
testAbsPathFileStr, err2 := fh.MakeAbsolutePath(correctedPathFileStr)
if err2 != nil {
err = fmt.Errorf("Error converting pathFileStr to absolute path.\n"+
"pathFileStr='%v'\nError='%v'\n",
correctedPathFileStr, err2.Error())
return pathFileType, absolutePathFile, err
}
volName := fp.VolumeName(testAbsPathFileStr)
if strings.ToLower(volName) == strings.ToLower(testAbsPathFileStr) ||
strings.ToLower(volName) == strings.ToLower(pathFileStr) {
// This is a volume name not a file Name!
pathFileType = PathFileType.Volume()
absolutePathFile = volName
err = nil
return pathFileType, absolutePathFile, err
}
// See if path actually exists on disk and
// then examine the File Info object returned.
if pathFileDoesExist {
if fInfo.IsDir() {
pathFileType = PathFileType.Path()
absolutePathFile = testAbsPathFileStr
err = nil
} else {
pathFileType = PathFileType.PathFile()
absolutePathFile = testAbsPathFileStr
err = nil
}
return pathFileType, absolutePathFile, err
} // End of if pathFileDoesExist
// Ok - We know the testPathFileStr does NOT exist on disk
firstCharIdx, lastCharIdx, err2 :=
fh.GetFirstLastNonSeparatorCharIndexInPathStr(correctedPathFileStr)
if err2 != nil {
pathFileType = PathFileType.None()
absolutePathFile = ""
err = fmt.Errorf(ePrefix+
"Error returned from fh.GetFirstLastNonSeparatorCharIndexInPathStr"+
"(correctedPathFileStr)\n"+
"correctedPathFileStr='%v'\nError='%v'\n",
correctedPathFileStr, err2.Error())
return pathFileType, absolutePathFile, err
}
interiorDotPathIdx := strings.LastIndex(correctedPathFileStr, "."+string(os.PathSeparator))
if interiorDotPathIdx > firstCharIdx {
pathFileType = PathFileType.None()
absolutePathFile = ""
err = fmt.Errorf(ePrefix+
"Error: INVALID PATH. Invalid interior relative path detected!\n"+
"correctedPathFileStr='%v'\n",
correctedPathFileStr)
return pathFileType, absolutePathFile, err
}
slashIdxs, err2 := fh.GetPathSeparatorIndexesInPathStr(correctedPathFileStr)
if err2 != nil {
pathFileType = PathFileType.None()
absolutePathFile = ""
err = fmt.Errorf(ePrefix+
"fh.GetPathSeparatorIndexesInPathStr(correctedPathFileStr) returned error.\n"+
"testAbsPathFileStr='%v'\nError='%v'\n",
correctedPathFileStr, err2.Error())
return pathFileType, absolutePathFile, err
}
dotIdxs, err2 := fh.GetDotSeparatorIndexesInPathStr(correctedPathFileStr)
if err2 != nil {
pathFileType = PathFileType.None()
absolutePathFile = ""
err = fmt.Errorf(ePrefix+
"fh.GetDotSeparatorIndexesInPathStr(correctedPathFileStr) retured error.\n"+
"correctedPathFileStr='%v'\nError='%v'\n",
correctedPathFileStr, err2.Error())
return pathFileType, absolutePathFile, err
}
lDotIdxs := len(dotIdxs)
lSlashIdxs := len(slashIdxs)
if lDotIdxs == 0 && lSlashIdxs == 0 && lastCharIdx == -1 {
// Option # 1
// There are no valid characters in the string
pathFileType = PathFileType.None()
absolutePathFile = ""
err = fmt.Errorf(ePrefix+
"No valid characters in parameter 'pathFileStr'\n"+
"pathFileStr='%v'\n", correctedPathFileStr)
} else if lDotIdxs == 0 && lSlashIdxs == 0 && lastCharIdx > -1 {
// Option # 2
// String consists only of eligible alphanumeric characters
// "sometextstring"
// the string has no dots and no path separators.
absolutePathFile = testAbsPathFileStr
// Call it a file!
// Example: "somefilename"
pathFileType = PathFileType.File()
err = nil
} else if lDotIdxs == 0 && lSlashIdxs > 0 && lastCharIdx == -1 {
// Option # 3
// There no dots no characters but string does contain
// slashes
if lSlashIdxs > 1 {
pathFileType = PathFileType.None()
absolutePathFile = ""
err = fmt.Errorf(ePrefix+
"Invalid parameter 'pathFileStr'!\n"+
"'pathFileStr' consists entirely of path separators!\n"+
"pathFileStr='%v'\n",
correctedPathFileStr)
} else {
// lSlashIdxs must be '1'
absolutePathFile = testAbsPathFileStr
// Call it a Directory!
// Example: "/"
pathFileType = PathFileType.Path()
err = nil
}
} else if lDotIdxs == 0 && lSlashIdxs > 0 && lastCharIdx > -1 {
// Option # 4
// strings contains slashes and characters but no dots.
absolutePathFile = testAbsPathFileStr
if lastCharIdx > slashIdxs[lSlashIdxs-1] {
// Example D:\dir1\dir2\xray
// It could be a file or a path. We simply
// can't tell.
pathFileType = PathFileType.Indeterminate()
err = nil
} else {
// Call it a Directory!
// Example: "D:\dir1\dir2\"
pathFileType = PathFileType.Path()
err = nil
}
} else if lDotIdxs > 0 && lSlashIdxs == 0 && lastCharIdx == -1 {
// Option # 5
// dots only. Must be "." or ".."
absolutePathFile = testAbsPathFileStr
// Call it a Directory!
// Example: "D:\dir1\dir2\"
pathFileType = PathFileType.Path()
err = nil
} else if lDotIdxs > 0 && lSlashIdxs == 0 && lastCharIdx > -1 {
// Option # 6
// Dots and characters only. No slashes.
// Maybe 'fileName.ext'
absolutePathFile = testAbsPathFileStr
// Call it a file!
// Example: "somefilename"
pathFileType = PathFileType.File()
err = nil
} else if lDotIdxs > 0 && lSlashIdxs > 0 && lastCharIdx == -1 {
// Option # 7
// Dots and slashes, but no characters.
absolutePathFile = testAbsPathFileStr
// Call it a Directory!
// Example: ".\"
pathFileType = PathFileType.Path()
err = nil
} else {
// Option # 8
// Must be else if lDotIdxs > 0 && lSlashIdxs > 0 && lastCharIdx > -1
// Contains dots slashes and characters
absolutePathFile = testAbsPathFileStr
// If there is a dot after the last path separator
// and there is a character following the dot.
// Therefore, this is a filename extension, NOT a directory
if dotIdxs[lDotIdxs-1] > slashIdxs[lSlashIdxs-1] &&
dotIdxs[lDotIdxs-1] < lastCharIdx {
// Call it a path/file!
// Example: "D:\dir1\dir2\somefilename.txt"
pathFileType = PathFileType.PathFile()
err = nil
} else if lastCharIdx > slashIdxs[lSlashIdxs-1] &&
dotIdxs[lDotIdxs-1] < slashIdxs[lSlashIdxs-1] {
// Example: "..\dir1\dir2\sometext"
// Could be a file could be a directory
// Cannot determine.
pathFileType = PathFileType.Indeterminate()
err = nil
} else {
// Call it a Directory!
// Example: "D:\dir1\dir2\"
pathFileType = PathFileType.Path()
err = nil
}
}
return pathFileType, absolutePathFile, err
}
// IsPathString - Attempts to determine whether a string is a
// path string designating a directory (and not a path file name
// file extension string).
//
// If the path exists on disk, this method will examine the
// associated file information and render a definitive and
// accurate determination as to whether the path string represents
// a directory.
//
// ------------------------------------------------------------------------
//
// Input Parameter:
//
// pathStr string - The path string to be analyzed.
//
// ------------------------------------------------------------------------
//
// Return Values:
//
// isPathStr bool - If the input parameter, 'pathStr'
// is determined to be a directory
// path, this return value is set to
// true. Here, a 'directory path' is defined
// as a true directory and the path does NOT
// contain a file name.
//
// cannotDetermine bool - If the method cannot determine whether
// the input parameter 'pathStr' is or
// is NOT a valid directory path, this
// this return value will be set to 'true'.
// The 'cannotDetermine=true' condition occurs
// with path names like 'D:\DirA\common'. The
// cannot determine whether 'common' is a file
// name or a directory name.
//
//
// testPathStr string - Input parameter 'pathStr' is subjected to cleaning routines
// designed to exclude extraneous characters from the analysis.
// 'testPathFileStr' is the actual string on which the analysis was
// performed.
//
// err error - If an error occurs this return value will
// be populated. If no errors occur, this return
// value is set to nil.
//
//
func (fh FileHelper) IsPathString(
pathStr string) (isPathStr bool, cannotDetermine bool, testPathStr string, err error) {
ePrefix := "FileHelper.IsPathString() "
testPathStr = ""
isPathStr = false
cannotDetermine = false
err = nil
errCode := 0
errCode, _, pathStr = fh.isStringEmptyOrBlank(pathStr)
if errCode == -1 {
err =
errors.New(ePrefix +
"Error: Input parameter 'pathStr' is an empty string!\n")
return isPathStr, cannotDetermine, testPathStr, err
}
if errCode == -2 {
err =
errors.New(ePrefix +
"Error: Input parameter 'pathStr' consists of blank spaces!\n")
return isPathStr, cannotDetermine, testPathStr, err
}
if strings.Contains(pathStr, "...") {
err = fmt.Errorf(ePrefix+
"Error: INVALID PATH STRING!\n"+
"pathStr='%v'\n", pathStr)
return isPathStr, cannotDetermine, testPathStr, err
}
testPathStr = fh.AdjustPathSlash(pathStr)
pathFileType, _, err2 := fh.IsPathFileString(testPathStr)
if err2 != nil {
err = fmt.Errorf(ePrefix+"%v\n", err2.Error())
return isPathStr, cannotDetermine, testPathStr, err
}
if pathFileType == PathFileType.Path() {
isPathStr = true
cannotDetermine = false
err = nil
return isPathStr, cannotDetermine, testPathStr, err
}
if pathFileType == PathFileType.Indeterminate() {
isPathStr = false
cannotDetermine = true
err = nil
return isPathStr, cannotDetermine, testPathStr, err
}
isPathStr = false
cannotDetermine = false
err = nil
return isPathStr, cannotDetermine, testPathStr, err
}
// JoinPathsAdjustSeparators - Joins two
// path strings and standardizes the
// path separators according to the
// current operating system.
func (fh FileHelper) JoinPathsAdjustSeparators(
p1 string, p2 string) string {
errCode := 0
errCode, _, p1 = fh.isStringEmptyOrBlank(p1)
if errCode < 0 {
p1 = ""
}
errCode, _, p2 = fh.isStringEmptyOrBlank(p2)
if errCode < 0 {
p2 = ""
}
if p1 == "" &&
p2 == "" {
return ""
}
ps1 := fh.AdjustPathSlash(fp.Clean(p1))
ps2 := fh.AdjustPathSlash(fp.Clean(p2))
return fp.Clean(fh.AdjustPathSlash(path.Join(ps1, ps2)))
}
// JoinPaths - correctly joins 2-paths. Like the method JoinPathsAdjustSeparators()
// this method also converts path separators to the correct path separators for
// the current operating system.
//
func (fh FileHelper) JoinPaths(p1 string, p2 string) string {
return fh.JoinPathsAdjustSeparators(p1, p2)
}
// MakeAbsolutePath - Supply a relative path or any path
// string and resolve that path to an Absolute path.
// Note: Clean() is called on result by fp.Abs().
func (fh FileHelper) MakeAbsolutePath(relPath string) (string, error) {
ePrefix := "FileHelper.MakeAbsolutePath() "
errCode := 0
errCode, _, relPath = fh.isStringEmptyOrBlank(relPath)
if errCode == -1 {
return "",
errors.New(ePrefix +
"Error: Input parameter 'relPath' is an empty string!\n")
}
if errCode == -2 {
return "",
errors.New(ePrefix +
"Error: Input parameter 'relPath' consists of blank spaces!\n")
}
testRelPath := fh.AdjustPathSlash(relPath)
errCode, _, testRelPath = fh.isStringEmptyOrBlank(testRelPath)
if errCode < 0 {
return "", errors.New(ePrefix +
"Error: Input Parameter 'relPath' adjusted for path Separators is an EMPTY string!\n")
}
p, err := fp.Abs(testRelPath)
if err != nil {
return "", fmt.Errorf(ePrefix+
"Error returned from fp.Abs(testRelPath).\n"+
"testRelPath='%v'\nError='%v'\n",
testRelPath, err.Error())
}
return p, nil
}
// MakeDirAll - creates a directory named path, along with any necessary
// parent directories. In other words, all directories in the path are
// created.
//
// The permission bits 'drwxrwxrwx' are used for all directories that the
// method creates.
//
// If path is a directory which already exists, this method does nothing
// and returns and error value of 'nil'.
//
// Note that this method calls FileHelper.MakeDirAllPerm()
//
func (fh FileHelper) MakeDirAll(dirPath string) error {
ePrefix := "FileHelper.MakeDirAll() "
permission, err := FilePermissionConfig{}.New("drwxrwxrwx")
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
err = fh.MakeDirAllPerm(dirPath, permission)
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
return nil
}
// MakeDir - Creates a single directory. The method returns an error
// type. If the operation succeeds, the error value is 'nil'. If the
// operation fails the error value is populated with an appropriate
// error message.
//
// This method will fail if the parent directory does not exist.
//
// The permission bits 'drwxrwxrwx' are used for directory creation.
// If path is already a directory, this method does nothing and returns
// an error value of 'nil'.
//
// Note that this method calls FileHelper.MakeDirPerm().
//
func (fh FileHelper) MakeDir(dirPath string) error {
ePrefix := "FileHelper.MakeDir() "
permission, err := FilePermissionConfig{}.New("drwxrwxrwx")
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
err = fh.MakeDirPerm(dirPath, permission)
if err != nil {
return fmt.Errorf(ePrefix+"%v\n", err.Error())
}
return nil
}
// MakeDirAllPerm - Creates a directory path along with any necessary
// parent paths.
//
// If the target directory path already exists, this method does nothing
// and returns.
//
// The input parameter 'permission' is of type 'FilePermissionConfig'.
// See method the documentation for method 'FilePermissionConfig.New()'
// for an explanation of permission codes.
//
// If you wish to grant total access to a directory, consider setting
// permission code as follows:
// FilePermissionConfig{}.New("drwxrwxrwx")
//
// If the parent directories in parameter 'dirPath' do not yet exist, this
// method will create them.
//
func (fh FileHelper) MakeDirAllPerm(dirPath string, permission FilePermissionConfig) error {
ePrefix := "FileHelper.MakeDirAllPerm() "
errCode := 0
errCode, _, dirPath = fh.isStringEmptyOrBlank(dirPath)
if errCode == -1 {
return errors.New(ePrefix +
"Error: Input parameter 'dirPath' is an empty string!\n")
}
if errCode == -2 {
return errors.New(ePrefix +
"Error: Input parameter 'dirPath' consists of blank spaces!\n")
}
err2 := permission.IsValid()
if err2 != nil {
return fmt.Errorf(ePrefix+"Input parameter 'permission' is INVALID!\n"+
"Error='%v'\n", err2.Error())
}
dirPermCode, err2 := permission.GetCompositePermissionMode()
if err2 != nil {
return fmt.Errorf(ePrefix+
"ERROR: INVALID Permission Code\n"+
"Error='%v'\n", err2.Error())
}
dirPath, err2 = fh.MakeAbsolutePath(dirPath)
if err2 != nil {
return fmt.Errorf(ePrefix+
"Error returned by fh.MakeAbsolutePath(dirPath).\n"+
"dirPath='%v'\nError='%v'\n",
dirPath, err2.Error())
}
err2 = os.MkdirAll(dirPath, dirPermCode)
if err2 != nil {
return fmt.Errorf(ePrefix+
"Error return from os.MkdirAll(dirPath, permission).\n"+
"dirPath='%v'\nError='%v'\n",
dirPath, err2.Error())
}
var pathDoesExist bool
_,
pathDoesExist,
_,
err2 = fh.doesPathFileExist(dirPath,
PreProcPathCode.None(), // Take no Pre-Processing Action
ePrefix,
"dirPath")
if err2 != nil {
return err2
}
if !pathDoesExist {
return fmt.Errorf(ePrefix+
"Error: Directory creation FAILED!. New Directory Path DOES NOT EXIST!\n"+
"dirPath='%v'\n", dirPath)
}
return nil
}
// MakeDirPerm - Creates a single directory using the permission codes passed by input
// parameter 'permission'.
//
// This method will fail if the parent directory does not exist. To create all parent
// directories in the path use method 'FileHelper.MakeDirAllPerm()'.
//
//
// The input parameter 'permission' is of type 'FilePermissionConfig'.
// See method the documentation for method 'FilePermissionConfig.New()'
// for an explanation of permission codes.
//
// If you wish to grant total access to a directory, consider setting
// permission code as follows:
// FilePermissionConfig{}.New("drwxrwxrwx")
//
// An error will be triggered if the 'dirPath' input parameter represents
// an invalid path or if parent directories in the path do not exist.
//
func (fh FileHelper) MakeDirPerm(dirPath string, permission FilePermissionConfig) error {
ePrefix := "FileHelper.MakeDirPerm() "
errCode := 0
errCode, _, dirPath = fh.isStringEmptyOrBlank(dirPath)
if errCode == -1 {
return errors.New(ePrefix +
"Error: Input parameter 'dirPath' is an empty string!\n")
}
if errCode == -2 {
return errors.New(ePrefix +
"Error: Input parameter 'dirPath' consists of blank spaces!\n")
}
err2 := permission.IsValid()
if err2 != nil {
return fmt.Errorf(ePrefix+
"Input parameter 'permission' is INVALID!\n"+
"Error='%v'\n", err2.Error())
}
dirPermCode, err2 := permission.GetCompositePermissionMode()
if err2 != nil {
return fmt.Errorf(ePrefix+
"ERROR: INVALID Permission Code\n"+
"Error='%v'\n", err2.Error())
}
dirPath, err2 = fh.MakeAbsolutePath(dirPath)
if err2 != nil {
return fmt.Errorf(ePrefix+
"Error returned by fh.MakeAbsolutePath(dirPath).\n"+
"dirPath='%v'\nError='%v'\n", dirPath, err2.Error())
}
err2 = os.Mkdir(dirPath, dirPermCode)
if err2 != nil {
return fmt.Errorf(ePrefix+
"Error return from os.Mkdir(dirPath, dirPermCode).\n"+
"dirPath='%v'\nError='%v'\n",
dirPath, err2.Error())
}
var pathDoesExist bool
_,
pathDoesExist,
_,
err2 = fh.doesPathFileExist(dirPath,
PreProcPathCode.None(), // Take no Pre-Processing action
ePrefix,
"dirPath")
if err2 != nil {
return err2
}
if !pathDoesExist {
return fmt.Errorf(ePrefix+
"Error: Directory creation FAILED!. New Directory Path DOES NOT EXIST!\n"+
"dirPath='%v'\n", dirPath)
}
return nil
}
// MoveFile - Copies file from source to destination and, if successful,
// then deletes the original source file.
//
// The copy procedure will carried out using the the 'Copy By Io' technique.
// See FileHelper.CopyFileByIo().
//
// The 'move' operation will create the destination file, but it will NOT
// create the destination directory. If the destination directory does NOT
// exist, an error will be returned.
//
// If this copy operation fails, the method will return an error and it
// will NOT delete the source file.
//
// If an error is encountered during this procedure it will be returned by
// means of the return parameter 'err'.
//
func (fh FileHelper) MoveFile(src, dst string) error {
ePrefix := "FileHelper.MoveFile() "
var err error
var srcFileDoesExist, dstFileDoesExist bool
var srcFInfo, dstFInfo FileInfoPlus
src,
srcFileDoesExist,
srcFInfo,
err = fh.doesPathFileExist(src,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"src")
if err != nil {
return err
}
if !srcFileDoesExist {
return fmt.Errorf(ePrefix+
"Error: Input parameter "+
"'src' file DOES NOT EXIST!\n"+
"src='%v'\n", src)
}
if srcFInfo.IsDir() {
return fmt.Errorf(ePrefix+
"Error: Input parameter 'src' "+
"exists and it is directory NOT a file!\n"+
"src='%v'\n", src)
}
dst,
dstFileDoesExist,
dstFInfo,
err = fh.doesPathFileExist(dst,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"dst")
if err != nil {
return err
}
if dstFileDoesExist && dstFInfo.IsDir() {
return fmt.Errorf(ePrefix+"Error: Input parameter 'dst' does exist,\n"+
"but it a 'directory' and NOT a File!\n"+
"dst='%v'\n", dst)
}
// ============================
// Perform the copy operation!
// Use Copy By IO Procedure
// ============================
err = fh.CopyFileByIo(src, dst)
if err != nil {
// Copy Operation Failed. Return an error
// and DO NOT delete the source file!
return fmt.Errorf(ePrefix+
"Error: Copy operation FAILED!\n"+
"Source File='%v'\n"+
"Destination File='%v'\nError='%v'\n",
src, dst, err.Error())
}
// CopyFileByIo operation was apparently successful.
// Now, verify that destination file exists.
_,
dstFileDoesExist,
_,
err = fh.doesPathFileExist(dst,
PreProcPathCode.None(), // Take no Pre-Processing action
ePrefix,
"dst")
if err != nil {
return err
}
if !dstFileDoesExist {
return fmt.Errorf(ePrefix+
"Error: After Copy Operation, destination file "+
"DOES NOT EXIST!\n"+
"Therefore, the copy operation FAILED! Source file was NOT deleted.\n"+
"destination file='%v'\n", dst)
}
// Successful copy operation has been verified.
// Time to delete the source file.
err = os.Remove(src)
if err != nil {
return fmt.Errorf(ePrefix+
"Copy operation succeeded, but attempted deletion of source file FAILED!\n"+
"Source File='%v'\n", src)
}
_,
srcFileDoesExist,
_,
err = fh.doesPathFileExist(src,
PreProcPathCode.None(), // Take No Pre-Processing Action
ePrefix,
"src")
if err != nil {
return err
}
if srcFileDoesExist {
return fmt.Errorf("Verification Error: File 'src' still exists!\n"+
"src='%v'\n", src)
}
// Success, source was copied to destination
// AND the source file was deleted.
// Done and we are out of here!
return nil
}
// OpenDirectory - Opens a directory and returns the associated 'os.File' pointer.
// This method will open a directory designated by input parameter, 'directoryPath'.
//
// The input parameter 'createDir' determines the action taken if 'directoryPath'
// does not exist. If 'createDir' is set to 'true' and 'directoryPath' does not
// currently exist, this method will attempt to create 'directoryPath'. Directories
// created in this manner are configured with Open Type of 'Read-Write' and a
// Permission code of 'drwxrwxrwx'.
//
// Alternatively, if 'createDir' is set to 'false' and 'directoryPath' does NOT exist,
// an error will be returned.
//
// Regardless of whether the target directory path already exists or is created by
// this method, the returned os.File pointer is opened with the 'Read-Only' attribute
// (O_RDONLY) and a permission code of zero ("----------").
//
// Note: The caller is responsible for calling "Close()" on the returned os.File pointer.
//
// --------------------------------------------------------------------------------------------------------
//
// Input Parameters:
//
//
// directoryPath string - A string containing the path name of the directory
// which will be opened.
//
//
// createDir bool - Determines what action will be taken if 'directoryPath'
// does NOT exist. If 'createDir' is set to 'true' and
// 'directoryPath' does NOT exist, this method will attempt
// to create 'directoryPath'. Alternatively, if 'createDir'
// is set to false and 'directoryPath' does NOT exist, this
// method will terminate and an error will be returned.
//
// Directories created in this manner will have an Open Type
// of 'Read-Write' and a Permission code of 'drwxrwxrwx'. This
// differs from the Open Type and permission mode represented
// by the returned os.File pointer.
//
// --------------------------------------------------------------------------------------------------------
//
// Return Values:
//
// *os.File - If successful, this method returns an os.File pointer
// to the directory designated by input parameter 'directoryPath'.
//
// If successful, the returned os.File pointer is opened with the
// 'Read-Only' attribute (O_RDONLY) and a permission code of zero
// ("----------").
//
// If this method fails, the *os.File return value is 'nil'.
//
// Note: The caller is responsible for calling "Close()" on this
// os.File pointer.
//
//
// error - If the method completes successfully, the error return value
// is 'nil'. If the method fails, the error type returned is
// populated with an appropriate error message.
//
func (fh FileHelper) OpenDirectory(
directoryPath string,
createDir bool) (*os.File, error) {
ePrefix := "FileHelper.OpenDirectory() "
var err error
var directoryPathDoesExist bool
var dirPathFInfo FileInfoPlus
directoryPath,
directoryPathDoesExist,
dirPathFInfo,
err = fh.doesPathFileExist(directoryPath,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"directoryPath")
if err != nil {
return nil, err
}
if directoryPathDoesExist &&
!dirPathFInfo.IsDir() {
return nil,
fmt.Errorf(ePrefix+
"ERROR: 'directoryPath' does exist, but\n"+
"IT IS NOT A DIRECTORY!\n"+
"directoryPath='%v'\n", directoryPath)
}
if directoryPathDoesExist && dirPathFInfo.Mode().IsRegular() {
return nil,
fmt.Errorf(ePrefix+
"ERROR: 'directoryPath' does exist, but\n"+
"it is classifed as a REGULAR File!\n"+
"directoryPath='%v'\n", directoryPath)
}
if !directoryPathDoesExist {
if !createDir {
return nil,
fmt.Errorf(ePrefix+"Error 'directoryPath' DOES NOT EXIST!\n"+
"directoryPath='%v'\n", directoryPath)
}
// Parameter 'createDir' must be 'true'.
// The error signaled that the path does not exist. So, create the directory path
err = fh.MakeDirAll(directoryPath)
if err != nil {
return nil,
fmt.Errorf(ePrefix+"ERROR: Attmpted creation of 'directoryPath' FAILED!\n"+
"directoryPath='%v'\nError='%v'\n", directoryPath, err.Error())
}
// Verify that the directory exists and get
// the associated file info object.
_,
directoryPathDoesExist,
dirPathFInfo,
err = fh.doesPathFileExist(directoryPath,
PreProcPathCode.None(), // Take No Pre-Processing Action
ePrefix,
"directoryPath")
if err != nil {
return nil, fmt.Errorf(ePrefix+"Error occurred verifying existance of "+
"newly created 'directoryPath'!\n"+
"Non-Path error returned by os.Stat(directoryPath)\ndirectoryPath='%v'\nError='%v'\n",
directoryPath, err.Error())
}
if !directoryPathDoesExist {
return nil, fmt.Errorf(ePrefix+"Error: Verification of newly created "+
"directoryPath FAILED!\n"+
"'directoryPath' DOES NOT EXIST!\n"+
"directoryPath='%v'\n", directoryPath)
}
if !dirPathFInfo.IsDir() {
return nil,
fmt.Errorf(ePrefix+"ERROR: Input Paramter 'directoryPath' is NOT a directory!\n"+
"directoryPath='%v'\n", directoryPath)
}
if dirPathFInfo.Mode().IsRegular() {
return nil,
fmt.Errorf(ePrefix+
"ERROR: 'directoryPath' does exist, but\n"+
"it is classifed as a REGULAR File!\n"+
"directoryPath='%v'\n", directoryPath)
}
}
filePtr, err := os.Open(directoryPath)
if err != nil {
return nil,
fmt.Errorf(ePrefix+"File Open Error: %v\n"+
"directoryPath='%v'\n",
err.Error(), directoryPath)
}
if filePtr == nil {
return nil, errors.New(ePrefix +
"ERROR: os.OpenFile() returned a 'nil' file pointer!\n")
}
return filePtr, nil
}
// OpenFile - wrapper for os.OpenFile. This method may be used to open or
// create files depending on the File Open and File Permission parameters.
//
// If successful, this method will return a pointer to the os.File object
// associated with the file designated for opening.
//
// The calling routine is responsible for calling "Close()" on this os.File
// pointer.
//
// ------------------------------------------------------------------------
//
// Input Parameters:
//
// pathFileName string - A string containing the path and file name
// of the file which will be opened. If a parent
// path component does NOT exist, this method will
// trigger an error.
//
// fileOpenCfg FileOpenConfig - This parameter encapsulates the File Open parameters
// which will be used to open subject file. For an
// explanation of File Open parameters, see method
// FileOpenConfig.New().
//
// filePermissionCfg FilePermissionConfig - This parameter encapsulates the File Permission
// parameters which will be used to open the subject
// file. For an explanation of File Permission parameters,
// see method FilePermissionConfig.New().
//
//
// ------------------------------------------------------------------------
//
// Return Values:
//
// *os.File - If successful, this method returns an os.File pointer
// to the file designated by input parameter 'pathFileName'.
// This file pointer can subsequently be used for reading
// content from the subject file. It may NOT be used for
// writing content to the subject file.
//
// If this method fails, the *os.File return value is 'nil'.
//
// Note: The caller is responsible for calling "Close()" on this
// os.File pointer.
//
//
// error - If the method completes successfully, this return value
// is 'nil'. If the method fails, the error type returned
// is populated with an appropriate error message.
//
func (fh FileHelper) OpenFile(
pathFileName string,
fileOpenCfg FileOpenConfig,
filePermissionCfg FilePermissionConfig) (filePtr *os.File, err error) {
filePtr = nil
err = nil
ePrefix := "FileHelper.OpenFile() "
var pathFileNameDoesExist bool
var fInfoPlus FileInfoPlus
pathFileName,
pathFileNameDoesExist,
fInfoPlus,
err = fh.doesPathFileExist(
pathFileName,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"pathFileName")
if err != nil {
return nil, err
}
if !pathFileNameDoesExist {
err = fmt.Errorf(ePrefix+
"ERROR: Input parameter 'pathFileName' DOES NOT EXIST!\n"+
"pathFileName='%v'\n", pathFileName)
return filePtr, err
}
if fInfoPlus.IsDir() {
err =
fmt.Errorf(ePrefix+
"ERROR: Input parameter 'pathFileName' is "+
"a 'Directory' - NOT a file!\n"+
"pathFileName='%v'\n", pathFileName)
return filePtr, err
}
err2 := fileOpenCfg.IsValid()
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Input Parameter 'fileOpenCfg' is INVALID!\n"+
"Error='%v'\n", err2.Error())
return filePtr, err
}
fOpenCode, err2 := fileOpenCfg.GetCompositeFileOpenCode()
if err2 != nil {
err = fmt.Errorf(ePrefix+"%v\n", err2.Error())
return filePtr, err
}
err2 = filePermissionCfg.IsValid()
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Input Parameter 'filePermissionCfg' is INVALID!\n"+
"Error='%v'\n", err2.Error())
return filePtr, err
}
fileMode, err2 := filePermissionCfg.GetCompositePermissionMode()
if err2 != nil {
err = fmt.Errorf(ePrefix+"%v\n", err2.Error())
return filePtr, err
}
filePtr, err2 = os.OpenFile(pathFileName, fOpenCode, fileMode)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned by os.OpenFile(pathFileName, fOpenCode, fileMode).\n"+
"pathFileName='%v'\nError='%v'\n", pathFileName, err2.Error())
return filePtr, err
}
if filePtr == nil {
err = errors.New(ePrefix +
"ERROR: os.OpenFile() returned a 'nil' file pointer!\n")
return filePtr, err
}
err = nil
return filePtr, err
}
// OpenFileReadOnly - Opens the designated path file name for reading
// only.
//
// If successful, this method returns a pointer of type *os.File which
// can only be used for reading reading content from the subject file.
// This file pointer is configured for 'Read-Only' operations. You may
// not write to the subject file using this pointer.
//
// If the designated file ('pathFileName') does NOT exist, an error
// will be triggered.
//
// ------------------------------------------------------------------------
//
// Input Parameter:
//
// pathFileName string - A string containing the path and file name
// of the file which will be opened in the
// 'Read-Only' mode. If the path or file does
// NOT exist, this method will trigger an error.
//
// ------------------------------------------------------------------------
//
// Return Values:
//
// *os.File - If successful, this method returns an os.File pointer
// to the file designated by input parameter 'pathFileName'.
// This file pointer can subsequently be used for reading
// content from the subject file. It may NOT be used for
// writing content to the subject file.
//
// If this method fails, the *os.File return value is 'nil'.
//
// Note: The caller is responsible for calling "Close()" on this
// os.File pointer.
//
//
// error - If the method completes successfully, this return value
// is 'nil'. If the method fails, the error type returned
// is populated with an appropriate error message.
//
func (fh FileHelper) OpenFileReadOnly(pathFileName string) (filePtr *os.File, err error) {
ePrefix := "FileHelper.OpenFileReadOnly() "
filePtr = nil
err = nil
var err2 error
var pathFileNameDoesExist bool
var fInfoPlus FileInfoPlus
pathFileName,
pathFileNameDoesExist,
fInfoPlus,
err = fh.doesPathFileExist(
pathFileName,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"pathFileName")
if err != nil {
return filePtr, err
}
if !pathFileNameDoesExist {
err = fmt.Errorf(ePrefix+
"ERROR: The input parameter 'pathFileName' DOES NOT EXIST!\n"+
"pathFileName='%v'\n", pathFileName)
return filePtr, err
}
if fInfoPlus.IsDir() {
err = fmt.Errorf(ePrefix+
"ERROR: The input parameter 'pathFileName' is a 'Directory' "+
"and NOT a path file name.\n"+
"'pathFileName' is therefore INVALID!\n"+
"pathFileName='%v'\n", pathFileName)
return filePtr, err
}
fileOpenCfg, err2 := FileOpenConfig{}.New(FOpenType.TypeReadOnly(),
FOpenMode.ModeNone())
if err2 != nil {
err =
fmt.Errorf(ePrefix+
"Error returned by FileOpenConfig{}.New(FOpenType.TypeReadOnly(),"+
"FOpenMode.ModeNone()).\n"+
"Error='%v'\n",
err2.Error())
return filePtr, err
}
fOpenCode, err2 := fileOpenCfg.GetCompositeFileOpenCode()
if err2 != nil {
err = fmt.Errorf(ePrefix+"Error Creating File Open Code.\n"+
"Error=%v\n",
err2.Error())
return filePtr, err
}
fPermCfg, err2 := FilePermissionConfig{}.New("-r--r--r--")
if err2 != nil {
err =
fmt.Errorf(ePrefix+
"Error returned by FilePermissionConfig{}.New(\"-r--r--r--\")\n"+
"Error='%v'\n", err2.Error())
return filePtr, err
}
fileMode, err2 := fPermCfg.GetCompositePermissionMode()
if err2 != nil {
err = fmt.Errorf(ePrefix+"Error Creating File Mode Code.\n"+
"Error=%v\n",
err2.Error())
return filePtr, err
}
filePtr, err2 = os.OpenFile(pathFileName, fOpenCode, fileMode)
if err2 != nil {
err = fmt.Errorf(ePrefix+"File Open Error: %v\n"+
"pathFileName='%v'", err2.Error(), pathFileName)
filePtr = nil
return filePtr, err
}
if filePtr == nil {
err = fmt.Errorf(ePrefix +
"ERROR: os.OpenFile() returned a 'nil' file pointer!\n")
return filePtr, err
}
err = nil
return filePtr, err
}
// OpenFileReadWrite - Opens the file designated by input parameter
// 'fileName' for 'Writing'. The actual permission code used to open
// the file is 'Read/Write'.
//
// If the method is successful, a pointer to the opened file is returned
// along with an error value of 'nil'.
//
// If the file does not exist, this method will attempt to create it.
//
// If the file path does not exist, an error will be triggered.
//
// If the method completes successfully, the caller is responsible for
// call "Close()" on the returned os.File pointer.
//
// ------------------------------------------------------------------------
//
// Input Parameter:
//
// pathFileName string - A string containing the path and file name
// of the file which will be opened in the
// 'Read/Write' mode. If the file does NOT
// exist, this method will attempt to create
// it. However, if the path component of
// 'pathFileName' does not exist, an error
// will be returned.
//
// truncateFile bool - If set to 'true' and the target file will
// be truncated to zero bytes in length before
// it is opened.
//
// If set to 'false', the target file will be
// be opened in the 'Append' mode and any bytes
// written to the file will be appended to the
// end of the file. Under this scenario, the
// original file contents are preserved and newly
// written bytes are added to the end of the file.
//
// If the file designated by input parameter 'pathFileName'
// does not exist, this parameter ('truncateFile') is
// ignored and the new created file is initialized
// containing zero bytes.
//
//
// ------------------------------------------------------------------------
//
// Return Values:
//
// *os.File - If successful, this method returns an os.File pointer
// to the file opened for 'Read/Write' operations. This
// file pointer can be used subsequently for writing
// content to, or reading content from, the subject file.
//
// If this method fails, this return value is 'nil'.
//
// Note: The caller is responsible for calling "Close()" on this
// os.File pointer.
//
//
// error - If the method completes successfully, this return value
// is 'nil'. If the method fails, the error type returned
// is populated with an appropriate error message.
//
func (fh FileHelper) OpenFileReadWrite(
pathFileName string,
truncateFile bool) (*os.File, error) {
ePrefix := "FileHelper.OpenFileReadWrite() "
var fPtr *os.File
var err error
var pathFileNameDoesExist bool
var fInfoPlus FileInfoPlus
pathFileName,
pathFileNameDoesExist,
fInfoPlus,
err = fh.doesPathFileExist(
pathFileName,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"pathFileName")
if err != nil {
return nil, err
}
var fileOpenCfg FileOpenConfig
if !pathFileNameDoesExist {
// pathFileName does NOT exist
fileOpenCfg, err = FileOpenConfig{}.New(FOpenType.TypeReadWrite(),
FOpenMode.ModeCreate(), FOpenMode.ModeAppend())
if err != nil {
return nil,
fmt.Errorf(ePrefix+
"Error returned by FileOpenConfig{}.New(FOpenType.TypeWriteOnly(),"+
"FOpenMode.ModeCreate(), FOpenMode.ModeAppend()).\n"+
"Error='%v'\n",
err.Error())
}
} else {
// pathFileName does exist
if fInfoPlus.IsDir() {
return nil,
fmt.Errorf(ePrefix+"ERROR: Input parameter 'pathFileName' is "+
"a 'Directory' NOT a file.\n"+
"pathFileName='%v'\n", pathFileName)
}
if truncateFile {
// truncateFile == true
fileOpenCfg, err = FileOpenConfig{}.New(FOpenType.TypeReadWrite(),
FOpenMode.ModeTruncate())
if err != nil {
return nil,
fmt.Errorf(ePrefix+
"Error returned by FileOpenConfig{}.New(FOpenType.TypeReadWrite(),"+
"FOpenMode.ModeTruncate()).\n"+
"Error='%v'\n",
err.Error())
}
} else {
// truncateFile == false
fileOpenCfg, err = FileOpenConfig{}.New(FOpenType.TypeReadWrite(),
FOpenMode.ModeAppend())
if err != nil {
return nil,
fmt.Errorf(ePrefix+
"Error returned by FileOpenConfig{}.New(FOpenType.TypeReadWrite(),"+
"FOpenMode.ModeAppend()).\n"+
"Error='%v'\n",
err.Error())
}
}
}
fOpenCode, err := fileOpenCfg.GetCompositeFileOpenCode()
if err != nil {
return nil,
fmt.Errorf(ePrefix+"%v", err.Error())
}
fPermCfg, err := FilePermissionConfig{}.New("-rwxrwxrwx")
if err != nil {
return nil,
fmt.Errorf(ePrefix+
"Error returned by FilePermissionConfig{}.New(\"-rwxrwxrwx\")\n"+
"Error='%v'\n", err.Error())
}
fileMode, err := fPermCfg.GetCompositePermissionMode()
if err != nil {
return nil, fmt.Errorf(ePrefix+"%v\n", err.Error())
}
fPtr, err = os.OpenFile(pathFileName, fOpenCode, fileMode)
if err != nil {
return nil, fmt.Errorf(ePrefix+"File Open Error\n"+
"pathFileName='%v'\nError='%v'\n",
pathFileName, err.Error())
}
if fPtr == nil {
return nil, fmt.Errorf(ePrefix+
"ERROR: os.OpenFile() returned a 'nil' file pointer!\n"+
"pathFileName='%v'\n", pathFileName)
}
return fPtr, nil
}
// OpenFileWriteOnly - Opens a file for 'Write-Only' operations. Input parameter
// 'pathFileName' specifies the the path and file name of the file which will be
// opened.
//
// If the path component of 'pathFileName' does not exist, an error will be returned.
//
// If the designated file does not exist, this method will attempt to create the file.
//
// If the method completes successfully, the caller is responsible for calling 'Close()'
// on the returned os.File pointer.
//
// ------------------------------------------------------------------------
//
// Input Parameter:
//
// pathFileName string - A string containing the path and file name
// of the file which will be opened in the
// 'Write Only' mode. If the file does NOT
// exist, this method will attempt to create
// it. However, if the path component of
// 'pathFileName' does not exist, an error
// will be returned.
//
// truncateFile bool - If set to 'true' and the target file will
// be truncated to zero bytes in length before
// it is opened.
//
// If set to 'false', the target file will be
// be opened in the 'Append' mode and any bytes
// written to the file will be appended to the
// end of the file. Under this scenario, the
// original file contents are preserved and newly
// written bytes are added to the end of the file.
//
// If the file designated by input parameter 'pathFileName'
// does not exist, this parameter ('truncateFile') is
// ignored and the newly created file is initialized
// with zero bytes of content.
//
//
// ------------------------------------------------------------------------
//
// Return Values:
//
// *os.File - If successful, this method returns an os.File pointer
// to the file opened for 'Write Only' operations. This
// file pointer can be used for writing content to the
// subject file.
//
// If this method fails, this return value is 'nil'.
//
// Note: The caller is responsible for calling "Close()" on this
// os.File pointer.
//
//
// error - If the method completes successfully, this return value
// is 'nil'. If the method fails, the error type returned
// is populated with an appropriate error message.
//
func (fh FileHelper) OpenFileWriteOnly(
pathFileName string,
truncateFile bool) (*os.File, error) {
ePrefix := "FileHelper.OpenFileWriteOnly() "
var fPtr *os.File
var err error
var pathFileNameDoesExist bool
var fInfoPlus FileInfoPlus
pathFileName,
pathFileNameDoesExist,
fInfoPlus,
err = fh.doesPathFileExist(
pathFileName,
PreProcPathCode.AbsolutePath(), // Convert to Absolute Path
ePrefix,
"pathFileName")
if err != nil {
return nil, err
}
var fileOpenCfg FileOpenConfig
if !pathFileNameDoesExist {
// The pathFileName DOES NOT EXIST!
fileOpenCfg, err = FileOpenConfig{}.New(FOpenType.TypeWriteOnly(),
FOpenMode.ModeCreate(), FOpenMode.ModeAppend())
if err != nil {
return nil,
fmt.Errorf(ePrefix+
"Error returned by FileOpenConfig{}.New(FOpenType.TypeWriteOnly(),"+
"FOpenMode.ModeCreate(), FOpenMode.ModeAppend()).\nError='%v'\n",
err.Error())
}
} else {
// The pathFileName DOES EXIST!
if fInfoPlus.IsDir() {
return nil,
fmt.Errorf(ePrefix+"ERROR: Input parameter 'pathFileName' is "+
"a 'Directory' NOT a file.\n"+
"pathFileName='%v'\n", pathFileName)
}
if truncateFile {
// truncateFile == true; Set Mode 'Truncate'
fileOpenCfg, err = FileOpenConfig{}.New(FOpenType.TypeWriteOnly(),
FOpenMode.ModeTruncate())
if err != nil {
return nil,
fmt.Errorf(ePrefix+
"Error returned by FileOpenConfig{}.New(FOpenType.TypeWriteOnly(),"+
"FOpenMode.ModeTruncate()).\nError='%v'\n",
err.Error())
}
} else {
// truncateFile == false; Set Mode 'Append'
fileOpenCfg, err = FileOpenConfig{}.New(FOpenType.TypeWriteOnly(),
FOpenMode.ModeAppend())
if err != nil {
return nil,
fmt.Errorf(ePrefix+
"Error returned by FileOpenConfig{}.New(FOpenType.TypeWriteOnly(),"+
"FOpenMode.ModeAppend()).\nError='%v'\n",
err.Error())
}
}
}
fOpenCode, err := fileOpenCfg.GetCompositeFileOpenCode()
if err != nil {
return nil,
fmt.Errorf(ePrefix+
"Error creating File Open Code.\nError=%v\n", err.Error())
}
fPermCfg, err := FilePermissionConfig{}.New("--wx-wx-wx")
if err != nil {
return nil,
fmt.Errorf(ePrefix+
"Error returned by FilePermissionConfig{}.New(\"-rwxrwxrwx\")\n"+
"Error='%v' \n", err.Error())
}
fileMode, err := fPermCfg.GetCompositePermissionMode()
if err != nil {
return nil, fmt.Errorf(ePrefix+
"Error creating file mode code.\nError=%v\n", err.Error())
}
fPtr, err = os.OpenFile(pathFileName, fOpenCode, fileMode)
if err != nil {
return nil, fmt.Errorf(ePrefix+
"Error returned from os.OpenFile().\n"+
"pathFileName='%v'\nError='%v'\n",
pathFileName, err.Error())
}
if fPtr == nil {
return nil, fmt.Errorf(ePrefix +
"ERROR: File pointer returned from os.OpenFile() is 'nil'!\n")
}
return fPtr, nil
}
// RemovePathSeparatorFromEndOfPathString - Remove Trailing path Separator from
// a path string - if said trailing path Separator exists.
//
func (fh FileHelper) RemovePathSeparatorFromEndOfPathString(pathStr string) string {
errCode := 0
lPathStr := 0
errCode, lPathStr, pathStr = fh.isStringEmptyOrBlank(pathStr)
if errCode < 0 {
return ""
}
lastChar := rune(pathStr[lPathStr-1])
if lastChar == os.PathSeparator ||
lastChar == '\\' ||
lastChar == '/' {
return pathStr[0 : lPathStr-1]
}
return pathStr
}
// SearchFileModeMatch - This method determines whether the file mode of the file described by input
// parameter, 'info', is match for the File Selection Criteria 'fileSelectCriteria.SelectByFileMode'.
// If the file's FileMode matches the 'fileSelectCriteria.SelectByFileMode' value, the return value,
// 'isFileModeMatch' is set to 'true'.
//
// If 'fileSelectCriteria.SelectByFileMode' is NOT initialized to a valid File Mode value, the
// return value 'isFileModeSet' is set to 'false' signaling the File Mode File Selection Criterion
// is NOT active.
//
// Note: Input parameter 'info' is of type os.FileInfo. You can substitute a type 'FileInfoPlus'
// object for the 'info' parameter because 'FileInfoPlus' implements the 'os.FileInfo' interface.
//
func (fh *FileHelper) SearchFileModeMatch(
info os.FileInfo,
fileSelectCriteria FileSelectionCriteria) (isFileModeSet, isFileModeMatch bool, err error) {
if fileSelectCriteria.SelectByFileMode.isInitialized == false {
isFileModeSet = false
isFileModeMatch = false
err = nil
return isFileModeSet, isFileModeMatch, err
}
selectFileMode, err2 := fileSelectCriteria.SelectByFileMode.GetFileMode()
if err2 != nil {
ePrefix := "FileHelper.SearchFileModeMatch() "
err = fmt.Errorf(ePrefix+"SelectByFileMode is INVALID!\n"+
"Error='%v'\n", err2.Error())
return isFileModeSet, isFileModeMatch, err
}
if selectFileMode == info.Mode() {
isFileModeSet = true
isFileModeMatch = true
err = nil
return isFileModeSet, isFileModeMatch, err
}
isFileModeSet = true
isFileModeMatch = false
err = nil
return isFileModeSet, isFileModeMatch, err
}
// SearchFileNewerThan - This method is called to determine whether the file described by the
// input parameter 'info' is a 'match' for the File Selection Criteria, 'fileSelectCriteria.FilesNewerThan'.
// If the file modification date time occurs after the 'fileSelectCriteria.FilesNewerThan' date time,
// the return value 'isFileNewerThanMatch' is set to 'true'.
//
// If 'fileSelectCriteria.FilesNewerThan' is set to time.Time zero ( the default or zero value for this type),
// the return value 'isFileNewerThanSet' is set to 'false' signaling that this search criterion is NOT active.
//
// Note: Input parameter 'info' is of type os.FileInfo. You can substitute a type 'FileInfoPlus' object
// for the 'info' parameter because 'FileInfoPlus' implements the 'os.FileInfo' interface.
//
func (fh *FileHelper) SearchFileNewerThan(
info os.FileInfo,
fileSelectCriteria FileSelectionCriteria) (isFileNewerThanSet, isFileNewerThanMatch bool, err error) {
isFileNewerThanSet = false
isFileNewerThanMatch = false
err = nil
if fileSelectCriteria.FilesNewerThan.IsZero() {
isFileNewerThanSet = false
isFileNewerThanMatch = false
err = nil
return
}
if fileSelectCriteria.FilesNewerThan.Before(info.ModTime()) {
isFileNewerThanSet = true
isFileNewerThanMatch = true
err = nil
return
}
isFileNewerThanSet = true
isFileNewerThanMatch = false
err = nil
return
}
// SearchFileOlderThan - This method is called to determine whether the file described by the
// input parameter 'info' is a 'match' for the File Selection Criteria, 'fileSelectCriteria.FilesOlderThan'.
// If the file modification date time occurs before the 'fileSelectCriteria.FilesOlderThan' date time,
// the return value 'isFileOlderThanMatch' is set to 'true'.
//
// If 'fileSelectCriteria.FilesOlderThan' is set to time.Time zero ( the default or zero value for this type),
// the return value 'isFileOlderThanSet' is set to 'false' signaling that this search criterion is NOT active.
//
// Note: Input parameter 'info' is of type os.FileInfo. You can substitute a type 'FileInfoPlus' object
// for the 'info' parameter because 'FileInfoPlus' implements the 'os.FileInfo' interface.
//
func (fh *FileHelper) SearchFileOlderThan(
info os.FileInfo,
fileSelectCriteria FileSelectionCriteria) (isFileOlderThanSet,
isFileOlderThanMatch bool,
err error) {
if fileSelectCriteria.FilesOlderThan.IsZero() {
isFileOlderThanSet = false
isFileOlderThanMatch = false
err = nil
return
}
if fileSelectCriteria.FilesOlderThan.After(info.ModTime()) {
isFileOlderThanSet = true
isFileOlderThanMatch = true
err = nil
return
}
isFileOlderThanSet = true
isFileOlderThanMatch = false
err = nil
return
}
// SearchFilePatternMatch - used to determine whether a file described by the
// 'info' parameter meets the specified File Selection Criteria and is judged
// to be a match for the fileSelectCriteria FileNamePattern. 'fileSelectCriteria.FileNamePatterns'
// consists of a string array. If the pattern signified by any element in the string array
// is a 'match', the return value 'isPatternMatch' is set to true.
//
// If the 'fileSelectCriteria.FileNamePatterns' array is empty or if it contains only empty strings,
// the return value isPatternSet is set to 'false' signaling that the pattern file search selection
// criterion is NOT active.
//
// Note: Input parameter 'info' is of type os.FileInfo. You can substitute a type 'FileInfoPlus' object
// for the 'info' parameter because 'FileInfoPlus' implements the 'os.FileInfo' interface.
//
func (fh *FileHelper) SearchFilePatternMatch(
info os.FileInfo,
fileSelectCriteria FileSelectionCriteria) (isPatternSet, isPatternMatch bool, err error) {
ePrefix := "DirMgr.SearchFilePatternMatch()"
isPatternMatch = false
isPatternSet = false
err = nil
isPatternSet = fileSelectCriteria.ArePatternsActive()
if !isPatternSet {
isPatternSet = false
isPatternMatch = false
err = nil
return
}
lPats := len(fileSelectCriteria.FileNamePatterns)
for i := 0; i < lPats; i++ {
matched, err2 := fp.Match(fileSelectCriteria.FileNamePatterns[i], info.Name())
if err2 != nil {
isPatternSet = true
err = fmt.Errorf(ePrefix+
"Error returned from filepath.Match(fileSelectCriteria.FileNamePatterns[i], "+
"info.Name())\nfileSelectCriteria.FileNamePatterns[i]='%v'\ninfo.Name()='%v'\nError='%v'\n",
fileSelectCriteria.FileNamePatterns[i], info.Name(), err2.Error())
isPatternMatch = false
return
}
if matched {
isPatternSet = true
isPatternMatch = true
err = nil
return
}
}
isPatternSet = true
isPatternMatch = false
err = nil
return
}
// SwapBasePath - Searches the 'targetPath' string for the existence of
// 'oldBasePath'. If 'oldBasePath' is found, it is replaced with 'newBasePath'.
//
// If 'oldBasePath' is not found in 'targetPath' an error is returned.
//
// Likewise, if 'oldBasePath' is not located at the beginning of 'targetPath',
// an error will be returned.
//
func (fh FileHelper) SwapBasePath(
oldBasePath,
newBasePath,
targetPath string) (string, error) {
ePrefix := "FileHelper.SwapBasePath() "
errCode := 0
oldBaseLen := 0
errCode, oldBaseLen, oldBasePath = fh.isStringEmptyOrBlank(oldBasePath)
if errCode == -1 {
return "",
errors.New(ePrefix + "Input parameter 'oldBasePath' is an empty string!")
}
if errCode == -2 {
return "", errors.New(ePrefix +
"Input parameter 'oldBasePath' consists of all spaces!")
}
errCode, _, newBasePath = fh.isStringEmptyOrBlank(newBasePath)
if errCode == -1 {
return "",
errors.New(ePrefix + "Input parameter 'newBasePath' is an empty string!")
}
if errCode == -2 {
return "", errors.New(ePrefix +
"Input parameter 'newBasePath' consists of all spaces!")
}
targetPathLen := 0
errCode, targetPathLen, targetPath = fh.isStringEmptyOrBlank(targetPath)
if errCode == -1 {
return "",
errors.New(ePrefix + "Input parameter 'targetPath' is an empty string!")
}
if errCode == -2 {
return "", errors.New(ePrefix +
"Input parameter 'targetPath' consists of all spaces!")
}
if oldBaseLen > targetPathLen {
return "", errors.New(ePrefix +
"Length of input parameter 'oldBasePath' is greater than length of \n" +
"input parameter 'targetPath'.\n")
}
idx := strings.Index(
strings.ToLower(targetPath),
strings.ToLower(oldBasePath))
if idx < 0 {
return "",
fmt.Errorf(ePrefix+
"Error: Could not locate 'oldBasePath' in 'targetPath'. "+
"oldBasePath='%v' targetPath='%v' ",
oldBasePath, targetPath)
}
if idx != 0 {
return "",
fmt.Errorf(ePrefix+
"Error: 'oldBasePath' is NOT located at the beginning of 'targetPath'. "+
"oldBasePath='%v' targetPath='%v' ",
oldBasePath, targetPath)
}
return newBasePath + targetPath[oldBaseLen:], nil
}
/*
FileHelper private methods
*/
// doesPathFileExist - A helper method which public methods use to determine whether a
// path and file does or does not exist.
//
// This method calls os.Stat(dirPath) which returns an error which is one of two types:
//
// 1. A Non-Path Error - An error which is not path related. It signals some other type
// of error which makes impossible to determine if the path actually exists. These
// types of errors generally relate to "access denied" situations, but there may be
// other reasons behind non-path errors. If a non-path error is returned, no valid
// existence test can be performed on the file path.
//
// or
//
// 2. A Path Error - indicates that the path definitely does not exist.
//
// To deal with these types of errors, this method will test path existence up to three times before
// returning a non-path error.
//
func (fh FileHelper) doesPathFileExist(
filePath string,
preProcessCode PreProcessPathCode,
errorPrefix string,
filePathTitle string) (absFilePath string,
filePathDoesExist bool,
fInfo FileInfoPlus,
nonPathError error) {
ePrefix := "FileHelper.doesDirPathExist() "
absFilePath = ""
filePathDoesExist = false
fInfo = FileInfoPlus{}
nonPathError = nil
if len(errorPrefix) > 0 {
ePrefix = errorPrefix
}
if len(filePathTitle) == 0 {
filePathTitle = "filePath"
}
errCode := 0
errCode, _, filePath = fh.isStringEmptyOrBlank(filePath)
if errCode == -1 {
nonPathError = fmt.Errorf(ePrefix+
"Error: Input parameter '%v' is an empty string!", filePathTitle)
return absFilePath, filePathDoesExist, fInfo, nonPathError
}
if errCode == -2 {
nonPathError = fmt.Errorf(ePrefix+
"Error: Input parameter '%v' consists of blank spaces!", filePathTitle)
return absFilePath, filePathDoesExist, fInfo, nonPathError
}
var err error
if preProcessCode == PreProcPathCode.PathSeparator() {
absFilePath = fh.AdjustPathSlash(filePath)
} else if preProcessCode == PreProcPathCode.AbsolutePath() {
absFilePath, err = fh.MakeAbsolutePath(filePath)
if err != nil {
absFilePath = ""
nonPathError = fmt.Errorf(ePrefix+"fh.MakeAbsolutePath() FAILED!\n"+
"%v", err.Error())
return absFilePath, filePathDoesExist, fInfo, nonPathError
}
} else {
// For any other PreProcPathCode value, apply no pre-processing to
absFilePath = filePath
}
var info os.FileInfo
for i := 0; i < 3; i++ {
filePathDoesExist = false
fInfo = FileInfoPlus{}
nonPathError = nil
info, err = os.Stat(absFilePath)
if err != nil {
if os.IsNotExist(err) {
filePathDoesExist = false
fInfo = FileInfoPlus{}
nonPathError = nil
return absFilePath, filePathDoesExist, fInfo, nonPathError
}
// err == nil and err != os.IsNotExist(err)
// This is a non-path error. The non-path error will be test
// up to 3-times before it is returned.
nonPathError = fmt.Errorf(ePrefix+"Non-Path error returned by os.Stat(%v)\n"+
"%v='%v'\nError='%v'\n",
filePathTitle, filePathTitle, filePath, err.Error())
fInfo = FileInfoPlus{}
filePathDoesExist = false
} else {
// err == nil
// The path really does exist!
filePathDoesExist = true
nonPathError = nil
fInfo = FileInfoPlus{}.NewFromFileInfo(info)
return absFilePath, filePathDoesExist, fInfo, nonPathError
}
time.Sleep(30 * time.Millisecond)
}
return absFilePath, filePathDoesExist, fInfo, nonPathError
}
// isStringEmptyOrBlank - Analyzes a string to determine if the string is 'empty' or
// if the string consists of all blanks (spaces).
//
// ------------------------------------------------------------------------
//
// Return Values:
//
// int - Integer Values Returned:
// -1 = string is empty
// -2 = string consists entirely of spaces
// 0 = string contains non-space characters
//
// string - The original input parameter string ('testStr') from which the
// leading and trailing spaces have been deleted.
// Examples:
//
// 1. 'testStr' = " a string "
// return string = "a string"
//
// 2. 'testStr' = " "
// return string = ""
//
// 3. 'testStr' = ""
// return string = ""
//
func (fh FileHelper) isStringEmptyOrBlank(
testStr string) (errCode int, strLen int, newStr string) {
errCode = 0
strLen = 0
newStr = ""
if len(testStr) == 0 {
errCode = -1
return errCode, strLen, newStr
}
newStr = strings.TrimLeft(testStr, " ")
newStr = strings.TrimRight(newStr, " ")
strLen = len(newStr)
if strLen == 0 {
errCode = -2
newStr = ""
return errCode, strLen, newStr
}
errCode = 0
return errCode, strLen, newStr
}
// makeFileHelperWalkDirDeleteFilesFunc - Used in conjunction with DirMgr.DeleteWalDirFiles
// to select and delete files residing the directory tree identified by the current DirMgr
// object.
//
func (fh *FileHelper) makeFileHelperWalkDirDeleteFilesFunc(dInfo *DirectoryDeleteFileInfo) func(string, os.FileInfo, error) error {
return func(pathFile string, info os.FileInfo, erIn error) error {
ePrefix := "FileHelper.makeFileHelperWalkDirDeleteFilesFunc()"
if erIn != nil {
dInfo.ErrReturns = append(dInfo.ErrReturns, erIn)
return nil
}
if info.IsDir() {
subDir, err := DirMgr{}.New(pathFile)
if err != nil {
ex := fmt.Errorf(ePrefix+
"Error returned from DirMgr{}.New(pathFile).\n"+
"pathFile:='%v'\nError='%v'\n", pathFile, err.Error())
dInfo.ErrReturns = append(dInfo.ErrReturns, ex)
return nil
}
subDir.actualDirFileInfo, err = FileInfoPlus{}.NewFromPathFileInfo(pathFile, info)
if err != nil {
ex := fmt.Errorf( ePrefix +
"Error returned by FileInfoPlus{}.NewFromPathFileInfo(pathFile, info)\n" +
"pathFile='%v'\ninfo.Name='%v'\nError='%v'\n",
pathFile, info.Name(), err.Error())
dInfo.ErrReturns = append(dInfo.ErrReturns, ex)
} else {
dInfo.Directories.AddDirMgr(subDir)
}
return nil
}
isFoundFile, err := fh.FilterFileName(info, dInfo.DeleteFileSelectCriteria)
if err != nil {
ex := fmt.Errorf(ePrefix+
"Error returned from fh.FilterFileName(info, dInfo.DeleteFileSelectCriteria)\n" +
"pathFile='%v'\n" +
"info.Name()='%v'\nError='%v'\n",
pathFile, info.Name(), err.Error())
dInfo.ErrReturns = append(dInfo.ErrReturns, ex)
return nil
}
if isFoundFile {
err := os.Remove(pathFile)
if err != nil {
ex := fmt.Errorf(ePrefix+
"Error returned from os.Remove(pathFile). pathFile='%v' Error='%v'",
pathFile, err.Error())
dInfo.ErrReturns = append(dInfo.ErrReturns, ex)
return nil
}
err = dInfo.DeletedFiles.AddFileMgrByFileInfo(pathFile, info)
if err != nil {
ex := fmt.Errorf(ePrefix+
"Error returned from dInfo.DeletedFiles.AddFileMgrByFileInfo( pathFile, info). "+
"pathFile='%v' Error='%v'",
pathFile, err.Error())
dInfo.ErrReturns = append(dInfo.ErrReturns, ex)
return nil
}
}
return nil
}
}
// makeFileHelperWalkDirFindFilesFunc - This function is designed to work in conjunction
// with a walk directory function like FindWalkDirFiles. It will process
// files extracted from a 'Directory Walk' operation initiated by the 'filepath.Walk' method.
func (fh *FileHelper) makeFileHelperWalkDirFindFilesFunc(dInfo *DirectoryTreeInfo) func(string, os.FileInfo, error) error {
return func(pathFile string, info os.FileInfo, erIn error) error {
ePrefix := "DirMgr.makeFileHelperWalkDirFindFilesFunc() "
if erIn != nil {
ex2 := fmt.Errorf(ePrefix+"Error returned from directory walk function. "+
"pathFile= '%v' Error='%v'", pathFile, erIn.Error())
dInfo.ErrReturns = append(dInfo.ErrReturns, ex2)
return nil
}
if info.IsDir() {
subDir, err := DirMgr{}.NewFromFileInfo(pathFile, info)
if err != nil {
er2 := fmt.Errorf(ePrefix+"Error returned by DirMgr{}.New(pathFile). "+
"pathFile='%v' Error='%v'", pathFile, err.Error())
dInfo.ErrReturns = append(dInfo.ErrReturns, er2)
return nil
}
dInfo.Directories.AddDirMgr(subDir)
return nil
}
fh := FileHelper{}
// This is not a directory. It is a file.
// Determine if it matches the find file criteria.
isFoundFile, err := fh.FilterFileName(info, dInfo.FileSelectCriteria)
if err != nil {
er2 := fmt.Errorf(ePrefix+
"Error returned from dMgr.FilterFileName(info, " +
"dInfo.FileSelectCriteria)\n" +
"pathFile='%v'\ninfo.Name()='%v'\nError='%v'\n",
pathFile, info.Name(), err.Error())
dInfo.ErrReturns = append(dInfo.ErrReturns, er2)
return nil
}
if isFoundFile {
fMgr, err2 := FileMgr{}.NewFromPathFileNameExtStr(pathFile)
if err2 != nil {
err = fmt.Errorf(ePrefix+
"Error returned by FileMgr{}.NewFromPathFileNameExtStr(pathFile) "+
"pathFile='%v' Error='%v' ", pathFile, err2.Error())
dInfo.ErrReturns = append(dInfo.ErrReturns, err)
return nil
}
err = dInfo.FoundFiles.AddFileMgrByFileInfo(fMgr.dMgr.GetAbsolutePath(), info)
if err != nil {
er2 := fmt.Errorf(ePrefix+
"Error returned from dInfo.FoundFiles.AddFileMgrByFileInfo(pathFile, info)\n"+
"pathFile='%v'\ninfo.Name()='%v'\nError='%v'\n",
pathFile, info.Name(), err.Error())
dInfo.ErrReturns = append(dInfo.ErrReturns, er2)
return nil
}
}
return nil
}
}
|
package main
import (
"html/template"
"io"
)
const (
extendSwitchRolesBaseAccountTemplate = `
[{{.TeamName}}]
aws_account_id = {{.AccountName}}
`
)
const (
extendSwitchRolesTemplate = `
[{{.AccountName}}]
source_profile = {{.SourceProfile}}
color = {{.Color}}
role_arn = arn:aws:iam::{{.AccountId}}:role/{{.Role}}
`
)
func generateExtendSwitchRolesBaseConfig(w io.Writer, team team) error {
if tpl, err := template.New("aliases").Option("missingkey=error").Parse(extendSwitchRolesBaseAccountTemplate); err != nil {
return err
} else {
t := templateVars{
TeamName: team.Name,
AccountName: team.SwitchRoleAccount,
}
_ = tpl.Execute(w, t)
}
return nil
}
func generateExtendSwitchRolesConfigForAccount(w io.Writer, team team, account account, role string) error {
if tpl, err := template.New("aliases").Option("missingkey=error").Parse(extendSwitchRolesTemplate); err != nil {
return err
} else {
generateExtendSwitchRolesConfigForRole(w, team, account, role, tpl)
}
return nil
}
func generateExtendSwitchRolesConfigForRole(w io.Writer, team team, account account, role string, tpl *template.Template) {
profileName := team.Name + "-" + account.Name + "-" + role
t := templateVars{
AccountId: account.AccountId,
AccountName: profileName,
Color: account.Color,
Role: role,
SourceProfile: team.Name,
}
_ = tpl.Execute(w, t)
}
|
package model
import "time"
type RoutingEntry struct {
Dest VirtualIp
Cost int
ExitIp VirtualIp
NextHop VirtualIp
Ttl int64
IsUpdated bool
GcTimer int64
HasExpired bool
IsLocal bool
}
func MakeRoutingEntry(dst VirtualIp, exitIp VirtualIp, nextHop VirtualIp, cost int, isLocal bool) RoutingEntry {
ttlTimer := time.Now().Unix() + RIP_ROUTING_ENTRY_TTL_SECONDS
gcTimer := ttlTimer + RIP_GC_TIMER_SECONDS
return RoutingEntry{dst, cost, exitIp, nextHop, ttlTimer, false, gcTimer, false, isLocal}
}
func (entry *RoutingEntry) Update(cost int, nextHop VirtualIp) {
entry.UpdateCost(cost)
entry.UpdateNextHop(nextHop)
entry.ResetTtl()
entry.SetExpired(false)
entry.ResetGcTimer()
entry.SetIsUpdated(true)
}
func (entry *RoutingEntry) ExtendTtl() {
entry.Ttl = time.Now().Unix() + RIP_ROUTING_ENTRY_TTL_SECONDS
entry.GcTimer = time.Now().Unix() + RIP_GC_TIMER_SECONDS
entry.HasExpired = false
}
func (entry *RoutingEntry) ResetTtl() {
entry.Ttl = time.Now().Unix() + RIP_ROUTING_ENTRY_TTL_SECONDS
entry.SetIsUpdated(true)
}
func (entry *RoutingEntry) ResetGcTimer() {
entry.GcTimer = time.Now().Unix() + RIP_GC_TIMER_SECONDS
entry.SetIsUpdated(true)
}
func (entry *RoutingEntry) UpdateCost(cost int) {
entry.Cost = cost
entry.SetIsUpdated(true)
}
func (entry *RoutingEntry) UpdateNextHop(nextHop VirtualIp) {
entry.NextHop = nextHop
entry.SetIsUpdated(true)
}
func (entry *RoutingEntry) SetIsUpdated(isUpdated bool) {
entry.IsUpdated = isUpdated
}
func (entry *RoutingEntry) SetExpired(expired bool) {
entry.HasExpired = expired
entry.SetIsUpdated(true)
}
func (entry *RoutingEntry) Expired() bool {
return entry.HasExpired
}
func (entry *RoutingEntry) Reachable() bool {
return entry.Cost < RIP_INFINITY
}
func (entry *RoutingEntry) ShouldExpire() bool {
// retrun true if ttl is expired but the entry hasn't been marked as expired
if entry.IsLocal && entry.Cost == 0 {
// a route to a local destination should never expire
return false
}
return (time.Now().Unix() > entry.Ttl) && !entry.Expired()
}
func (entry *RoutingEntry) ShouldGC() bool {
if entry.IsLocal && entry.Cost == 0 {
return false
}
return (time.Now().Unix() > entry.GcTimer) && entry.Expired()
}
func (entry *RoutingEntry) MarkAsExpired() {
entry.UpdateCost(RIP_INFINITY)
entry.SetExpired(true)
entry.SetIsUpdated(true)
}
|
package unarchive
import (
"bytes"
"github.com/alexmullins/zip"
"log"
"os/exec"
"strings"
)
func checkForPassword(path,ext string,err error)bool{
switch ext {
case ".zip":
return checkZip(path,err)
case ".rar":
return checkRar(path,err)
case ".7z":
return check7z(path)
}
return false
}
func checkZip(path string,err error)bool{
//открыть архив
//проверка на пароль
or, err := zip.OpenReader(path)
if err != nil {
return false
}
defer or.Close()
if or.File[0].IsEncrypted() {
return true
}
return false
}
func checkRar(path string,err error)bool{
if err.Error() == "reading file in rar archive: rardecode: incorrect password" {
return true
}
return false
}
//true password exist
func check7z(path string)bool{
//
var cmd *exec.Cmd
cmd = getCommandPassword(path)
//var out bytes.Buffer
var stderr bytes.Buffer
//cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
if strings.Contains(stderr.String(),"Can not open encrypted archive. Wrong password?") {
log.Println(path,"Contains password")
return true
}
}
return false
}
//добавить 7z в path
func addToPATH(){
//fmt.Println(os.Getenv("TEST_ENV_FOR_PROD"))
//os.Setenv("TEST_ENV_FOR_PROD","/w/e/r/t:d/d/g/s")
//old := os.Getenv("TEST_ENV_FOR_PROD")
//fmt.Println(os.Getenv("TEST_ENV_FOR_PROD"))
//newenv := old + ":" + "/w/g/a/c/g"
//os.Setenv("TEST_ENV_FOR_PROD", newenv)
//fmt.Println(os.Getenv("TEST_ENV_FOR_PROD"))
}
|
package main
import "fmt"
// https://leetcode-cn.com/problems/generate-parentheses/
func generateParenthesis(n int) []string {
if n == 0 {
return []string{}
}
str := make([]byte, 2*n)
var res []string
var gen func(left, right int)
gen = func(l, r int) {
if l == n && r == n {
res = append(res, string(str))
return
}
if l < n {
str[l+r] = '('
gen(l+1, r)
}
if l > r {
str[l+r] = ')'
gen(l, r+1)
}
}
gen(0, 0)
return res
}
func main() {
cases := []int{
3,
}
realCase := cases[0:]
for i, c := range realCase {
fmt.Println("## case", i)
// solve
fmt.Println(generateParenthesis(c))
}
}
|
package telemetry
import (
"fmt"
"strings"
"github.com/10gen/realm-cli/internal/utils/flags"
)
// set of supported telemetry flags
const (
FlagMode = "telemetry"
FlagModeUsage = `Enable/Disable CLI usage tracking for your current profile (Default value: "on"; Allowed values: "on", "off")`
)
// Mode is the Telemetry Mode
type Mode string
// String returns the string representation
func (m Mode) String() string { return string(m) }
// Type returns the Mode type
func (m Mode) Type() string { return flags.TypeString }
// Set validates and sets the mode value
func (m *Mode) Set(val string) error {
mode := Mode(val)
if !isValidMode(mode) {
allModes := []string{string(ModeOn), string(ModeOff)}
return fmt.Errorf("unsupported value, use one of [%s] instead", strings.Join(allModes, ", "))
}
*m = mode
return nil
}
// set of supported telemetry modes
const (
ModeEmpty Mode = "" // zero-valued to be flag's default
ModeOn Mode = "on"
ModeStdout Mode = "stdout"
ModeOff Mode = "off"
)
func isValidMode(mode Mode) bool {
switch mode {
case
ModeOn,
ModeEmpty,
ModeStdout,
ModeOff:
return true
}
return false
}
|
package main
import (
"errors"
"fmt"
"net/http"
"os"
"strings"
"time"
"./models"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/globalsign/mgo/bson"
)
var connection = models.Db()
func listBooksEndpoint(c *gin.Context) {
book := &models.Book{}
var books = []models.Book{}
find := connection.Collection("books").Find(bson.M{})
for find.Next(book) {
books = append(books, *book)
}
c.JSON(http.StatusOK, books)
}
func createBookEndpoint(c *gin.Context) {
var newBook models.Book
if c.ShouldBind(&newBook) == nil {
connection.Collection("books").Save(&newBook)
c.JSON(http.StatusCreated, newBook)
} else {
c.JSON(http.StatusBadRequest, gin.H{})
}
}
func FindBookByID(id string) (models.Book, error) {
book := &models.Book{}
err := connection.Collection("books").FindById(bson.ObjectIdHex(id), book)
return *book, err
}
func updateBookEndpoint(c *gin.Context) {
id := c.Param("id")
var newBook models.Book
if c.ShouldBind(&newBook) == nil {
newBook.SetId(bson.ObjectIdHex(id))
connection.Collection("books").Save(&newBook)
c.JSON(http.StatusCreated, newBook)
} else {
c.JSON(http.StatusBadRequest, gin.H{})
}
}
func RemoveBookByID(id string) error {
err := connection.Collection("books").DeleteOne(bson.M{"_id": bson.ObjectIdHex(id)})
return err
}
func deleteBookEndpoint(c *gin.Context) {
id := c.Param("id")
err := RemoveBookByID(id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err})
return
}
c.JSON(http.StatusNoContent, gin.H{})
}
func getBookEndpoint(c *gin.Context) {
id := c.Param("id")
book, err := FindBookByID(id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err})
return
}
c.JSON(http.StatusOK, book)
}
func TokenAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authorizationHeader := c.Request.Header.Get("Authorization")
if authorizationHeader == "" {
c.JSON(http.StatusUnauthorized, errors.New("Not authenticated"))
c.Abort()
return
}
tokenString := strings.Split(authorizationHeader, "Bearer ")[1]
_, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte("jdnfksdmfksd"), nil
})
if err != nil {
c.JSON(http.StatusUnauthorized, errors.New("Not authorized"))
c.Abort()
return
}
c.Next()
}
}
func CreateToken(userName string) (string, error) {
var err error
//Creating Access Token
os.Setenv("ACCESS_SECRET", "jdnfksdmfksd") //this should be in an env file
atClaims := jwt.MapClaims{}
atClaims["authorized"] = true
atClaims["user_id"] = userName
atClaims["exp"] = time.Now().Add(time.Minute * 15).Unix()
at := jwt.NewWithClaims(jwt.SigningMethodHS256, atClaims)
token, err := at.SignedString([]byte(os.Getenv("ACCESS_SECRET")))
if err != nil {
return "", err
}
return token, nil
}
func signinEndpoint(c *gin.Context) {
users := []models.User{
{
Name: "teste",
Password: "teste",
},
}
var signinUser models.User
if err := c.ShouldBindJSON(&signinUser); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
isAuth := false
for _, n := range users {
if signinUser.Name == n.Name && signinUser.Password == n.Password {
isAuth = true
}
}
result, _ := CreateToken(signinUser.Name)
if isAuth == true {
c.JSON(http.StatusOK, gin.H{"token": result})
} else {
c.JSON(http.StatusUnauthorized, gin.H{})
}
}
func main() {
router := gin.Default()
router.POST("/signin", signinEndpoint)
booksRoutes := router.Group("/books")
{
booksRoutes.GET("/", listBooksEndpoint)
booksRoutes.POST("/", createBookEndpoint)
booksRoutes.PUT("/:id", updateBookEndpoint)
booksRoutes.GET("/:id", getBookEndpoint)
booksRoutes.DELETE("/:id", deleteBookEndpoint)
}
router.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
|
package tic
import (
"context"
"github.com/odom11/playground_micro/api"
"golang.org/x/tools/go/ssa/interp/testdata/src/fmt"
)
type Tic struct {
toc api.TocService;
counter int
}
func New(toc api.TocService) *Tic {
return &Tic{toc: toc}
}
func (t *Tic) Shout(ctx context.Context, req *api.Bounce, rsp *api.Bounce) error {
_, err := t.toc.Shout(context.Background(), &api.Bounce{Message: "foo"})
if err != nil {
fmt.Println("tic successfully shouted ", t.counter)
t.counter++
fmt.Println("got message: ", req.Message)
}
return nil
}
|
package image
import (
"api/factory"
"api/handler"
"context"
"encoding/json"
"io"
"net/http"
"os"
"path/filepath"
"time"
"cloud.google.com/go/storage"
"github.com/gorilla/mux"
)
func Create(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
username := vars["username"]
typeImage := vars["type"]
file, handle, err := request.FormFile("file")
defer file.Close()
extension := filepath.Ext(handle.Filename)
hash := handler.RandomString(20)
path := username + "/" + typeImage + "/" + string(hash) + extension
var created bool
var image *Image
var resp []byte
if created, resp, image = create(path, typeImage, hash); !created {
response.WriteHeader(http.StatusInternalServerError)
response.Write(resp)
return
}
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
image.delete()
}
ctx, cancel := context.WithTimeout(ctx, time.Second*50)
defer cancel()
bucket := client.Bucket(os.Getenv("BUCKET_NAME"))
wc := bucket.Object(path).NewWriter(ctx)
if _, err = io.Copy(wc, file); err != nil {
image.delete()
}
if err := wc.Close(); err != nil {
image.delete()
}
payload, _ := json.Marshal(image)
response.Write(payload)
}
func create(path string, typeImage string, hash string) (bool, []byte, *Image) {
image := New()
db := factory.GetConnection()
defer db.Close()
{
tx, err := db.Begin()
e, isEr := factory.CheckErr(err)
if isEr {
return false, e.ReturnError(), nil
}
{
stmt, err := tx.Prepare(`INSERT INTO image (path, type, path_code) VALUES ($1, $2, $3) returning *;`)
e, isEr := factory.CheckErr(err)
if isEr {
tx.Rollback()
return false, e.ReturnError(), nil
}
err = stmt.QueryRow(path, typeImage, hash).Scan(
&image.ID,
&image.Path,
&image.Type,
&image.PathCode,
)
e, isEr = factory.CheckErr(err)
if isEr {
tx.Rollback()
return false, e.ReturnError(), nil
}
}
tx.Commit()
}
return true, nil, &image
}
func (image Image) delete() {
db := factory.GetConnection()
defer db.Close()
{
tx, err := db.Begin()
_, isEr := factory.CheckErr(err)
if isEr {
tx.Rollback()
}
{
stmt, err := tx.Prepare(` DELETE FROM image WHERE id = $1; `)
_, isEr := factory.CheckErr(err)
if isEr {
tx.Rollback()
}
_, err = stmt.Exec(image.ID)
_, isEr = factory.CheckErr(err)
if isEr {
tx.Rollback()
}
}
tx.Commit()
}
}
|
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
func main() {
data, err := ioutil.ReadFile("gameofthrones-1-1.txt")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(data[0])
fmt.Println(data[1])
data_s := strings.Replace(string(data), "<br>", " ", -1) // 줄바꿈 => 뛰어쓰기로 변경
data_s = strings.Replace(string(data_s), " ", "", -1) // => 빈값으로 변경
data_s = strings.Replace(string(data_s), "<P Class=KRCC>", "", -1)
data_s = strings.Replace(string(data_s), "<P Class=ENCC>", "", -1)
data = []byte(data_s)
b_del := false
for i := 0; i < len(data); i++ {
if data[i] == 60 && b_del == false {
b_del = true
data[i] = 0
} else if data[i] == 62 && b_del == true {
data[i] = 0
b_del = false
}
if b_del == true {
data[i] = 0
}
}
err = ioutil.WriteFile("gameofthrones-1-1copy.txt", []byte(string(data)), os.FileMode(644))
if err != nil {
fmt.Println(err)
return
}
}
|
package main
import (
"fmt"
"reflect"
)
func setvalue(x interface{}) {
//v := reflect.ValueOf(x)
// if v.Elem().Kind()==reflect.Int{
// v.Elem().SetInt(365)
v := reflect.ValueOf(x).Elem()
if v.Kind() == reflect.Int {
v.SetInt(365)
}
}
func main() {
a := 1
setvalue(&a)
fmt.Printf("type:%T,value:%v", a, a)
}
|
package keva
type bucketCache struct {
HitCount uint64
MissCount uint64
maxBucketsCached int
usedEntries bucketCacheEntry
freeEntries bucketCacheEntry
bucketsCached int
buckets []bucketCacheEntry
trieRoot *bucketCacheTrie
}
func (c *bucketCache) Clear() {
c.buckets = make([]bucketCacheEntry, c.maxBucketsCached)
c.usedEntries.Init()
c.freeEntries.Init()
for i := 0; i < len(c.buckets); i++ {
e := &c.buckets[i]
e.Init().SpliceAfter(&c.freeEntries)
}
c.bucketsCached = 0
c.trieRoot = newBucketCacheTrie()
}
func (c *bucketCache) Close(rootPath string) error {
err := c.Flush(rootPath)
if err != nil {
return err
}
c.Clear()
return nil
}
func (c *bucketCache) Evict(bucketID string, rootPath string) error {
e := c.trieRoot.Remove(bucketPath(bucketID))
if e != nil {
err := e.bucket.Save(rootPath)
if err != nil {
return err
}
e.SpliceAfter(&c.freeEntries)
c.bucketsCached--
}
return nil
}
func (c *bucketCache) Fetch(bucketID string, rootPath string, fetch func(string) (*bucket, error)) (*bucket, error) {
b := c.lookup(bucketID)
if b != nil {
return b, nil
}
b, err := fetch(bucketID)
if err != nil {
return nil, err
}
err = c.encache(b, rootPath)
if err != nil {
return nil, err
}
return b, nil
}
func (c *bucketCache) Flush(rootPath string) error {
for e := c.usedEntries.next; e != &c.usedEntries; e = e.next {
err := e.bucket.Save(rootPath)
if err != nil {
return err
}
}
return nil
}
func (c *bucketCache) SetMaxBucketsCached(n int, rootPath string) error {
err := c.Flush(rootPath)
if err != nil {
return err
}
c.maxBucketsCached = n
c.Clear()
return nil
}
func (c *bucketCache) encache(b *bucket, rootPath string) error {
var e *bucketCacheEntry
if c.bucketsCached >= c.maxBucketsCached {
e = c.usedEntries.prev
c.trieRoot.Remove(e.bucket.path)
err := e.bucket.Save(rootPath)
if err != nil {
return err
}
} else {
c.bucketsCached++
e = c.freeEntries.next
}
e.SpliceAfter(&c.usedEntries)
e.bucket = b
c.trieRoot.Insert(e)
return nil
}
func (c *bucketCache) lookup(id string) *bucket {
e := c.trieRoot.Find(bucketPath(id))
if e != nil {
c.HitCount++
e.SpliceAfter(&c.usedEntries)
return e.bucket
}
c.MissCount++
return nil
}
func newBucketCache(maxBucketsCached int) *bucketCache {
c := &bucketCache{
maxBucketsCached: maxBucketsCached,
}
c.Clear()
return c
}
|
package models
import (
"database/sql"
"fmt"
"github.com/google/uuid"
)
type AvailableInterview struct {
ID int `json:"id"`
Start string `json:"start"`
End string `json:"end"`
PositionID int `json:"position"`
Address string `json:"address"`
Room string `json:"room"`
}
type BookedInterview struct {
ID int `json:"id"`
Start string `json:"start"`
End string `json:"end"`
PositionID int `json:"position"`
Address string `json:"address"`
Room string `json:"room"`
IntervieweeID int `json:"interviewee"`
}
func GetAllInterviews(db *sql.DB) ([]AvailableInterview, error) {
query := fmt.Sprintf(`SELECT * FROM Available`)
rows, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
interviews := []AvailableInterview{}
for rows.Next() {
var interview AvailableInterview
if err := rows.Scan(&interview.ID, &interview.Start, &interview.End,
&interview.PositionID, &interview.Address, &interview.Room); err != nil {
return nil, err
}
interviews = append(interviews, interview)
}
return interviews, nil
}
func GetInterviewById(db *sql.DB, interviewID int) (*AvailableInterview, error) {
query := fmt.Sprintf(`SELECT * FROM Available WHERE id = %d
UNION
SELECT id, start_time, end_time, position_id, address, room_name FROM Booked WHERE id = %d`, interviewID, interviewID)
row := db.QueryRow(query)
var interview AvailableInterview
if err := row.Scan(&interview.ID, &interview.Start, &interview.End,
&interview.PositionID, &interview.Address, &interview.Room); err != nil {
return nil, err
}
return &interview, nil
}
func GetInterviews(db *sql.DB, start, end, position string) ([]AvailableInterview, error) {
query := fmt.Sprintf(`SELECT a.id, a.start_time, a.end_time, a.position_id FROM Available a, Position p
WHERE (a.start_time BETWEEN '%s' AND '%s')
AND (end_time BETWEEN '%s' AND '%s') AND (a.position_id = p.id) AND (p.name = '%s')`, start, end, start, end, position)
rows, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
interviews := []AvailableInterview{}
for rows.Next() {
var interview AvailableInterview
if err := rows.Scan(&interview.ID, &interview.Start, &interview.End,
&interview.PositionID); err != nil {
return nil, err
}
interviews = append(interviews, interview)
}
return interviews, nil
}
func GetMinimumTime(db *sql.DB, start, end, position string) (*AvailableInterview, error) {
query := fmt.Sprintf(`SELECT MIN(a.start_time) as start_time FROM Available a, Position p
WHERE (a.start_time BETWEEN '%s' AND '%s')
AND (end_time BETWEEN '%s' AND '%s') AND (a.position_id = p.id) AND (p.name = '%s')`, start, end, start, end, position)
rows := db.QueryRow(query)
var interview AvailableInterview
if err := rows.Scan(&interview.Start); err != nil {
return nil, err
}
return &interview, nil
}
func GetInterviewsWithLocation(db *sql.DB, start, end, position string) ([]AvailableInterview, error) {
query := fmt.Sprintf(`SELECT a.id, a.start_time, a.end_time, a.position_id
, a.address, a.room_name FROM Available a, Position p
WHERE (a.start_time BETWEEN '%s' AND '%s')
AND (end_time BETWEEN '%s' AND '%s') AND (a.position_id = p.id) AND (p.name = '%s')`, start, end, start, end, position)
rows, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
interviews := []AvailableInterview{}
for rows.Next() {
var interview AvailableInterview
if err := rows.Scan(&interview.ID, &interview.Start, &interview.End,
&interview.PositionID, &interview.Address, &interview.Room); err != nil {
return nil, err
}
interviews = append(interviews, interview)
}
return interviews, nil
}
func GetInterviewsByPosition(db *sql.DB, positionName string) ([]AvailableInterview, error) {
query := fmt.Sprintf(`SELECT a.id, a.start_time, a.end_time,
a.position_id, a.address, a.room_name FROM Available a, Position p WHERE
a.position_id = p.id AND p.name = '%s'`, positionName)
rows, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
interviews := []AvailableInterview{}
for rows.Next() {
var interview AvailableInterview
if err := rows.Scan(&interview.ID, &interview.Start, &interview.End,
&interview.PositionID, &interview.Address, &interview.Room); err != nil {
return nil, err
}
interviews = append(interviews, interview)
}
return interviews, nil
}
func GetInterviewsWithEveryQuestion(db *sql.DB) ([]AvailableInterview, error) {
query := fmt.Sprintf(`SELECT * FROM Available a WHERE NOT EXISTS (
SELECT * FROM Questions q WHERE NOT EXISTS (
SELECT c.available_interview_id FROM Contains c
WHERE a.id = c.available_interview_id AND q.id = c.question_id) )`)
rows, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
interviews := []AvailableInterview{}
for rows.Next() {
var interview AvailableInterview
if err := rows.Scan(&interview.ID, &interview.Start, &interview.End,
&interview.PositionID, &interview.Address, &interview.Room); err != nil {
return nil, err
}
interviews = append(interviews, interview)
}
return interviews, nil
}
func GetQuestionDifficulty(db *sql.DB, interviewId int) (string, error) {
query := fmt.Sprintf(`SELECT difficulty FROM (
SELECT question_id FROM Contains WHERE booked_interview_id = %d OR available_interview_id = %d) a, Questions b
WHERE a.question_id = b.id`, interviewId, interviewId)
rows, err := db.Query(query)
if err != nil {
return "", err
}
count := 0.0
sum := 0.0
defer rows.Close()
for rows.Next() {
var difficulty float64
if err := rows.Scan(&difficulty); err != nil {
return "", err
}
sum += difficulty
count++
}
avg := sum / count
var difficulty string
if avg > 1 && avg <= 1.5 {
difficulty = "easy"
} else if avg > 1.5 && avg <= 2.5 {
difficulty = "medium"
} else {
difficulty = "hard"
}
return difficulty, nil
}
func DeleteInterview(db *sql.DB, interviewID int) error {
getStatement := fmt.Sprintf(`SELECT id, start_time,
end_time, position_id, address, room_name
FROM Booked WHERE id = %d`, interviewID)
row := db.QueryRow(getStatement)
var available AvailableInterview
if err := row.Scan(&available.ID, &available.Start, &available.End, &available.PositionID,
&available.Address, &available.Room); err != nil {
return err
}
if err := available.create(db); err != nil {
return err
}
if err := updateConducts(db, interviewID, false); err != nil {
return fmt.Errorf("Unable to update conduct table: %v", err)
}
if err := updateContains(db, interviewID, false); err != nil {
return fmt.Errorf("unable to update contains table: %v", err)
}
statement := fmt.Sprintf(`DELETE FROM Booked
WHERE id = %d`, interviewID)
if _, err := db.Exec(statement); err != nil {
return err
}
return nil
}
func (available *AvailableInterview) create(db *sql.DB) error {
insertStatement := fmt.Sprintf(` INSERT INTO Available VALUES (
%d, '%s', '%s', %d, '%s', '%s')`, available.ID, available.Start, available.End,
available.PositionID, available.Address, available.Room)
if _, err := db.Exec(insertStatement); err != nil {
return err
}
return nil
}
func BookInterview(db *sql.DB, interviewID, intervieweeID int, nda, tou bool) error {
available, err := getAvailable(db, interviewID)
if err != nil {
return fmt.Errorf("Unable to get interview: %v", err)
}
booked := BookedInterview{
ID: available.ID,
Start: available.Start,
End: available.End,
PositionID: available.PositionID,
Address: available.Address,
Room: available.Room,
IntervieweeID: intervieweeID,
}
if err := booked.create(db); err != nil {
return fmt.Errorf("unable to create booked: %v", err)
}
if err := updateConducts(db, interviewID, true); err != nil {
return fmt.Errorf("Unable to update conduct table: %v", err)
}
if err := updateContains(db, interviewID, true); err != nil {
return fmt.Errorf("unable to update contains table: %v", err)
}
if err := addAgreement(db, interviewID, nda, tou); err != nil {
return fmt.Errorf("unable to add agreement: %v", err)
}
if err := removeAvailable(db, interviewID); err != nil {
return fmt.Errorf("Unable to remove available: %v", err)
}
return nil
}
func updateConducts(db *sql.DB, interviewID int, isToBooked bool) error {
var updateStatement string
if isToBooked {
updateStatement = fmt.Sprintf(`UPDATE Conducts SET booked_interview_id=%d WHERE available_interview_id = %d`,
interviewID, interviewID)
} else {
updateStatement = fmt.Sprintf(`UPDATE Conducts SET available_interview_id=%d WHERE booked_interview_id = %d`,
interviewID, interviewID)
}
if _, err := db.Exec(updateStatement); err != nil {
return err
}
return nil
}
func updateContains(db *sql.DB, interviewID int, isToBooked bool) error {
var updateStatement string
if isToBooked {
updateStatement = fmt.Sprintf(`UPDATE Contains SET booked_interview_id=%d WHERE available_interview_id = %d`,
interviewID, interviewID)
} else {
updateStatement = fmt.Sprintf(`UPDATE Contains SET available_interview_id=%d WHERE booked_interview_id = %d`,
interviewID, interviewID)
}
if _, err := db.Exec(updateStatement); err != nil {
return err
}
return nil
}
func addAgreement(db *sql.DB, interviewID int, nda, tou bool) error {
id, err := uuid.NewUUID()
if err != nil {
return fmt.Errorf("Unable to generate id for interviewee: %v", err)
}
agreementID := uint16(id.ID())
insertStatement := fmt.Sprintf(`INSERT INTO Agreement VALUES (%d, %d, %v, %v)`,
agreementID, interviewID, nda, tou)
if _, err := db.Exec(insertStatement); err != nil {
return err
}
return nil
}
func (booked *BookedInterview) create(db *sql.DB) error {
createStatement := fmt.Sprintf(`INSERT INTO Booked VALUES (
%d, '%s', '%s', %d, '%s', '%s', %d)`, booked.ID, booked.Start,
booked.End, booked.PositionID, booked.Address, booked.Room, booked.IntervieweeID)
if _, err := db.Exec(createStatement); err != nil {
return err
}
return nil
}
func removeAvailable(db *sql.DB, availableInterviewID int) error {
removeStatement := fmt.Sprintf(`DELETE FROM Available
WHERE id = %d`, availableInterviewID)
if _, err := db.Exec(removeStatement); err != nil {
return err
}
return nil
}
func getAvailable(db *sql.DB, id int) (*AvailableInterview, error) {
queryStatement := fmt.Sprintf(`SELECT * FROM Available
WHERE id = %d`, id)
row := db.QueryRow(queryStatement)
var available AvailableInterview
if err := row.Scan(&available.ID, &available.Start,
&available.End, &available.PositionID, &available.Address,
&available.Room); err != nil {
return nil, err
}
return &available, nil
}
|
/*
Challenge
For any two non-empty strings A and B, we define the following sequence :
F(0) = A
F(1) = B
F(n) = F(n-1) + F(n-2)
Where + denotates the standard string concatenation.
The sequence for strings "A" and "B" starts with the following terms: A, B, BA, BAB, BABBA, ...
Create a function or program that, when given two strings A and B, and a positive integer I returns the I-th character of F(∞).
You may choose to use 0-indexing or 1-indexing for I, just specify it in your answer.
You may assume the strings contain only uppercase (or lowercase) letters.
This is a variation of Project Euler's Problem 230, where the two strings were strings of digits of equal length, which trivialize the problem.
Input/Output
You may choose any format for the input. The output should only contain the desired character, with trailing spaces/newlines allowed.
Test Cases
ABC, DEF, 1234567890 → A
ACBB, DEFGH, 45865 → B
A, B, 3 → B
ABC, DEF, 10 → E
This is code-golf, so the lowest byte count for each language wins!
*/
package main
func main() {
assert(vlfw("ABC", "DEF", 1234567890) == 'A')
assert(vlfw("ACBB", "DEFGH", 45865) == 'B')
assert(vlfw("A", "B", 3) == 'B')
assert(vlfw("ABC", "DEF", 10) == 'E')
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
/*
@Delfad0r
F(a, b) = b + F(b, a + b)
*/
func vlfw(a, b string, n int) byte {
if n < len(b) {
return b[n]
}
return vlfw(b, b+a, n)
}
|
package main
import "fmt"
type person struct {
name string
age uint
add address
}
type address struct {
province string
city string
}
func main() {
var p person
p = person{name: "josiah", age: 26, add: address{
province: "ss",
city: "afds",
}}
fmt.Print(p)
}
|
package main
func FindSumOfEvens(max int) int {
sum := 0
current := 0
prev := 0
next := 1
for current < max {
current = prev + next
prev = next
next = current
if current%2 == 0 {
sum += current
}
}
return sum
}
func main() {
}
|
package main
import (
"github.com/jhabc1314/day/archive_go"
"github.com/jhabc1314/day/bufio"
"github.com/jhabc1314/day/builtin"
"github.com/jhabc1314/day/bytes"
"github.com/jhabc1314/day/container"
"github.com/jhabc1314/day/crypto/cipher"
"github.com/jhabc1314/day/crypto/md5"
"github.com/jhabc1314/day/crypto/rand"
)
//单引号则用于表示Golang的一个特殊类型:rune,类似其他语言的byte但又不完全一样,是指:码点字面量(Unicode code point),不做任何转义的原始内容
func main() {
archive_go.Tar()
archive_go.Untar("./cache/output.tar")
archive_go.Zip()
archive_go.Unzip("./cache/output.zip")
bufio.Read("./tar_file1.txt")
bufio.Write()
builtin.Builtin()
bytes.Byte()
h := container.IntHeap{9,8,11,2,3,5,7,7,15}
container.HeapFunc(&h) //有序的队列,插入进去自动会排序
container.ListFunc()
md5.Md5Demo()
cipher.Encrypt()
cipher.Decrypt()
rand.RandDemo()
}
|
package smallNet
import (
"fmt"
"net"
"scommon"
)
type tcpClientSessionManager struct {
_maxSessionCount int
_curSessionCount int
_netConf NetworkConfig
_pktRecvFunc PacketReceivceFunctors
_sessionList []*tcpSession // 멀티스레드에서 호출된다
_sessionIndexPool *scommon.Deque
}
func newClientSessionManager(config NetworkConfig,
pktRecvFunc PacketReceivceFunctors) *tcpClientSessionManager {
sessionMgr := new(tcpClientSessionManager)
sessionMgr._pktRecvFunc = pktRecvFunc
sessionMgr._initialize(config)
return sessionMgr
}
func (mgr *tcpClientSessionManager) stop() {
mgr._forceCloseAllSession()
}
func (mgr *tcpClientSessionManager) sendPacket(sessionIndex int, sendData []byte) bool {
session, result := mgr.findSession(sessionIndex)
if result == false || session.isEnableSend() == false {
return false
}
session.sendPacket(sendData)
return true
}
func (mgr *tcpClientSessionManager) sendPacketAllClient(sendData []byte) {
for i := 0; i < mgr._maxSessionCount; i++ {
session := mgr._sessionList[i]
if session.isEnableSend() == false {
continue
}
session.sendPacket(sendData)
}
}
func (mgr *tcpClientSessionManager) forceDisconnectClient(sessionIndex int) {
session, result := mgr.findSession(sessionIndex)
if result == false || session.isEnableSend() == false {
return
}
session.closeSocket(sessionCloseForce)
}
func (mgr *tcpClientSessionManager) setDisablePacketProcessClient(sessionIndex int) {
session, result := mgr.findSession(sessionIndex)
if result == false || session.isEnableSend() == false {
return
}
session.setDisablePacketProcess()
}
func (mgr *tcpClientSessionManager) setDisableSend(sessionIndex int) {
if session, result := mgr.findSession(sessionIndex); result {
session.setDisableSend()
}
}
func (mgr *tcpClientSessionManager) setEnableSend(sessionIndex int) {
if session, result := mgr.findSession(sessionIndex); result {
session.setEnableSend()
}
}
func (mgr *tcpClientSessionManager) _initialize(config NetworkConfig) {
mgr._netConf = config
mgr._maxSessionCount = config.MaxSessionCount
mgr._curSessionCount = 0
mgr._createSessionPool()
}
func (mgr *tcpClientSessionManager) _createSessionPool() {
mgr._sessionList = make([]*tcpSession, mgr._maxSessionCount)
mgr._sessionIndexPool = scommon.NewCappedDeque((int)(mgr._maxSessionCount))
for i := 0; i < (int)(mgr._maxSessionCount); i++ {
mgr._sessionList[i] = new(tcpSession)
mgr._sessionList[i].initialize(i, true, mgr._netConf)
mgr._freeSessionObj(i)
}
}
func (mgr *tcpClientSessionManager) _connectedSessionCount() int {
return mgr._curSessionCount
}
func (mgr *tcpClientSessionManager) _incConnectedSessionCount() {
mgr._curSessionCount++
}
func (mgr *tcpClientSessionManager) _decConnectedSessionCount() {
mgr._curSessionCount--
}
func (mgr *tcpClientSessionManager) _validIndex(index int) bool {
if index < 0 || index >= mgr._maxSessionCount {
return false
}
return true
}
func (mgr *tcpClientSessionManager) findSession(sessionIndex int) (*tcpSession, bool) {
if mgr._validIndex(sessionIndex) == false {
return nil, false
}
session := mgr._sessionList[sessionIndex]
if session == nil {
return nil, false
}
return session, true
}
func (mgr *tcpClientSessionManager) newSession(tcpconn *net.TCPConn) int {
newSession := mgr._allocSessionObj()
if newSession == nil {
scommon.LogError(fmt.Sprintf("[tcpClientSessionManager._newSession] empty SessionObj"))
_ = tcpconn.Close()
return -1
}
index := newSession.getIndex()
newSession.clear()
newSession.onConnect(tcpconn)
newSession.settingTCPSocketOption(int(mgr._netConf.SockReadbuf), int(mgr._netConf.SockWritebuf))
go newSession.handleReceive_goroutine(mgr._netConf, mgr._pktRecvFunc)
return index
}
func (mgr *tcpClientSessionManager) deleteSession(sessionIndex int) {
if session, ret := mgr.findSession(sessionIndex); ret == true {
session.setDisableSend()
mgr._decConnectedSessionCount()
session.setStateClosed()
mgr._freeSessionObj(sessionIndex)
}
}
func (mgr *tcpClientSessionManager) _allocSessionObj() *tcpSession {
item := mgr._sessionIndexPool.First()
if item == nil {
return nil
}
sessionIndex := item.(int)
data := mgr._sessionList[sessionIndex]
_ = mgr._sessionIndexPool.Shift()
scommon.LogTrace(fmt.Sprintf("[tcpClientSessionManager] _allocSessionObj(%d)", sessionIndex))
return data
}
func (mgr *tcpClientSessionManager) _freeSessionObj(sessionIndex int) {
if useCount, ok := mgr._sessionIndexPool.Append(sessionIndex); ok {
scommon.LogTrace(fmt.Sprintf("[tcpClientSessionManager] _freeSessionObj. sessionIndex(%d)UseCount( %d )",
sessionIndex, useCount))
} else {
scommon.LogError(fmt.Sprintf("[tcpClientSessionManager] _freeSessionObj( %d )", sessionIndex))
return
}
}
func (mgr *tcpClientSessionManager) _forceCloseAllSession() {
scommon.LogInfo("_forceCloseAllSession - start")
for _, session := range mgr._sessionList {
if session == nil {
continue
}
session.closeSocket(sessionCloseAllSession)
}
scommon.LogInfo("_forceCloseAllSession - end")
}
|
package main
import "fmt"
func vals(a int, b int) (int, int) {
return a, b
}
func main() {
a, b := vals(3, 5)
fmt.Println("return value:", a, b)
_, c := vals(7, 11)
fmt.Println("return value:", c)
}
|
package main
import (
"net/http"
// "encoding/json"
"log"
"github.com/gorilla/mux"
"github.com/hendrikhoffmann/smartfblib"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/switchon", smartfblib.SwitchOn).Methods("GET")
router.HandleFunc("/switchoff", smartfblib.SwitchOff).Methods("GET")
router.HandleFunc("/switchchannel/{channel}", smartfblib.SwitchChannel).Methods("GET")
router.HandleFunc("/setvolume/{volume}", smartfblib.SetVolume).Methods("GET")
log.Fatal(http.ListenAndServe(":3000", router))
}
//import "golang.org/x/net/websocket"
//Websocket Communication Postponed
// http.Handle("/switchon", websocket.Handler(func(ws *websocket.Conn) {
// ws.Write([]byte(smartfblib.SwitchOn()))
// }))
// http.ListenAndServe(":3000", nil)
|
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/pingcap/log"
"github.com/spf13/cobra"
"go.uber.org/zap"
)
func main() {
gCtx := context.Background()
ctx, cancel := context.WithCancel(gCtx)
defer cancel()
sc := make(chan os.Signal, 1)
signal.Notify(sc,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
go func() {
sig := <-sc
fmt.Printf("\nGot signal [%v] to exit.\n", sig)
log.Warn("received signal to exit", zap.Stringer("signal", sig))
cancel()
fmt.Fprintln(os.Stderr, "gracefully shuting down, press ^C again to force exit")
<-sc
// Even user use SIGTERM to exit, there isn't any checkpoint for resuming,
// hence returning fail exit code.
os.Exit(1)
}()
rootCmd := &cobra.Command{
Use: "br",
Short: "br is a TiDB/TiKV cluster backup restore tool.",
TraverseChildren: true,
SilenceUsage: true,
}
AddFlags(rootCmd)
SetDefaultContext(ctx)
rootCmd.AddCommand(
NewDebugCommand(),
NewBackupCommand(),
NewRestoreCommand(),
NewStreamCommand(),
newOpeartorCommand(),
)
// Outputs cmd.Print to stdout.
rootCmd.SetOut(os.Stdout)
rootCmd.SetArgs(os.Args[1:])
if err := rootCmd.Execute(); err != nil {
cancel()
log.Error("br failed", zap.Error(err))
os.Exit(1) // nolint:gocritic
}
}
|
package rabbitmq
import (
"fmt"
"queueman/libs/queue/types"
"queueman/libs/request"
"queueman/libs/statistic"
"strings"
"time"
amqpReconnect "github.com/isayme/go-amqp-reconnect/rabbitmq"
log "github.com/sirupsen/logrus"
"github.com/streadway/amqp"
)
// Dispatcher for Queue
func (queue *Queue) Dispatcher(combineConfig interface{}) {
if cc, ok := combineConfig.(CombineConfig); ok {
for _, queueConfig := range cc.Queues {
if queueConfig.IsEnabled {
queueConfig.SourceType = "RabbitMQ"
// enabledTotal++ todo
qi := &QueueInstance{
Source: cc.Config,
Queue: queueConfig,
}
go qi.QueueHandle()
}
}
} else {
log.WithFields(log.Fields{
"queueConfig": combineConfig,
}).Warn("Not correct rabbitmq config")
return
}
}
// GetConnection get a connect to source
func (qi *QueueInstance) GetConnection() (*amqpReconnect.Connection, error) {
conn, err := qi.Source.GetConnection()
if nil != err {
log.WithFields(log.Fields{
"error": err,
}).Warn("Can not connect to rabbitmq")
return nil, err
}
return conn, nil
}
// QueueHandle handle Normal or Delay queue
func (qi *QueueInstance) QueueHandle() {
if qi.Queue.Concurency < 1 {
log.WithFields(log.Fields{
"queueName": qi.Queue.QueueName,
}).Warn("configure file of queue must have Concurency configure !!!")
return
}
// process main queue
// get the delay time
delayTime := 0
if len(qi.Queue.DelayOnFailure) > 0 {
delayTime = qi.Queue.DelayOnFailure[0]
}
// first process delay queue
totalDelays := len(qi.Queue.DelayOnFailure)
if totalDelays > 0 {
go qi.ProcessDelay("retry")
}
// wait ProcessDelay finished (to finished delay queue bind exchange queue)
time.Sleep(1 * time.Second)
if false == qi.Queue.IsDelayQueue {
go qi.ProcessNormal(delayTime)
} else {
go qi.ProcessDelay("first")
}
}
// ProcessNormal get a data from queue and dispatch
func (qi *QueueInstance) ProcessNormal(delayTime int) {
conn, err := qi.GetConnection()
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
// ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args Table) error
err = ch.ExchangeDeclare(qi.Queue.ExchangeName, qi.Queue.ExchangeType, qi.Queue.IsDurable, false, false, false, nil)
failOnError(err, "Failed to Declare a exchange")
// QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args Table) (Queue, error)
q, err := ch.QueueDeclare(
qi.Queue.QueueName, // name
qi.Queue.IsDurable, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue"+q.Name)
// QueueBind(name, key, exchange string, noWait bool, args Table) error
err = ch.QueueBind(qi.Queue.QueueName, qi.Queue.RoutingKey, qi.Queue.ExchangeName, false, nil)
failOnError(err, "Failed to bind a queue")
// auto-ack exclusive
// Consume(queue, consumer string, autoAck, exclusive, noLocal, noWait bool, args Table) (<-chan Delivery, error)
msgs, err := ch.Consume(
qi.Queue.QueueName, // queue
qi.Queue.ConsumerTag, // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "Failed to register a consumer")
log.Printf("Start consume ( %s %s) queue (%s) from Exchange (%s) Vhost (%s)", qi.Queue.SourceType, qi.Source.Type, qi.Queue.QueueName, qi.Queue.ExchangeType, conn.Config.Vhost)
// control the concurency
concurency := make(chan bool, qi.Queue.Concurency)
for delivery := range msgs {
// control the concurency
concurency <- true
// dispatch to URLs
go func(d amqp.Delivery) {
queueData := string(d.Body)
queueRequest := &request.QueueRequest{
QueueName: qi.Queue.QueueName,
DispatchURL: qi.Queue.DispatchURL,
DispatchTimeout: qi.Queue.DispatchTimeout,
QueueData: queueData,
}
result, err := queueRequest.Post()
status := ""
if qi.Queue.IsAutoAck {
d.Ack(false)
status = "Auto acked"
statistic.IncrSuccessCounter(qi.Queue.QueueName)
} else {
// failure
if 1 != result.Code {
log.WithFields(log.Fields{
"err": err,
"Message": result.Message,
"queueName": qi.Queue.QueueName,
"delayTime": delayTime,
}).Warn("Request data result")
nextDelayTime := delayTime
if nextDelayTime > 0 {
serializeDelayQueueData, err := types.SerializeDelayQueueData(queueData, nextDelayTime)
if nil != err {
log.WithFields(log.Fields{
"error": err,
"Message": result.Message,
}).Warn("Serialize DelayQueueData error")
d.Ack(false) // when a error occur acked
statistic.IncrFailureCounter(qi.Queue.QueueName)
<-concurency // remove control
return
}
queueNameDelay := fmt.Sprintf("%s.delayed", qi.Queue.QueueName)
routingKeyDelay := fmt.Sprintf("%s.delayed", qi.Queue.RoutingKey)
exchangeNameDelay := fmt.Sprintf("%s.delayed", qi.Queue.ExchangeName)
// when fail push queue data to first delay queue
header := amqp.Table{"x-delay": nextDelayTime * 1000}
if "aliyun" == strings.ToLower(qi.Source.Type) {
header = amqp.Table{"delay": nextDelayTime * 1000}
}
var deliveryMode uint8 = 1 // Transient (0 or 1) or Persistent (2)
if qi.Queue.IsDurable {
deliveryMode = 2
}
err = ch.Publish(
exchangeNameDelay, // exchange
routingKeyDelay, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
Headers: header,
ContentType: "text/plain",
Body: serializeDelayQueueData,
DeliveryMode: deliveryMode,
})
if nil != err {
log.WithFields(log.Fields{
"error": err,
"queueName": queueNameDelay,
"exchangeName": exchangeNameDelay,
}).Warn("Publish to rabbitmq failure")
}
status = "Normal Delayed"
log.WithFields(log.Fields{
"status": status,
"queueName": queueNameDelay,
"exchangeName": exchangeNameDelay,
"routingKeyDelay": routingKeyDelay,
"trigglerTime": time.Now().Add(time.Duration(nextDelayTime) * time.Second),
}).Info("Delayed to queue")
} else {
status = "Normal Failure"
statistic.IncrFailureCounter(qi.Queue.QueueName)
}
d.Ack(false)
} else {
status = "Normal Acked"
statistic.IncrSuccessCounter(qi.Queue.QueueName)
d.Ack(false)
}
}
log.WithFields(log.Fields{
"status": status,
"queueName": qi.Queue.QueueName,
"queueData": queueData,
}).Info("Messages from queue")
<-concurency // remove control
}(delivery)
}
}
// ProcessDelay to deal with delay queue
func (qi *QueueInstance) ProcessDelay(runMode string) {
queueName := ""
queueNameDelay := ""
routingKey := ""
routingKeyDelay := ""
exchangeName := ""
exchangeNameDelay := ""
if "retry" == runMode {
queueName = fmt.Sprintf("%s.delayed", qi.Queue.QueueName)
routingKey = fmt.Sprintf("%s.delayed", qi.Queue.RoutingKey)
exchangeName = fmt.Sprintf("%s.delayed", qi.Queue.ExchangeName)
queueNameDelay = queueName
routingKeyDelay = routingKey
exchangeNameDelay = exchangeName
} else {
// if runMode is first means it is the main delay queue
queueName = qi.Queue.QueueName
routingKey = qi.Queue.RoutingKey
exchangeName = qi.Queue.ExchangeName
queueNameDelay = fmt.Sprintf("%s.delayed", qi.Queue.QueueName)
routingKeyDelay = fmt.Sprintf("%s.delayed", qi.Queue.RoutingKey)
exchangeNameDelay = fmt.Sprintf("%s.delayed", qi.Queue.ExchangeName)
}
conn, err := qi.GetConnection()
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
// all queue is delay below ProcessDelay function
// ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args Table) error
if "aliyun" != strings.ToLower(qi.Source.Type) {
err = ch.ExchangeDeclare(exchangeName, "x-delayed-message", qi.Queue.IsDurable, false, false, false, amqp.Table{"x-delayed-type": "direct"})
} else {
err = ch.ExchangeDeclare(exchangeName, qi.Queue.ExchangeType, qi.Queue.IsDurable, false, false, false, nil)
}
failOnError(err, "Failed to Declare a exchange")
// QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args Table) (Queue, error)
q, err := ch.QueueDeclare(
queueName, // name
qi.Queue.IsDurable, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue"+q.Name)
// QueueBind(name, key, exchange string, noWait bool, args Table) error
err = ch.QueueBind(queueName, routingKey, exchangeName, false, nil)
failOnError(err, "Failed to bind a queue")
// auto-ack exclusive
// Consume(queue, consumer string, autoAck, exclusive, noLocal, noWait bool, args Table) (<-chan Delivery, error)
msgs, err := ch.Consume(
queueName, // queue
qi.Queue.ConsumerTag, // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "Failed to register a consumer")
log.Printf("Start consume ( %s %s) queue (%s) from Exchange (%s) Vhost (%s)", qi.Queue.SourceType, qi.Source.Type, queueName, qi.Queue.ExchangeType, conn.Config.Vhost)
// control the concurency
concurency := make(chan bool, qi.Queue.Concurency)
for delivery := range msgs {
// control the concurency
concurency <- true
// dispatch to URLs
go func(d amqp.Delivery) {
queueData, nextDelayTime, delayTime, err := types.UnserializeDelayQueueData(runMode, string(d.Body), qi.Queue.DelayOnFailure)
if nil != err {
log.WithFields(log.Fields{
"error": err,
"queueName": queueName,
"exchangeName": exchangeName,
}).Warn("DelayPop Unmarshal error")
<-concurency // remove control
return
}
log.WithFields(log.Fields{
"queueName": queueName,
"queueData": queueData,
}).Info("Queue data")
queueRequest := &request.QueueRequest{
QueueName: qi.Queue.QueueName,
DelayQueueName: queueName,
DispatchURL: qi.Queue.DispatchURL,
DispatchTimeout: qi.Queue.DispatchTimeout,
QueueData: queueData,
}
result, err := queueRequest.Post()
status := ""
if qi.Queue.IsAutoAck {
d.Ack(false)
status = "Auto acked"
statistic.IncrSuccessCounter(qi.Queue.QueueName)
} else {
// failure
if 1 != result.Code {
log.WithFields(log.Fields{
"err": err,
"Message": result.Message,
"queueName": queueName,
"nextDelayTime": nextDelayTime,
"delayTime": delayTime,
}).Warn("Request data result")
if nextDelayTime > 0 {
serializeDelayQueueData, err := types.SerializeDelayQueueData(queueData, nextDelayTime)
if nil != err {
log.WithFields(log.Fields{
"error": err,
"Message": result.Message,
}).Warn("Serialize DelayQueueData error")
d.Ack(false) // when a error occur acked
statistic.IncrFailureCounter(qi.Queue.QueueName)
<-concurency // remove control
return
}
// when fail push queue data to first delay queue
header := amqp.Table{"x-delay": (nextDelayTime - delayTime) * 1000}
if "aliyun" == strings.ToLower(qi.Source.Type) {
header = amqp.Table{"delay": (nextDelayTime - delayTime) * 1000}
}
var deliveryMode uint8 = 1 // Transient (0 or 1) or Persistent (2)
if qi.Queue.IsDurable {
deliveryMode = 2
}
err = ch.Publish(
exchangeNameDelay, // exchange
routingKeyDelay, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
Headers: header,
ContentType: "text/plain",
Body: serializeDelayQueueData,
DeliveryMode: deliveryMode,
})
if nil != err {
log.WithFields(log.Fields{
"error": err,
"queueName": queueNameDelay,
"exchangeName": exchangeNameDelay,
}).Warn("Publish to rabbitmq failure")
}
status = "Delayed"
log.WithFields(log.Fields{
"status": status,
"queueName": queueNameDelay,
"exchangeName": exchangeNameDelay,
"routingKeyDelay": routingKeyDelay,
"trigglerTime": time.Now().Add(time.Duration(nextDelayTime-delayTime) * time.Second),
}).Info("Delayed to queue")
} else {
status = "Failure"
statistic.IncrFailureCounter(qi.Queue.QueueName)
}
d.Ack(false) // we alrealy pushed failure message to delay queue, so mark as acked
} else {
status = "Success"
statistic.IncrSuccessCounter(qi.Queue.QueueName)
d.Ack(false)
}
}
log.WithFields(log.Fields{
"status": status,
"queueName": queueName,
"queueData": queueData,
}).Info("Messages from queue")
<-concurency // remove control
}(delivery)
}
}
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}
|
package main
import (
"fmt"
"log"
"net/http"
"os"
"regexp"
"strconv"
"sync"
)
var wg3 sync.WaitGroup
func init() {
log.SetFlags(log.Lshortfile)
}
func main() {
start, end := user()
spiderEngine1(start, end)
}
func user() (start, end int) {
retry:
fmt.Print("起始页 start(>=1) = ")
fmt.Scan(&start)
fmt.Print("终止页 start(>1) = ")
fmt.Scan(&end)
if start >= 1 && end > start {
return
}
fmt.Println("你是不是傻?")
goto retry
}
func spiderEngine1(start, end int) {
wg3.Add(end - start)
for i := start; i < end; i++ {
go spider1(i)
}
wg3.Wait()
}
func spider1(i int) {
defer wg3.Done()
fmt.Printf("爬取第 %d 页\n", i)
pn := strconv.Itoa(i)
url := "https://www.pengfu.com/xiaohua_" + pn + ".html"
res, err := http.Get(url)
if err != nil {
log.Fatalln(err)
}
recByts := make([]byte, 1024*100)
_, err = res.Body.Read(recByts)
defer res.Body.Close()
if err != nil {
log.Fatalln(err)
}
spiderRE(recByts, pn)
}
func spiderRE(recByts []byte, pn string) {
fmt.Printf("处理第 %s 页数据\n", pn)
expr := `<h1 class="dp-b"><a href="https://www.pengfu.com/content_\d+?_1.html" target="_blank">(?s:(.+?))</a>(?s:.+?)</h1>(?s:.+?)<div class="content-img clearfix pt10 relative">(?s:.+?)(?s:(.+?))</div>`
re, err := regexp.Compile(expr)
if err != nil {
log.Fatalln(err)
}
recStr := fmt.Sprintf("%s", recByts)
recSli := re.FindAllStringSubmatch(recStr, -1)
f, err := os.Create("D:\\workspace\\go\\learnGo\\itcast\\src\\01_20H\\day08_HTTP编程\\tempFile\\" + pn + ".txt")
defer f.Close()
for _, sli := range recSli {
if err != nil {
log.Fatalln(err)
}
f.WriteString(fmt.Sprintf("%s\n%s\n", sli[1], sli[2]))
f.WriteString("=======================================================================================\n")
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.