假设我有一个类似的结构
type A struct{
name string`json:"name"`
}
Run Code Online (Sandbox Code Playgroud)
然后在主要我有代码
var jsonString string = `{"status":false}`
var a A
error := json.Unmarshal([]byte(jsonString),&a)
Run Code Online (Sandbox Code Playgroud)
显然上面的代码产生了一个nil错误,无论json格式是不同的.什么时候json.Unmarshal()会在Go中返回错误?
我正在尝试学习Go web编程,这里是一个简单的Web服务器:它打印出被调用的时间.
package main
import (
"fmt"
"net/http"
)
var calls int
// HelloWorld print the times being called.
func HelloWorld(w http.ResponseWriter, r *http.Request){
calls++
fmt.Fprintf(w, "You've called me %d times", calls)
}
func main() {
fmt.Printf("Started server at http://localhost%v.\n", 5000)
http.HandleFunc("/", HelloWorld)
http.ListenAndServe(":5000", nil)
}
Run Code Online (Sandbox Code Playgroud)
当我刷新页面时,我得到了:
You've called me 1 times
You've called me 3 times
You've called me 5 times
....
Run Code Online (Sandbox Code Playgroud)
问题:为什么是1,3,5次,而不是1,2,3 ......?HelloWorld被调用的函数的顺序是什么?
已经厌倦了这个人为的例子:
package main
import "fmt"
func printElo() {
fmt.Printf("Elo\n")
}
func printHello() {
fmt.Printf("Hello\n")
}
func main() {
fmt.Printf("This will print.")
i := 0
for i < 10 {
go printElo()
go printHello()
i++
}
}
Run Code Online (Sandbox Code Playgroud)
这个程序的输出只是"这将打印".输出goroutine printElo()并且printHello不会被发出因为,我猜,main()函数线程将在goroutines甚至有机会开始执行之前完成.
在Golang中使类似代码工作而不是过早终止的惯用方法是什么?
假设我有以下 struct wherevalid用于验证每个验证器(特别是govalidator)的自定义消息的结构。
type Login struct {
Email string `json:"email" valid:"required~Email is required,email~The email address provided is not valid"`
Password string `json:"password" valid:"required~Password is required,stringlength(6|40)~Password length must be between 6 and 40"`
}
Run Code Online (Sandbox Code Playgroud)
添加了一些验证器后,行太长且无法维护。
我想拆分成新行,但不支持 go并且与reflect.StructTag.Get不兼容。
但是,根据我的测试,验证器可以使用多行结构标记,但 vet 失败。
简而言之,拆分长结构标签的正确方法是什么?
我正在与https://github.com/mongodb/mongo-go-driver 合作,目前正在尝试实现此类结构的部分更新
type NoteUpdate struct {
ID string `json:"id,omitempty" bson:"_id,omitempty"`
Title string `json:"title" bson:"title,omitempty"`
Content string `json:"content" bson:"content,omitempty"`
ChangedAt int64 `json:"changed_at" bson:"changed_at"`
}
Run Code Online (Sandbox Code Playgroud)
例如,如果我有
noteUpdate := NoteUpdate{ Title: "New Title" }
Run Code Online (Sandbox Code Playgroud)
然后我希望存储文档中唯一的“标题”字段将被更改。
我需要写一些类似的东西
collection.FindOneAndUpdate(context.Background(),
bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)),
// I need to encode non-empty fields here
bson.NewDocument(bson.EC.SubDocument("$set", bson.NewDocument(...)))
)
Run Code Online (Sandbox Code Playgroud)
问题是我不想用bson.EC.String(...)or手动编码每个非空字段bson.EC.Int64(...)。我尝试使用bson.EC.InterfaceErr(...)但出现错误
无法为 *models.NoteUpdate 类型创建元素,请尝试使用 bsoncodec.ConstructElementErr
不幸的是,bsoncodec 中没有这样的功能。我发现的唯一方法是创建包装器
type SetWrapper struct {
Set interface{} `bson:"$set,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)
并使用它
partialUpdate := &NoteUpdate{
ID: "some-note-id",
Title: "Some new title", …Run Code Online (Sandbox Code Playgroud) 正如我们在go中所知,当goroutine必须执行阻塞调用(例如系统调用)或通过cgo调用C库时,可能会创建一个线程.一些测试代码:
package main
import (
"io/ioutil"
"os"
"runtime"
"strconv"
)
func main() {
runtime.GOMAXPROCS(2)
data, err := ioutil.ReadFile("./55555.log")
if err != nil {
println(err)
return
}
for i := 0; i < 200; i++ {
go func(n int) {
for {
err := ioutil.WriteFile("testxxx"+strconv.Itoa(n), []byte(data), os.ModePerm)
if err != nil {
println(err)
break
}
}
}(i)
}
select {}
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,它没有创建很多线程.
? =99=[root /root]$ cat /proc/9616/status | grep -i thread
Threads: 5
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
以下代码运行完全正常:
package main
import (
"fmt"
)
func my_func(c chan int){
fmt.Println(<-c)
}
func main(){
c := make(chan int)
go my_func(c)
c<-3
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我改变
c<-3
Run Code Online (Sandbox Code Playgroud)
至
time.Sleep(time.Second)
c<-3
Run Code Online (Sandbox Code Playgroud)
我的代码没有执行.
我的直觉是main在my_func完成执行之前以某种方式返回,但似乎添加暂停应该没有任何效果.我完全迷失在这个简单的例子上,这里发生了什么?
我在我的表单中有一个多选输入,我试图在我的处理程序中获取所选值,但我不能,我怎么能得到这些值?
<form action="process" method="post">
<select id="new_data" name="new_data class="tag-select chzn-done" multiple="" style="display: none;">
<option value="1">111mm1</option>
<option value="2">222mm2</option>
<option value="3">012nx1</option>
</select>
</form>
Run Code Online (Sandbox Code Playgroud)
我的处理程序:
func myHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.FormValue("new_data")) // result-> []
fmt.Println(r.Form("new_data")) // result-> []
}
Run Code Online (Sandbox Code Playgroud)
表单序列化数据,从JS控制台中选择选项1和2:
>$('#myform').serialize()
>"new_data=1&new_data=2"
Run Code Online (Sandbox Code Playgroud) 我想在3年前得到时间unix时间戳,我现在用它:
time.Now().Unix(() - 3 * 3600 * 24 * 365
Run Code Online (Sandbox Code Playgroud)
无论如何这都不准确(因为年份可能有366天).
当我定义一个自定义类型时,似乎底层类型的类型对我是否可以将其传递给函数或我需要转换它有所不同.
问题是:
为什么RuneFunc和StringMap有效,但不是Integer?
https://play.golang.org/p/buKNkrg5y-
package main
type RuneFunc func(rune) rune
type Integer int
type StringMap map[string]string
func main() {
//m := make(StringMap)
//mf(m)
var i Integer = 5
nf(i)
//var f func(rune) rune
//ff(f)
}
func mf(i map[string]string) {
}
func ff(i func(rune)rune) {
}
func nf(i int) {
}
Run Code Online (Sandbox Code Playgroud)
在这里,当我运行这个函数调用nf与Integer它抱怨,虽然int是基础类型.但是当我打电话mf或ff他们成功运行时.