这看起来有点愚蠢,肯定有更好的方法吗?
err = SendMessageAndWait(db, "this is a test")
if err != nil {
fmt.Println("Error sending message", err)
return
}
err = DoSomething(db, "this is a test")
if err != nil {
fmt.Println("Error sending message", err)
return
}
err = CheckSomething(db, "this is another test")
if err != nil {
fmt.Println("Error sending message", err)
return
}
err = SendMessageAndWait(db, "this is a third test")
if err != nil {
fmt.Println("Error sending message", err)
return
}
... x10 ...
Run Code Online (Sandbox Code Playgroud) 我正在关注Go Tour,当涉及到goroutines时我有点卡住了.我知道他们非常轻量级,每次goroutine阻止,另一个将开始,但我无法理解这个例子实际如何工作:
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(1000 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
Run Code Online (Sandbox Code Playgroud)
据我所知,一个goroutine是针对具有参数"world"的say函数启动的,但据我所知,应该打印"world"五次并且"hello"一次.但是我不明白为什么输出是这样的:
hello
world
hello
world
hello
world
hello
world
hello
Run Code Online (Sandbox Code Playgroud)
从我对其他语言的线程的有限理解,输出应该是这样的:
hello
world
world
world
world
world
Run Code Online (Sandbox Code Playgroud)
或者像这样:
world
world
world
hello
world
world
Run Code Online (Sandbox Code Playgroud)
为什么第二行也执行五次?go语句下面的任何内容都会归类为go例程的一部分吗?
下一张幻灯片还显示了我无法再次回头看的内容:
package main
import "fmt"
func sum(a []int, c chan int) {
sum := 0 …Run Code Online (Sandbox Code Playgroud) 我正在创建一个Go应用程序,以便在终端中使用.以下代码要求用户向终端输入文本.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
for {
fmt.Println("Please input something and use arrows to move along the text left and right")
in := bufio.NewReader(os.Stdin)
_, err := in.ReadString('\n')
if err != nil {
fmt.Println(err)
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是用户不能使用左箭头和右箭头沿着刚输入的文本进行修改.当他按下箭头时,控制台会打印 ^[[D^[[C^[[A^[[B标志.
输出:
Please input something and use arrows to move along the text left and right
hello^[[D^[[C^[[A^[[B
Run Code Online (Sandbox Code Playgroud)
如何使箭头键表现得更加用户友好,让人类使用左右箭头沿着刚刚输入的文本导航?
我想,我应该关注像termbox-go或gocui这样的库, 但是如何正确地将它们用于此目的,我不知道.
给出以下Go方法:
func (t *T) TMethod(data *testData) (interface{}, *error) {
...
}
Run Code Online (Sandbox Code Playgroud)
我想反映参数的名称(data在这里).
我尝试了以下,但它返回结构名称(testData在这里):
reflect.ValueOf(T).MethodByName("TMethod").Type().In(0).Elem().Name()
Run Code Online (Sandbox Code Playgroud)
如何获取参数的名称?
我是golang的新手,我正在尝试构建一个简单的tcp服务器.但是我遇到了一些使用JSON响应的问题.我写了下面的代码,然后尝试postman发送一些json数据.但是,我的邮递员总是得到空的回应而且content-type是text/plain; charset=utf-8.然后我在http://www.alexedwards.net/blog/golang-response-snippets#json中检查了一个样本.我复制并粘贴了样本,效果很好.但我看不出我和样本之间有任何区别.有人可以帮忙吗?
package main
import (
"encoding/json"
"net/http"
)
type ResponseCommands struct {
key string
value bool
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":5432", nil)
}
func handler(rw http.ResponseWriter, req *http.Request) {
responseBody := ResponseCommands{"BackOff", false}
data, err := json.Marshal(responseBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.WriteHeader(200)
rw.Header().Set("Content-Type", "application/json")
rw.Write(data)
}
Run Code Online (Sandbox Code Playgroud) 我有一个简单的Go HTML模板,其中包含HTML条件注释:
package main
import (
"html/template"
"os"
)
var body = `<!doctype html>
<html>
<head>
<!--[if !IE]><!--><script src="http://code.jquery.com/jquery-2.0.3.min.js"></script><!--<![endif]-->
<!--[if gte IE 9]><script src="http://code.jquery.com/jquery-2.0.3.min.js"></script><![endif]-->
<!--[if lt IE 9]><script src="http://code.jquery.com/jquery-1.10.2.min.js"></script><![endif]-->
</head>
</html>`
func main() {
tmp := template.Must(template.New("tmp").Parse(body))
tmp.Execute(os.Stdout, nil)
}
Run Code Online (Sandbox Code Playgroud)
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
</head>
</html>
Run Code Online (Sandbox Code Playgroud)
为什么html/template在编译后删除那些条件注释?
package demo
type People struct {
Name string
Age uint
}
type UserInfo struct {
Address string
Hobby []string
NickNage string
}
Run Code Online (Sandbox Code Playgroud)
另一个包:
import "demo"
Run Code Online (Sandbox Code Playgroud)
在这个包中,如何获取从演示包中导出的所有类型?
基本上我的文件夹结构如下:
bin/
pkg/
linux_amd64/
github.com/user/
stringutil.a
src/
github.com/user/
hello/
hello.go (main file)
stringutil/
stringutil.go
Run Code Online (Sandbox Code Playgroud)
hello.go是从 导入一些函数的主程序stringutil.go。
运行后go install,在(如上)stringutil.a下创建。pkg
我的问题是,既然我已经有了源,我可以在go install没有源的情况下再次运行吗?stringutil.gostringutil.a
我是一名 Java 程序员,也是 Go 新手。通常在Java中,在编译时,我们可以将编译好的jar文件导入到classpath中进行编译。
我怎样才能在 Go 中做同样的事情?如果我有一个编译好的包,stringutil.a我怎样才能将该文件分发给某人并让他们使用它而不暴露原始源代码?
我已经开发了一个小型Go TCP服务器来制作聊天应用程序。但是,当我尝试将客户端连接到该服务器时,该服务器可以与两个客户端正常工作,但是每当我尝试连接第三个客户端时,该服务器就不会连接到服务器。我在Windows上运行。可能是什么问题?
package main
import (
"bufio"
"fmt"
"net"
)
var allClients map[*Client]int
type Client struct {
// incoming chan string
outgoing chan string
reader *bufio.Reader
writer *bufio.Writer
conn net.Conn
connection *Client
}
func (client *Client) Read() {
for {
line, err := client.reader.ReadString('\n')
if err == nil {
if client.connection != nil {
client.connection.outgoing <- line
}
fmt.Println(line)
} else {
break
}
}
client.conn.Close()
delete(allClients, client)
if client.connection != nil {
client.connection.connection = nil
}
client = nil …Run Code Online (Sandbox Code Playgroud) 我已经编写了REST API服务,该服务要求所有响应均为JSON。但是,当Go HTTP请求解析器遇到错误时,它将返回400作为纯文本响应,而无需调用我的处理程序。例:
> curl -i -H 'Authorization: Basic hi
there' 'http://localhost:8080/test' -v
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /test HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
> Authorization: Basic hi
> there
>
< HTTP/1.1 400 Bad Request
HTTP/1.1 400 Bad Request
< Content-Type: text/plain; charset=utf-8
Content-Type: text/plain; charset=utf-8
< Connection: close
Connection: close
<
* Closing connection 0
Run Code Online (Sandbox Code Playgroud)
请注意无效的授权标头。当然,400是正确的响应,但是当然是文本/纯文本。有什么方法可以配置Go http解析器以使用自定义错误响应媒体类型和主体?
go ×10
bad-request ×1
chat ×1
concurrency ×1
goroutine ×1
html ×1
http ×1
json ×1
media-type ×1
reflection ×1
tcp ×1
templates ×1
terminal ×1