Go语言中文网 为您找到相关结果 160

Golang判断类型示例

package mainimport "fmt"type Student struct { Name string}func TestType(items ...interface{}) { for k, v := range items { switch v.(type) { case string: fmt.Printf("type is string, %d[%v]\n", k, v) case bool: fmt.Printf("type is bool, %d[%v]\n", k, v) case int: fmt.Printf("type is int, %d[%v]\n", k, v) case float32, float64: fmt.Printf("type is flo...阅读全文

博文 2019-08-29 11:32:52 灰侠_bf44

GO语言练习:网络编程 ICMP 示例

1、代码 2、编译及运行 1、Go语言网络编程:ICMP示例代码 icmptest.go 1 package main 2 3 import ( 4 "fmt" 5 "net" 6 "os" 7 "io" 8 "bytes" 9 ) 10 11 func main() { 12 if len(os.Args) != 2 { 13 fmt.Println("Usage : ", os.Args[0], "host") 14 os.Exit(0) 15 } 16 service := os.Args[1] 17 18 conn, err := net.Dial("ip4:icmp", service) 19 checkError(err) 20 21 var msg [512]byte 22 m...阅读全文

博文 2015-07-21 03:00:02 fengbohello

GTK+3 的 Go 绑定 gotk3

gotk3 提供 Go 绑定 GTK+3 和依赖的其他项目。每个组件都给出了用来导入包路径的子目录。以下是部分已经实施的支持库: * GTK+3 (3.6 and later) * GDK 3 (3.6 and later) * GLib 2 (2.36 and later) * Cairo (1.10 and later) 已经采取谨慎的内存管理与Go的垃圾收集器无缝工作,而无需使用或理解图形对象的浮动参考。 简单示例:

package main
import (
    "github.com/conformal/gotk3/gtk"
    ...阅读全文

Go-Type

在谈论struct和interface已经用到了type这个关键字。 另外,Go的type另外一种常用功能,是类似于C/C++的typedef。在Go的package中,这种用法非常常见。 A type declaration defines a new named type that has the same underlying type as an existing type. The named type provides a way to separate different and perhaps incompatible uses of the underlying type so that they can’t be mixed unintentionally. type n...阅读全文

博文 2016-09-07 07:00:01 u013344915

golang crypto aes 加密,解密示例

https://cyberspy.io/articles/crypto101/ 加密: package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "fmt" "io" ) func main() { // The key argument should be the AES key, either 16 or 32 bytes // to select AES-128 or AES-256. key := []byte("0123456789ABCDEF") plaintext := []byte("Apple") block, err := aes.NewCipher(key) if err != nil { pani...阅读全文

博文 2018-09-29 12:34:45 asmcos

golang flag 用法示例

file.go package main import "flag" import "fmt" import "os" func main() { if len(os.Args) < 2 { fmt.Println("too less param") return } var ip = flag.Int("flagname", 1234, "help message for flagname") var real string flag.StringVar(&real, "dir", "this is a test","help msg for dir") flag.Parse() fmt.Println(*ip) fmt.Println(real) } go build file.go ....阅读全文

博文 2015-06-18 17:04:31 u011363248

lex in golang

var txt = `{key1 = "\"value1\"\n" | key2 = { key3 = 10 } | key4 = {key5 = { key6 = value6}}}` var s scanner.Scanner s.Init(strings.NewReader(txt)) var b []byte loop: for { switch tok := s.Scan(); tok { case scanner.EOF: break loop case '|': b = append(b, ',') case '=': b = append(b, ':') case scanner.Ident: b = append(b, strconv.Quote(s.TokenText()...阅读全文

博文 2015-06-17 20:17:47 templarzq

Django中如何配置Database缓存?

  BACKEND:   django.core.cache.backends.db.DatabaseCache   LOCATION:   数据库表名   示例:   CACHES = {   'default': {   'BACKEND': 'django.core.cache.backends.db.DatabaseCache',   'LOCATION': 'my_cache_table',   }   }   Database缓存配置——创建缓存表   使用数据库缓存之前,需要创建缓存表:   python manage.py createcachetable   创建的表名为缓存配置中的LOCA...阅读全文

rana/ora.v4连接oracle的示例代码报错 (srvCfg := ora.SrvCfg{Dblink: "orcl"} env.OpenSrv(&srvCfg) )

错误: ./ocitest.go:17: cannot use &srvCfg (type *ora.SrvCfg) as type ora.SrvCfg in argument to env.OpenSrv 请知道的大神帮忙解答一下,谢谢了 oci8.pc文件内容: prefix=/usr version=12.1 build=client64 libdir=/root/program/lib includedir=/home/oracle_11/app/oracle/product/11.2.0/db_1/rdbms/public Name: oci8 Description: Oracle database engine ...阅读全文

SQL injection论述

SQL injection What is SQL injection SQL injection attacks are (as the name would suggest) one of the many types of script injection attacks. In web development, these are the most common form of security vulnerabilities. Attackers can use it to obtain sensitive information from databases, and aspects of an attack can involve adding users to the d...阅读全文

Go 语言 make & new

make 与 new 都是 Go 语言分配变量内存的方式,其中 make 主要针对 slice、map 与 chan 变量类型的内存分配以及相应内部结构的初始化,而 new 可以申请任何类型变量内存,但是拿到内存后会赋零值,他对于 slice、map 以及 chan 类型变量的申请没有太大意义。下面依据实际示例对这两种内存分配方式的区别进行个简单分析。 分配 sclie var s0 []int s0 = append(s0, 10) fmt.Println(&s0, s0) s1 := new([]int) *s1 = append(*s1, 10) fmt.Println(s1, *s1) s2 := make([]int, 0) s2 = append(s2, 10) fmt.Prin...阅读全文

博文 2015-12-10 16:00:31 u013148156

Go 唯一标识生成库 NUID

NUID 是一个高性能的唯一标识生成库,使用 GO 语言开发。 示例代码:

// Utilize the global locked instance
nuid := nuid.Next()

// Create an instance, these are not locked.
n := nuid.New()
nuid = n.Next()

// Generate a new crypto/rand seeded prefix.
// Generally not needed, happens automatically.
n.RandomizePrefix()阅读全文

Go-sha1

要点 计算字符串或码流的SHA1: sha1.Sum() 示例代码 util.go package main import ( "fmt" "crypto/sha1" "io/ioutil" ) /* Get the sha1 of file's content. If success, return the sha1 hex string. If fail, return "". */ func GetFileSHA1(filename string) string { data, err := ioutil.ReadFile(filename) if err != nil { fmt.Println("sum error: ", err) return "" } b := sha1.Su...阅读全文

博文 2016-10-31 07:00:02 u013344915

Go语言学习示例

Go by Example Go is an open source programming language designed for building simple, fast, and reliable software. Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below. Hello WorldValuesVariablesConstantsForIf/ElseSwitchArraysSlicesMapsRangeFunctionsMultiple Retur...阅读全文

博文 2015-06-19 22:00:25 boonya

fmt 的两个使用技巧

1. 通常 Printf 格式化字符串包含多个%参数时将会包含对应相同数量的额外操作数,但是%之后的[1]副词告诉 Printf 函数再次使用第一个操作数;[1] 可以扩展到更多。 2. %后的#副词告诉 Printf 在用%o、%x或%X输出时生成0、0x或0X前缀。 示例: ```go i := 123 fmt.Printf("%d %[1]x %#[1]x %#[1]X\n", i) ``` Output: `123 7b 0x7b 0X7B...阅读全文

Go学习笔记之:切片

切片是Go语言的关键类型之一,它提供了比数组更多的功能。 示例1: package main import "fmt" func main() { // 和数组不同的是,切片的长度是可变的。 // 我们可以使用内置函数make来创建一个长度不为零的切片 // 这里我们创建了一个长度为3,存储字符串的切片,切片元素 // 默认为零值,对于字符串就是""。 s := make([]string, 3) fmt.Println("emp:", s) // 可以使用和数组一样的方法来设置元素值或获取元素值 s[0] = "a" s[1] = "b" s[2] = "c" fmt.Println("set:", s) fmt.Println("get:", s[2]) // 可以用内置函数len获取切...阅读全文

博文 2014-11-26 08:00:01 Goopand

go语言 功能测试和性能测试的示例

F:./src └─hello hello.go hello_test.go hello.go ========= package hello import "fmt" func Add(a, b int) (result int) { return a + b } func main() { fmt.Println("Hello, world. 你好,世界!") c := Add(1, 2) fmt.Println("c=", c) } hello_test.go package hello import ( "fmt" "testing" "time" ) func TestAdd1(t *testing.T) { fmt.Println("进行Add测试") r := Add(1, 2...阅读全文

用于写 TCP 代理tcpproxy

包 tcpproxy 允许用户构建 TCP 代理,可选地根据 HTTP/1 主机头和 TLS 连接中的 SNI 主机名进行路由决策。 使用示例 ``` var p tcpproxy.Proxy p.AddHTTPHostRoute(":80", "foo.com", tcpproxy.To("10.0.0.1:8081")) p.AddHTTPHostRoute(":80", "bar.com", tcpproxy.To("10.0.0.2:8082")) p.AddRoute(":80", tcpproxy.To("10.0.0.1:8081")) // fallback p.AddSNIRoute(":443", "foo.com", tcpproxy.To("10.0...阅读全文

Golang Post传参调用示例

Golang Post传参package main import ( "fmt" "net/http" "io/ioutil" "strings" "encoding/json" "log" ) type TeamworkInfo struct { ProductId int64 `json:"productId"` //产品ID Topic string `json:"topic"` // Environment int64 `json:"environment"` //调用环境生产为1 沙盒2 DiscoverType int64 `json:"discoverType"` //缺陷发现方式 告警 4 Manager string `json:"manager"` //负责人 Creat...阅读全文

博文 2019-06-06 10:33:41 GoDevops

Golang之定义错误(errors)

基本示例: package main //定义错误 //error 也是个接口 import ( "errors" "fmt" ) var errNotFound error = errors.New("Not found error") func main() { fmt.Printf("error:%v", errNotFound) } 错误处理: package main import ( "fmt" "os" "time" ) type PathError struct { path string op string createTime string message string } func (p *PathError) Error() string { return fmt.S...阅读全文

博文 2018-01-20 08:30:00 pyyu

golang自定义模板示例

package main import ( "text/template" "time" "os" ) type User struct { Username, Password string RegTime time.Time } func ShowTime(t time.Time, format string) string { return t.Format(format) } func main() { u := User{"dotcoo", "dotcoopwd", time.Now()} t, err := template.New("text").Funcs(template.FuncMap{"showtime":ShowTime}). Parse(`

{{.Usernam...阅读全文

博文 2017-01-09 03:00:03 面码

Go学习笔记之:数组

数组是一个具有相同数据类型的元素组成的固定长度的有序集合。 在Go语言中,数组是值类型,长度是类型的组成部分,也就是说"[10]int"和“[20]int”是完全不同的两种数组类型。 同类型的两个数组支持"=="和"!="比较,但是不能比较大小。 数组作为参数时,函数内部不改变数组内部的值,除非是传入数组的指针。 数组的指针:*[3]int 指针数组:[2]*int 示例1: package main import "fmt" func main() { // 这里我们创建了一个具有5个元素的整型数组 // 元素的数据类型和数组长度都是数组的一部分 // 默认情况下,数组元素都是零值 // 对于整数,零值就是0 var a [5]int fmt.Println("emp:", a) // 我...阅读全文

博文 2014-11-26 08:00:01 Goopand

go语言示例:hello world

go语言示例:hello world 我们的第一个例子是经典的"hello world".这里是全部代码。 Plain Text code ? 1 2 3 4 5 package main import "fmt" func main() { fmt.Println("hello world") } 为了运行这个程序。我们把程序放到hello-world.go 文件中,并运行go run 命令。 $ go run hello-world.go hello world 有时候我们为了生成二进制文件。我们可以用go build命令。 $ go build hello-world.go $ ls hello-world hello-world.go 然后我们可以直接执行这个二进制文件。 $ ./h...阅读全文

博文 2014-11-13 18:00:01 xming4321

Postgres 高可用集群 Yoke

Yoke 是 Postgres 的高可用集群,具有自动切换和自动集群恢复。Postgres冗余/自动故障转移解决方案,提供一个高可用PostgreSQL集群的简单管理。 Yoke 依赖: * 包含 'primary', 'secondary' 和 'monitor' 三个节点的 3-server 集群 * 'primary' & 'secondary' 节点需要互相之间进行 ssh 连接 (w/o 密码) * 'primary' & 'secondary' 节点需要远程同步安装 (或者一些替代 sync_command) * ...阅读全文

Go语言 Go操作mysql简单示例

package main import ( "fmt" "database/sql" _"mysql" ) type TestMysql struct { db *sql.DB } /* 初始化数据库引擎 */ func Init() (*TestMysql,error){ test := new(TestMysql); db,err := sql.Open("mysql","test:test@tcp(127.0.0.1:3306)/abwork?charset=utf8"); //第一个参数 : 数据库引擎 //第二个参数 : 数据库DSN配置。Go中没有统一DSN,都是数据库引擎自己定义的,因此不同引擎可能配置不同 //本次演示采用[url]http://code.google.com...阅读全文

博文 2015-06-17 23:07:47 abv123456789

Go基础系列:nil channel用法示例

Go channel系列: channel入门 为select设置超时时间 nil channel用法示例 双层channel用法示例 指定goroutine的执行顺序 当未为channel分配内存时,channel就是nil channel,例如var ch1 chan int。nil channel会永远阻塞对该channel的读、写操作。 nil channel会阻塞对该channel的所有读、写。所以,可以将某个channel设置为nil,进行强制阻塞,对于select分支来说,就是强制禁用此分支。 以下是一个nil channel的示例: package main import ( "fmt" "math/rand" "time" ) // 不断向channel c中发送[0,10...阅读全文

博文 2018-11-23 09:12:12 f-ck-need-u

Go 实现的网站链接检查器Muffet

Muffet 是一个 Go 实现的网站链接检查器,可递归地检查网站中的所有页面。 **具有以下特性** 速度快 彩色输出 支持不同的标签(`a`, `img`, `link`, `script`, 等) **安装** **用法示例** [](https://shady.bakery.hotland)通过 `muffet --help` 获取更多帮助信息 **运行效果** ![image](https://static.oschina.net/uploads/space/2018/0425/150129_TPCX_2720166.png...阅读全文

开源项目 2018-04-25 15:30:00 网友

golang的一些试验小程序

golang的Map程序: package main import "fmt" type e interface{} func mult2(t e) e { switch t.(type) { case int: return t.(int) * 2 case string: return t.(string) + t.(string) } return t } func add3(t e) e { switch t.(type) { case int: return t.(int) + t.(int) + t.(int) case string: return t.(string) + t.(string) + t.(string) } return t } func localmap(s...阅读全文

博文 2014-10-04 19:27:19 壬癸甲乙

Go 语言编写 CPython 扩展 goPy

goPy 是一个新的开源项目,实现了用 Go 语言来编写 CPython 扩展。 示例代码: 01 package simple 02 03 import ( 04 "fmt" 05 "gopy" 06 ) 07 08 func example(args *py.Tuple) (py.Object, error) { 09 fmt.Printf("simple.example: %v\n", args) 10 py.None.Incref() 11 return py.None, nil 12 } 13 14 func init() { 15 methods := []py.Method{ 16 {"example", example, "example function"}, 17 } 1...阅读全文

博文 2015-06-17 23:01:31 hewy0526

golang json 示例

jsonStr, err := client.Get( deviceIdKey ).Result() if err == redis.Nil { deviceIds = []string{deviceId} fmt.Println("nil" ) } else if err != nil { //error r.status = -2 fmt.Println( "error ",err ) return c.JSON(http.StatusOK, r) } else { fmt.Println("other", jsonStr) //c, _ := ioutil.ReadFile(jsonStr) //dec := json.NewDecoder( bytes.NewReader(c) ) ...阅读全文

博文 2015-08-26 03:00:00 sban

Redis 热部署工具 Rump

## Rump Redis 热部署工具。 Rump 能够通过仅使用 SCAN,DUMP 和 RESTORE 将密钥从 ElastiCache 集群或任何 Redis 服务器传输到另一个 Redis 服务器。 ### 特性 * 使用 SCAN 代替 KEYS,以避免 DoS 您自己的服务器 * 可以同步任何键类型 * 有意删除TTL,因其不会同步 * 不使用任何临时文件 * 使用缓冲通道优化慢速源服务器 * 使用管道以最小化网络往返 ### 示例

# Sy...阅读全文

go语言 类型:字符串

示例 package main import ( "fmt" ) func main() { var str1 string // 声明一个字符串变量 str1 = "Hello world" // 字符串赋值 ch := str1[0] // 取字符串的第一个字符 fmt.Println(ch) //输出 73 fmt.Printf("%c\n", ch) //输出 H str2 := "Hello osfipin" // 字符串也支持声明时进行初始化的做法 //str2[0] = 'X' //编译错误 fmt.Println(len(str2)) //输出 13 str2 = "我爱you" fmt.Println(len(str2)) //输出 9 str3 := str2 + "ma...阅读全文

博文 2015-10-09 11:00:11 osfipin

go nil转为interface{}后判断不可靠

判断一个值是否为nil,最好是直接跟nil进行比较判断,而不要通过interface{}的形参传给另一个函数来进行判断。 但是用反射可以通过interface{}来判断nil,如testnil5。 看如下示例代码,a是一空指针,但只有testnil4和testnil5能正确判断出来: type State struct {} func testnil1(a, b interface {}) bool { return a == b } func testnil2(a *State, b interface{}) bool{ return a == b } func testnil3(a interface {}) bool { return a == nil } func testnil4(...阅读全文

博文 2016-02-01 13:00:00 logsharp

leetcode--两数之和(1)

1.给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1] go实现: package main import ( "fmt" ) func main() { nums := []int{1, 3, 4, 6, 7, 10} target := 17 newArr := twoSum(nums, target) fmt.Println(newArr) } func twoSum(nums []int, target int) []int { maps :=...阅读全文

博文 2018-05-09 21:34:37 fighter

Go-iota

要点 用const定义常量 iota 表示取值为0(const关键字)所在行,后续常量依次加1 iota 用来表示递增的数列,用法较多,参考下面的示例代码。 示例代码 package main import ( "fmt" ) /* The Go Programming Language. 3.6 Constants When a sequence of constants is declared as a group, the right-hand side expression may be omitted for all but the first of the group, implying that the previous expression and its type shou...阅读全文

博文 2016-11-20 03:00:02 u013344915

并行 SSH 执行工具multissh

一个简单的并行 SSH 工具,可以批量的对主机通过 SSH 执行命令组合。 支持: 并发执行 单次执行多条命令 ip 地址段自动匹配主机(192.168.0.1-192.168.0.100) ssh 用户名/密码认证 ssh key 认证 json 格式输出 输出到文本,文件名为 host.txt 可以直接下载编译好的 release 版本 提供 win64 和 linux64 两个平台的可执行文件 [https://github.com/shanghai-edu/multissh/releases/](https://github.com/shanghai-edu/multissh/releases/) **cmdfile 示例** **hostfile 示例**...阅读全文

windows下go编码转换问题

github上有两个package做编码转换,都是基于iconv,用到了cgo,在linux下没有问题,在windows下用,非常麻烦。采用mingw安装libiconv也不行,一直提示找不到libiconv方法。 最终找到一个官方实现(纯go实现):https://code.google.com/p/go/source/checkout?repo=text gbk转utf-8示例: func gbk2utf8(str byte[]) ([]byte, error) { return ioutil.ReadAll(transform.NewReader(bytes.NewReader(str), simplifiedchinese.GBK.NewDecoder())) } 经测试没有任何问题...阅读全文

博文 2016-06-16 13:00:15 baizx

GO语言如何调用C写的函数

1,c文件 #include #include extern int sun(int a, int b) { return a + b; } 2,go调用示例 package main // #include "c_fun.h" import "C" import "fmt" func main() { fmt.Println("go call c: 3+4=", C.sun(3, 4)) } 3,说明 输出:go call c: 3+4= 7 c_fun.h是标准的C,声明一个sun函数。在go文件中,#include要放在注释里; 还有import "C",要单独成一行。 转自:http://kan.weibo.com/con/360554816...阅读全文

博文 2015-06-17 23:07:43 rznice

生成本地 HTTPS 加密证书的工具mkcert

mkcert 是生成本地 HTTPS 加密证书的工具,一个命令就可以生成证书,不需要任何配置。 **使用示例** ![image](https://static.oschina.net/uploads/space/2018/0705/151103_zHGf_2720166.jpg) 目前仅支持 Linux 和 macOS 系统,未来计划支持 Windows 系统。 **安装使用** 在 macOS 上,使用 Homebrew 进行安装 在 Linux 上,安装 certuti...阅读全文

开源项目 2018-07-05 16:30:01 网友

针对json的查询--alibaba的开源项目jsonq

项目地址: https://github.com/alibaba/jsonq 示例json { "foo": 1, "bar": 2, "test": "Hello, world!", "baz": 123.1, "array": [ {"foo": 1}, {"bar": 2}, {"baz": 3} ], "subobj": { "foo": 1, "subarray": [1,2,3], "subsubobj": { "bar": 2, "baz": 3, "array": ["hello", "world"] } }, "bool": true } 调用 import ( "strings" "encoding/json" "github.com/jmoiron/jsonq" ) d...阅读全文

博文 2017-10-19 02:40:45 zsy

go排序示例

package main import( "fmt" "sort" "math/rand" ) const( male = iota female unknown ) var genderStr []string=[]string{"male","female","unknown",} type People struct{ Id int `ID` Age int `Age` Name string `Name` Gender int `Gender` } func (p People) String() string{ return fmt.Sprintf("People %q of age %v with ID %v,Gender %s\n",p.Name,p.Age,p.Id,gend...阅读全文

博文 2016-05-05 17:00:01 zhannk

Golang的反射reflect深入理解和示例

本人认为讲解的最好的文章,在此做个备案。方便以后查询。 微信链接地址: https://mp.weixin.qq.com/s?__biz=MzI2NzE3NzMzNQ==&mid=2650555706&idx=1&sn=c5383ac15c0038fdf2ff29152ee419b5&chksm=f28a3922c5fdb034831e93fd82d760111fd07dc1b0ee6748f55fa0be6f569d46875b6631b097&mpshare=1&scene=1&srcid=&sharer_sharetime=1576809179753&sharer_shareid=9a8fb33c226ef040ec830cafc7905e51&key=e149ed35f0e9d79c...阅读全文

博文 2019-12-21 06:32:44 caoxinyiyi