golang

一看就懂系列之Golang的goroutine和通道

你。 提交于 2019-12-03 02:03:14
https://blog.csdn.net/u011957758/article/details/81159481 前言 如果说php是最好的语言,那么golang就是最并发的语言。 支持golang的并发很重要的一个是goroutine的实现,那么本文将重点围绕goroutine来做一下相关的笔记,以便日后快速留恋。 10s后,以下知识点即将靠近: 1.从并发模型说起 2.goroutine的简介 3.goroutine的使用姿势 4.通道(channel)的简介 5.重要的四种通道使用 6.goroutine死锁与处理 7.select的简介 8.select的应用场景 9.select死锁 正文 1.从并发模型说起 看过很多大神简介,各种研究高并发,那么就通俗的说下并发。 并发目前来看比较主流的就三种: 1.多线程 每个线程一次处理一个请求,线程越多可并发处理的请求数就越多,但是在高并发下,多线程开销会比较大。 2.协程 无需抢占式的调度,开销小,可以有效的提高线程的并发性,从而避免了线程的缺点的部分 3.基于异步回调的IO模型 说一个熟悉的,比如nginx使用的就是epoll模型,通过事件驱动的方式与异步IO回调,使得服务器持续运转,来支撑高并发的请求 为了追求更高效和低开销的并发,golang的goroutine来了。 2.goroutine的简介 定义: 在go里面

convert interface{} to int in Golang

匿名 (未验证) 提交于 2019-12-03 01:58:03
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I'm new to Golang and I'm trying to get a value from a JSON and cast it to int but it doesn't work. Don't know how to do it properly. Here is the error message: ...cannot convert val (type interface {}) to type int: need type assertion And the Code: var f interface{} err = json.Unmarshal([]byte(jsonStr), &f) if err != nil { utility.CreateErrorResponse(w, "Error: failed to parse JSON data.") return } m := f.(map[string]interface{}) val, ok := m["area_id"] if !ok { utility.CreateErrorResponse(w, "Error: Area ID is missing from submitted data."

Dereferencing a map index in Golang

匿名 (未验证) 提交于 2019-12-03 01:57:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I'm learning Go currently and I made this simple and crude inventory program just to tinker with structs and methods to understand how they work. In the driver file I try to call a method from and item type from the items map of the Cashier type. My method have pointer reciever to use the structs directly instead of making copies. When I run the program I get this error .\driver.go:11: cannot call pointer method on f[0] .\driver.go:11: cannot take the address of f[0] Inventory.go: package inventory type item struct{ itemName string amount

Reusing http connections in Golang

匿名 (未验证) 提交于 2019-12-03 01:54:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I'm currently struggling to find a way to reuse connections when making HTTP posts in Golang. I've created a transport and client like so: // Create a new transport and HTTP client tr := &http.Transport{} client := &http.Client{Transport: tr} I'm then passing this client pointer into a goroutine which is making multiple posts to the same endpoint like so: r, err := client.Post(url, "application/json", post) Looking at netstat this appears to be resulting in a new connection for every post resulting in a large number of concurrent connections

How to parse unix timestamp in golang

匿名 (未验证) 提交于 2019-12-03 01:49:02
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I'm trying to parse an Unix timestamp but I get out of range error. That doesn't really makes sense to me because the layout is correct (as in the golang docs): package main import "fmt" import "time" func main() { tm, err := time.Parse("1136239445", "1405544146") if err !=nil{ panic(err) } fmt.Println(tm) } play 回答1: The time.Parse function does not do Unix timestamps. Instead you can use strconv.ParseInt to parse the string to int64 and create the timestamp with time.Unix : package main import ( "fmt" "time" "strconv" ) func main() { i,

Golang: how to verify number of processors on which a Go program is running

匿名 (未验证) 提交于 2019-12-03 01:48:02
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I am new to Google Go (Golang). My question is related to this post What exactly does runtime.Gosched do? . The structure of code is as copied below. My question, is that when I change the number of processor in GOMAXPROCS, how do I verify how many processors it is running on. When I do 'top', it shows a.out process which consumes 100% or less resources even when GOMAXPROCS is more than 1. I would be grateful for your help. package main import ( "fmt" "runtime" "sync" ) var wg sync.WaitGroup func doTasks() { fmt.Println(" Doing task ") for

In golang, how to determine the final URL after a series of redirects?

匿名 (未验证) 提交于 2019-12-03 01:47:02
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 由 翻译 强力驱动 问题: So, I'm using the net/http package. I'm GETting a URL that I know for certain is redirecting. It may even redirect a couple of times before landing on the final URL. Redirection is handled automatically behind the scenes. Is there an easy way to figure out what the final URL was without a hackish workaround that involves setting the CheckRedirect field on a http.Client object? I guess I should mention that I think I came up with a workaround, but it's kind of hackish, as it involves using a global variable and setting the

Golang Daily - 闭包作用

落爺英雄遲暮 提交于 2019-12-03 01:45:33
一、什么是闭包 特征: - 函数内部包含匿名子函数,子函数以return返回 - 子函数可以访问函数内部的局部变量 - 被子函数持有的局部变量不回被销毁 二、闭包的作用 优点 - 访问函数的私有变量 - 外部函数为全局函数的情况下,保证内部私有变量不被回收 类似类的封装,数据为私有变量,操作为return的匿名函数 缺点 - 内存占用,无法回收 三、示例 package main import "fmt" func intSeq() func() int { i := 0 return func() int { i++ return i } } func main() { nextInt := intSeq() fmt.Println(nextInt()) fmt.Println(nextInt()) fmt.Println(nextInt()) newInts := intSeq() fmt.Println(newInts()) } 四、参考文章 【 https://www.golangprograms.com/closures-functions-in-golang.html 】 【 https://gobyexample.com/closures 】 【 https://omarkhawaja.com/understanding-function-closures-in

Golang and MongoDb remote access fail (server returned error on SASL authentication step: Authentication failed.)

匿名 (未验证) 提交于 2019-12-03 01:39:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I am trying to connect to remote MongoDB database (Mongolab) from Go with mgo library but getting error panic: server returned error on SASL authentication step: Authentication failed . Here is my code package main import ( "fmt" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "log" ) type Person struct { Name string Phone string } func main() { session, err := mgo.Dial("mongodb://<dbusername>:<dbpassword>@ds055855.mlab.com:55855") if err != nil { panic(err) } defer session.Close() // Optional. Switch the session to a monotonic behavior. session

GoLang: How to delete an element from a 2D slice?

匿名 (未验证) 提交于 2019-12-03 01:39:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I've recently been messing around with Go and I wanted to see how it would be to delete an element from a two-dimensional slice. For deleting an element from a one-dimensional slice, I can successfully use: data = append(data[:i], data[i+1:]...) However, with a two-dimensional slice, using: data = append(data[i][:j], data[i][j+1:]...) throws the error: cannot use append(data[i][:j], data[i][j+1:]...) (type []string) as type [][]string in assignment Would tackling this require a different approach? 回答1: A 2D slice in Go is nothing more than a