golang

Golang: get the type of slice

匿名 (未验证) 提交于 2019-12-03 00:50:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I am using reflect package to get the type of arbitrary array, but getting prog.go:17: cannot use sample_array1 (type []int) as type []interface {} in function argument [process exited with non-zero status] How do I get the type from array? I know how to get it from value. func GetTypeArray(arr []interface{}) reflect.Type { return reflect.TypeOf(arr[0]) } http://play.golang.org/p/sNw8aL0a5f 回答1: Change: GetTypeArray(arr []interface{}) to: GetTypeArray(arr interface{}) By the way, []int is not an array but a slice of integers. 回答2: The fact

Golang Redis Cache

匿名 (未验证) 提交于 2019-12-03 00:44:02
1.Redis 2.Golang Redis Pool 点击打开链接 Codis 是一个分布式 Redis 解决方案, 对于上层的应用来说, 连接到 Codis Proxy 和连接原生的 Redis Server 没有显著区别 ( 不支持的命令列表 ), 上层应用可以像使用单机的 Redis 一样使用, Codis 底层会处理请求的转发, 不停机的数据迁移等工作, 所有后边的一切事情, 对于前面的客户端来说是透明的, 可以简单的认为后边连接的是一个内存无限大的 Redis 服务。 点击打开链接 const ( redis_host string = "127.0.0.1:6379" database string = "redisServer" password string = "123456" maxOpenConns int = 10 maxIdleConns int = 10 ) var Cache *RedisConnPool type RedisConnPool struct { redisPool *redis.Pool } func init() { Cache = &RedisConnPool{} Cache.redisPool = myNewPool() if Cache.redisPool == nil { panic("init redis failed!"

golang string转换数组

匿名 (未验证) 提交于 2019-12-03 00:43:02
如果去掉 arr *[5]rune 中的5, 则指参数变成了切片类型, 数组的指针就传不进去了, 编译会报错, 那么难道一定要写死数组的长度吗? 这样也太不优雅. 代码例子如下: func StringToRuneArr(s string , arr []rune) { src : = []rune(s) for i, v := range src { if i >= len(arr) { break } arr[i] = v } } func main(){ str : = " 这是一个字符串ABCDEF " var arr [ 10 ]rune utility.StringToRuneArr(str, arr[:]) fmt.Println( string (arr[:])) } 原文:https://www.cnblogs.com/elonlee/p/9363461.html

golang基础--reflect反射

匿名 (未验证) 提交于 2019-12-03 00:41:02
反射的知识点比较晦涩,后期会对此知识点展开深入的分析及示例代码展示 反射可达大提高程序的灵活性,使得inferface{}有更大的发挥余地 反射使用TypeOf和ValueOf函数从接口中获取目标对象信息:字段属性,方法信息 package main import ( "fmt" "reflect" ) type User struct { //定义一个结构类型 Id int Name string Age int } func (u User) Hello() { //定义一个结构方法 fmt.Println("Hello world") } func Info(o interface{}) { //定义一个方法,参数为空接口 t := reflect.TypeOf(o) //获取接收到的接口类型 fmt.Println("Type:", t.Name()) //获取名称 v := reflect.ValueOf(o) //获取接口的字段 fmt.Println("Fields:") //获取结构字段 for i := 0; i < t.NumField(); i++ { //for循环,取出所拥有的字段 f := t.Field(i) //获取值字段 val := v.Field(i).Interface() //获取字段的值 fmt.Printf("%6s:%v=%v\n",

解决vscode无法提示golang的问题

匿名 (未验证) 提交于 2019-12-03 00:39:02
https://github.com/Microsoft/vscode-go/wiki/Go-with-VS-Code-FAQ-and-Troubleshooting Q: Auto-completions stopped working. What do I do? Run gocode close in a terminal and try again. If it still doesnt work, run go get -u github.com/mdempsky/gocode to update the tool. If you use the go.toolsGopath setting, then set GOPATH to the value in that setting before running go get so that the tool is installed/updated in the right location If it still doesnt work, run gocode -s -debug in a terminal and try again. Results from gocode will show up in the terminal. If you see expected results in the

golang channel tips

匿名 (未验证) 提交于 2019-12-03 00:39:02
1. 读nil的channel是永远阻塞的。关闭nil的channel会造成panic。 2. closed channel的行为: 向close的channel发消息会panic。因为go建议向channel发送数据的人负责close channel。 如果close的channel还有数据,仍然可以读取。 读取close的并且空的channel,会马上返回零值(注意chan int会返回0)。 3. 可以对channel使用range。这样不用写select,显得代码简洁。 4. ok=false表示channel空并且close了 (注意不是“或者”)。 参考: https://stackoverflow.com/questions/34897843/why-does-go-panic-on-writing-to-a-closed-channel golang channel tips 原文:https://www.cnblogs.com/dearplain/p/9246558.html

golang jwt验证

匿名 (未验证) 提交于 2019-12-03 00:37:01
安装 go get “github.com/dgrijalva/jwt-go” 登陆 // Create a new token object, specifying signing method and the claims // you would like it to contain. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "foo" : "bar" , "nbf" : time.Date (2015 , 10 , 10 , 12 , 0 , 0 , 0 , time.UTC).Unix(), }) // Sign and get the complete encoded token as a string using the secret tokenString, err := token.SignedString(hmacSampleSecret) fmt.Println(tokenString, err) 验证 在调用 Parse 时,会进行加密验证,同时如果提供了 exp ,会进行过期验证; 如果提供了 iat ,会进行发行时间验证;如果提供了 nbf ,会进行发行时间验证. hmacSampleSecret := [] byte ( "my_secret_key" ) //

golang http middleware实现

匿名 (未验证) 提交于 2019-12-03 00:37:01
在登录后,可以使用中间件在处理业务逻辑前,先进行验证. 自定义middleware参考 func AuthOn(hFunc func (http.ResponseWriter, *http.Request)) func (http.ResponseWriter, *http.Request) { return http.HandlerFunc( func (w http.ResponseWriter, r *http.Request) { log.Printf( "AuthOn %v, token %v\n" , r.URL.Path, r.Header) hFunc(w, r) }) } // in func main http.HandleFunc( "/itemlist" , AuthOn(getItemHandler)) 关联jwt验证middleware, 携带的 token 只能放到header中; 如果放到body中,会影响正常的handler代码读取body中的字段. func VerifyJWT(tokenString string ) (jwt.MapClaims, error) { token, err := jwt.Parse(tokenString, func (token *jwt.Token) ( interface {}, error) { //

Golang的包名

匿名 (未验证) 提交于 2019-12-03 00:34:01
Golang的包名 (金庆的专栏 2018.6) 摘自: https://talks.golang.org/2014/organizeio.slide#1 The name of a package Keep package names short and meaningful. Don’t use underscores, they make package names long. io/ioutil not io/util suffixarray not suffix_array Don’t overgeneralize. A util package could be anything. The name of a package is part of its type and function names. On its own, type Buffer is ambiguous. But users see: buf := new(bytes.Buffer) Choose package names carefully. Choose good names for users. 文章来源: Golang的包名

golang测试框架 GoConvey使用总结

匿名 (未验证) 提交于 2019-12-03 00:34:01
一下是搭建好了环境以后,使用的过程和开发的时候-遇到的一些坑。 安装golang测试框架 go get github.com/smartystreets/goconvey 下载后,在github.com/smartystreets/goconvey 目录下运行goconvey.exe文件。 出来的cmd命令页面不要关闭,否则会中断测试。 注意修改端口。默认是8080端口。可能会与开发的端口产生冲突。 测试用例必须带_test后缀,否则系统无法检测到你的测试用例。 通过 生成测试所用的单元测试http://localhost:8080/composer.html Convey( "API " , t, func () { Convey( "/v1/user/login发送post请求得到状态code And http请求 And 账号登录 测试用例" , func () { So(PostRequest(urlUserLogin), ShouldEqual, true ) }) }) Convey可无限嵌套,用于表示子测试下的关系 部分参考内容:https://blog.csdn.net/zwqjoy/article/details/79474196 开源代码地址 GoConvey 网站 : http://smartystreets.github.io/goconvey/ 文章来源: