小编Cer*_*món的帖子

如何使用 Go 的 text/template 包返回数组中的唯一元素?

我是 Go 新手,我正在努力寻找一种从 Go 模板语言中的数组返回唯一变量的方法。这是为了配置一些软件,我无法访问源代码来更改实际程序,只能更改模板。

我在 Go 操场上举了一个例子:

https://play.golang.org/

package main

import "os"
import "text/template"

func main() {

      var arr [10]string
      arr[0]="mice"
      arr[1]="mice"
      arr[2]="mice"
      arr[3]="mice"
      arr[4]="mice"
      arr[5]="mice"
      arr[6]="mice"
      arr[7]="toad"
      arr[8]="toad"
      arr[9]="mice"

      tmpl, err := template.New("test").Parse("{{range $index, $thing := $}}The thing is: {{$thing}}\n{{end}}")
      if err != nil { panic(err) }
      err = tmpl.Execute(os.Stdout, arr)
      if err != nil { panic(err) }

}
Run Code Online (Sandbox Code Playgroud)

现在返回:

The thing is: mice
The thing is: mice
The thing is: mice
The thing is: mice
The thing …
Run Code Online (Sandbox Code Playgroud)

go

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

为什么地图中没有键

我创建了一张地图:

l := make(map[*A]string)
Run Code Online (Sandbox Code Playgroud)

其中A是:

type A struct{}
Run Code Online (Sandbox Code Playgroud)

然后在其中添加键值:

a1 := &A{}
a2 := &A{}
a3 := &A{}

l[a1] = "a1"
l[a2] = "a2"
l[a3] = "a3"
Run Code Online (Sandbox Code Playgroud)

我希望在做的时候看到所有的值("a1","a2","a3") range

for k, v := range l{
    fmt.Println(k, v)
}
Run Code Online (Sandbox Code Playgroud)

但我只看到最后一个.

为什么会这样? https://play.golang.org/p/GSdUWzExxLK

dictionary go

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

在Go中声明变量

Go文档表明应该使用速记:

x := "Hello World" 
Run Code Online (Sandbox Code Playgroud)

而不是长形式

var x string = "Hello World"
Run Code Online (Sandbox Code Playgroud)

提高可读性.虽然以下工作:

package main   
import "fmt"
var x string = "Hello World"
func main() {
    fmt.Println(x)
}
Run Code Online (Sandbox Code Playgroud)

这不是:

package main
import "fmt"
x := "Hello World"
func main() {
    fmt.Println(x)
}
Run Code Online (Sandbox Code Playgroud)

并给出错误"函数体外的非声明语句".相反,我在函数中声明它:

package main
import "fmt"
func main() {
   x := "Hello World"
   fmt.Println(x)
}
Run Code Online (Sandbox Code Playgroud)

然后它工作得很好.看来我只能在使用变量的函数中使用简写.是这样的吗?谁能告诉我为什么?

go variable-declaration

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

在 Go 中对 Gob 数据使用 Snappy 压缩?

我需要将一个结构保存到磁盘并稍后再次读取它,我试图将 IO 降至最低,但也不会花费很长时间来压缩和解压缩文件,所以我打算使用 Snappy 进行压缩,因为它非常快并且相对高效。

通常我会在将 gob 保存到文件时对其进行 gzip 压缩,如下所示:

func (t *Object) Save(filename string) error {
    // Open file for writing
    fi, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer fi.Close()
    // Attach gzip writer
    fz := gzip.NewWriter(fi)
    defer fz.Close()
    // Push from the gob encoder
    encoder := gob.NewEncoder(fz)
    err = encoder.Encode(t.Classifier)
    if err != nil {
        return err
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

但是 Snappy 并没有附加到其他所有东西似乎都在使用的这些 Reader/Writer 接口上。相反,它只提供基本功能:https : //godoc.org/code.google.com/p/snappy-go/snappy

func Encode(dst, src []byte) …

go gob

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

使用 Go 解析 HTML

我正在尝试使用 Go 构建一个网络爬虫,我对这门语言相当陌生,我不确定在使用 html 解析器时我做错了什么。我正在尝试解析 html 以查找锚标记,但我不断收到 html.TokenTypeEnd 。

package main

import (
    "fmt"
    "golang.org/x/net/html"
    "io/ioutil"
    "net/http"
)

func GetHtml(url string) (text string, resp *http.Response, err error) {
    var bytes []byte
    if url == "https://www.coastal.edu/scs/employee" {
        resp, err = http.Get(url)
        if err != nil {
            fmt.Println("There seems to ben an error with the Employee Console.")
        }
        bytes, err = ioutil.ReadAll(resp.Body)
        if err != nil {
            fmt.Println("Cannot read byte response from Employee Console.")
        }
        text = string(bytes)
    } else {
        fmt.Println("Issue …
Run Code Online (Sandbox Code Playgroud)

html go html-parsing web-scraping

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

如何下载Go的最新版本

如何在不知道最新版本的确切版本号的情况下找到Go的最新版本号?这是为了构建下载URL.

当发布在GitHub上时,我可以使用例如

curl -s "https://api.github.com/repos/nagios-plugins/nagios-plugins/releases/latest" | jq -r '.assets[] | .browser_download_url')
Run Code Online (Sandbox Code Playgroud)

但由于下载网址不在GitHub上,而是在https://golang.org/dl/上,我很想知道如何找到最新的Go版本号.

bash shell automation go

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

Go xml.Marshal返回无效字符

我使用下面的代码生成字符串str的XML编码:

str := string([]byte{0x01})
marshalBytes, _ := xml.Marshal(str)
fmt.Println(string(marshalBytes)) // output: <string>?</string>; ? is [239 191 189] in bytes.
Run Code Online (Sandbox Code Playgroud)

显然, 不等于0x01.

我该如何解决?

xml encoding go

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

使用 Go 自定义 404 错误消息

我有这个代码,如果我去 /time/ 会给出我的自定义 404 错误消息,但如果我去 /times/ 或只是 / 或 /whatever 然后我会得到默认的 404 错误消息。我想为除 /time/ 以外的所有情况显示我的自定义 404

package main

import (
        "fmt"
        "time"
        "flag"
        "os"
        "net/http"
        )

const AppVersion = "timeserver version: 3.0"

func timeserver(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/time/" {
        NotFoundHandler(w, r)
        return
    }

    const layout = "3:04:05 PM"
    t := time.Now().Local()
    fmt.Fprint(w, "<html>\n")
    fmt.Fprint(w, "<head>\n")
    fmt.Fprint(w, "<style>\n")
    fmt.Fprint(w, "p {font-size: xx-large}\n")
    fmt.Fprint(w, "span.time {color: red}\n")
    fmt.Fprint(w, "</style>\n")
    fmt.Fprint(w, "</head>\n")
    fmt.Fprint(w, "<body>\n")
    //fmt.Fprint(w, "The time is now …
Run Code Online (Sandbox Code Playgroud)

http go http-status-code-404

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

在Go中为httptest.NewServer使用自定义URL

我通过使用Go语言创建http测试服务器在一些其他电话上运行UT。我的代码如下。

type student struct{
FirstName string
LastName string
}

func testGetStudentName() {
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    response = new(student)
    response.FirstName = "Some"
    response.LastName = "Name"
    b, err := json.Marshal(response)
    if err == nil {
            fmt.Fprintln(w, string(b[:]))
        }
    }))
    defer ts.Close()
    student1 := base.getStudent("123")
    log.Print("testServerUrl",testServer.URL) //prints out http://127.0.0.1:49931 ( port changes every time this is run)

   ts.URL = "http://127.0.0.1:8099" //this assignment does not quite change the URL of the created test server.
}
Run Code Online (Sandbox Code Playgroud)

在要测试的文件中,

var baseURL = "http://originalUrl.com" …
Run Code Online (Sandbox Code Playgroud)

unit-testing http go

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

在 UTF-8 中加密 Golang 中的字符串以放入 postgres

我在 go 中使用 crypto 来获取密码并使用密码短语来加密密码,然后将其作为字符串存储在 postgres sql 数据库中。加密工作正常,但是当我尝试将它添加到我的数据库时,我收到一个错误,似乎表明从 []byte 到 string 类型混淆了加密密码。

func Encrypt(password string, passphrase string) string {
    data := []byte(password)
    block, _ := aes.NewCipher([]byte(createHash(passphrase)))
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        panic(err.Error())
    }
    nonce := make([]byte, gcm.NonceSize())
    if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
        panic(err.Error())
    }
    ciphertext := gcm.Seal(nonce, nonce, data, nil)
    return string(ciphertext)
}

func createHash(key string) string {
    hasher := md5.New()
    hasher.Write([]byte(key))
    return hex.EncodeToString(hasher.Sum(nil))
}
Run Code Online (Sandbox Code Playgroud)

当我运行此代码并尝试在数据库中添加行时,出现错误

ERROR #22021 invalid byte sequence …
Run Code Online (Sandbox Code Playgroud)

encryption postgresql utf-8 go

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

Go 有部分类吗?

Go 中有部分类吗?

就像 C# 中的那个一样? http://msdn.microsoft.com/en-us/library/wa80x488.aspx

我想没有,因为你不能部分声明结构。

go

-1
推荐指数
1
解决办法
592
查看次数