小编Jim*_*imB的帖子

我可以启动一个脚本,因此它独立于Linux上的父进程吗?

有没有办法从另一个进程启动脚本,以便如果进程死亡/结束,脚本仍然继续?

setuid会这样做吗?如果我要将所有者设置为root,然后启动脚本?

例如,如果我有一些PHP代码启动脚本,但httpd死亡或被杀死,我认为它需要我的脚本.有没有解决的办法?

具体来说,我使用的是Apache 2和PHP 5的Fedora 10.

php linux scripting daemon process

4
推荐指数
1
解决办法
3154
查看次数

使用crypto/ssh的golang scp文件

我正在尝试通过 ssh 下载远程文件以下方法在 shell 上工作正常

ssh hostname "tar cz /opt/local/folder" > folder.tar.gz
Run Code Online (Sandbox Code Playgroud)

然而,golang 上的相同方法在输出工件大小方面存在一些差异。例如,与纯 shell 相同的文件夹产生工件 gz 文件 179B,与 go script 178B 相同。我认为 io.Reader 中遗漏了一些东西,或者 session 更早关闭了。恳请各位大侠帮忙。

这是我的脚本示例:

func executeCmd(cmd, hostname string, config *ssh.ClientConfig, path string) error {
    conn, _ := ssh.Dial("tcp", hostname+":22", config)
    session, err := conn.NewSession()
    if err != nil {
        panic("Failed to create session: " + err.Error())
    }

    r, _ := session.StdoutPipe()
    scanner := bufio.NewScanner(r)

    go func() {
        defer session.Close()

        name := fmt.Sprintf("%s/backup_folder_%v.tar.gz", path, time.Now().Unix())
        file, err …
Run Code Online (Sandbox Code Playgroud)

ssh scp go

4
推荐指数
1
解决办法
8224
查看次数

不可变的字符串和指针地址

在Go 规范中写道:

字符串是不可变的:一旦创建,就不可能改变字符串的内容.

我有以下代码:

str := "hello"
fmt.Printf("%p\n",&str) // 0x1040c128
fmt.Printf("%v\n",str) // hello
ptr := &str
*ptr = "world"
fmt.Printf("%p\n",&str) // 0x1040c128
fmt.Printf("%v\n",str) // world  
Run Code Online (Sandbox Code Playgroud)

&str原本预计地址会改变*ptr = "world".正如Java所发生的那样,我们重新分配字符串引用.

什么是"不变性"?

string immutability go

4
推荐指数
1
解决办法
433
查看次数

我想检查记录是否存在,如果不存在,那么我想使用 golang 将该记录插入到数据库中

package main

import (
    "database/sql"
    "fmt"

    "github.com/gin-gonic/gin"
)

func main() {

    router := gin.New()
    router.Use(gin.Logger())
    router.Use(gin.Recovery())
    db, err := sql.Open("mysql", "root:password@tcp(gpstest.cksiqniek8yk.ap-south-1.rds.amazonaws.com:3306)/tech")
    if err != nil {
        fmt.Print(err.Error())
    }
    err = db.Ping()
    if err != nil {
        fmt.Print(err.Error())
    }
    rows, err := db.Query("select sum(usercount) as usercount from ( select count(*) as usercount from category where name = 'construction' union all  select count(*) as usercount from sub_category where name = 'construction'  union all  select count(*) as usercount from industry where name = …
Run Code Online (Sandbox Code Playgroud)

mysql go

4
推荐指数
1
解决办法
1万
查看次数

如何使用 gorm 进行单元测试

我是Go和的新人unit test。在我的项目中,我使用Gogorm连接mysql数据库。

我的疑问是如何对我的代码进行单元测试:

我的代码如下(main.go):

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "strconv"
    "time"

    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

type Jobs struct {
    JobID                  uint   `json: "jobId" gorm:"primary_key;auto_increment"`
    SourcePath             string `json: "sourcePath"`
    Priority               int64  `json: "priority"`
    InternalPriority       string `json: "internalPriority"`
    ExecutionEnvironmentID string `json: "executionEnvironmentID"`
}

type ExecutionEnvironment struct {
    ID                     uint      `json: "id" gorm:"primary_key;auto_increment"`
    ExecutionEnvironmentId string    `json: "executionEnvironmentID"`
    CloudProviderType      string    `json: "cloudProviderType"`
    InfrastructureType     string    `json: "infrastructureType"`
    CloudRegion            string    `json: "cloudRegion"`
    CreatedAt …
Run Code Online (Sandbox Code Playgroud)

unit-testing go go-gorm

4
推荐指数
1
解决办法
1万
查看次数

高朗的生产者消费者

尝试运行以下代码(生产者和使用者)以了解golang中的goroutine和通道(从下面的代码片段中删除了包和导入):

var done = make(chan bool)
var msgs = make(chan int)

func produce() {
    for i := 0; i < 10; i++ {
            msgs <- i
    }
    fmt.Println("Before closing channel")
    close(msgs)
    fmt.Println("Before passing true to done")
    done <- true
}

func consume() {
    for {
            msg := <-msgs
            time.Sleep(100 * time.Millisecond)
            fmt.Println("Consumer: ", msg)
    }
}

func main() {
    go produce()
    go consume()
    <-done
    fmt.Println("After calling DONE")
}
Run Code Online (Sandbox Code Playgroud)

源代码来自:http : //www.golangpatterns.info/concurrency/producer-consumer

下面是我运行代码时的输出

Consumer:  0
Consumer:  1
Consumer:  2
Consumer: …
Run Code Online (Sandbox Code Playgroud)

go goroutine

3
推荐指数
1
解决办法
4492
查看次数

Golang 从 NodeJS 解密 AES 256 CBC base64

这是我在 Node.js 中所拥有的:

var crypto = require('crypto')

function encryptstring(str) {
    var cipher = crypto.createCipheriv('aes-256-cbc', 'NFd6N3v1nbL47FK0xpZjxZ7NY4fYpNYd', 'TestingIV1234567'),
        encrypted = cipher.update(str, 'utf-8', 'base64');
    encrypted += cipher.final('base64');
    return encrypted;
}

console.log(encryptstring("Testing 111111111111111111111111111111111111111111"))
Run Code Online (Sandbox Code Playgroud)

那返回: w2f0vBP2hRfgVqssqOluk68Qxkc9LXFESc0ZGzPBq3p6f/x/LbwBbg1XOoRr7I/DAtESJGdweKG6nL9m8RfewA==

这是我在 Go 中所拥有的:

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "fmt"
)

// decrypt from base64 to decrypted string
func decrypt(key []byte, iv []byte, cryptoText string) string {
    ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)
    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }
    if len(ciphertext) < aes.BlockSize {
        panic("ciphertext …
Run Code Online (Sandbox Code Playgroud)

encryption go node.js

3
推荐指数
1
解决办法
2635
查看次数

替换字符串中除最后4个字符以外的所有字符

使用Go,除了最后4个字符外,如何用"X"替换字符串中的所有字符?

这适用于php/javascript但不适用于golang,因为不支持"?=".

\w(?=\w{4,}$)
Run Code Online (Sandbox Code Playgroud)

试过这个,但不起作用.我找不到任何类似golang的东西

(\w)(?:\w{4,}$)
Run Code Online (Sandbox Code Playgroud)

JavaScript工作链接

去非工作链接

regex string replace substring go

3
推荐指数
1
解决办法
1477
查看次数

Go HTTP 表单解析 - 返回空切片/空值?

我用 Go 编写了一个简单的 Web 应用程序,需要读取 HTTP 表单的值(用户名、密码)等。但是,我发现打印时这些值是空的。len(r.Form)并且len(r.Form["password"])都返回 0。

r.ParseForm()在尝试读取字段之前我已经调用了应用程序,并且我正在使用 Postman 发送请求。在 Linux 和 macOS 上进行了测试。

我用来测试的代码是 Astaxie golang Web 教程中的一些示例代码。我已附上我的邮递员请求。到目前为止看起来像这样:

package main

import (
    "fmt"
    "html/template"
    "log"
    "net/http"
    "strings"
    "time"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {
    r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body)
    // attention: If you do not call ParseForm method, the following data can not be obtained form
    fmt.Println(r.Form) // print …
Run Code Online (Sandbox Code Playgroud)

forms parsing http go

2
推荐指数
1
解决办法
2795
查看次数

转到另一个包中的函数定义

我读这个岗位约time.startTimer声明和定义。

从答案中,time.startTimer的声明src/time/sleep.go 如下:

func startTimer(*runtimeTimer)
Run Code Online (Sandbox Code Playgroud)

其定义src/runtime/time.go如下:

func startTimer(t *timer) {
    if raceenabled {
        racerelease(unsafe.Pointer(t))
    }
    addtimer(t)
}
Run Code Online (Sandbox Code Playgroud)

因此,似乎可以在一个.go文件中声明一个函数,然后在另一个.go文件中实现该函数。我尝试了相同的方法,例如,在a.go中声明了一个函数并在b.go中实现了该函数,但是当时,它总是失败go run a.go。这是正确的方法吗?如何声明在另一个.go文件中实现的功能?或中没有import任何内容。Go如何做到?sleep.gotime.go

谢谢

declaration function go

2
推荐指数
1
解决办法
151
查看次数