golang有趣的demo

发布时间:2024-07-02 21:05:21

Golang有趣的Demo:探索Go语言魅力

Go语言(Golang)作为一门简洁、高效、可靠的开发语言,已经在全球范围内引起了广泛关注。其原生支持并发、易于编译和部署的特性,使得它成为现代应用程序开发的首选语言之一。除了在实际项目中应用Go语言,我们还可以通过一些有趣的demo来体验其强大之处。

1. 数据加密与解密

Go语言的crypto包提供了丰富而强大的加密、解密算法库,使得我们可以在应用程序中轻松实现数据的加密和解密操作。让我们以AES对称加密算法为例进行展示。

代码示例:

    package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "fmt"
    "io"
)

func main() {
    key := []byte("abcdefghijklmnopqrstuvwxyz123456")
    plaintext := []byte("Hello, Golang!")

    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    iv := ciphertext[:aes.BlockSize]
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        panic(err)
    }

    mode := cipher.NewCBCEncrypter(block, iv)
    mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
    fmt.Printf("Encrypted Text: %x\n", ciphertext)

    decrypted := make([]byte, len(ciphertext[aes.BlockSize:]))
    mode = cipher.NewCBCDecrypter(block, iv)
    mode.CryptBlocks(decrypted, ciphertext[aes.BlockSize:])
    fmt.Printf("Decrypted Text: %s\n", decrypted)
}
    

通过上述代码,我们使用AES对称加密算法将字符串“Hello, Golang!”加密为密文,并成功解密还原。这展示了Go语言在数据加密方面的便利性和灵活性。

2. 并发网络服务器

一个基于Golang实现的并发网络服务器可以让我们体验到Go语言无比强大的并发能力。以下是一个简单的demo,用于展示Go语言协程和通道的使用。

代码示例:

    package main

import (
    "fmt"
    "net"
    "time"
)

func handleConnection(conn net.Conn) {
    defer conn.Close()

    // 模拟请求处理
    time.Sleep(1 * time.Second)

    // 返回响应
    message := "Hello, Gopher!"
    conn.Write([]byte(message))
}

func main() {
    listener, err := net.Listen("tcp", ":8080")
    if err != nil {
        panic(err)
    }
    defer listener.Close()

    fmt.Println("Server is running on port 8080...")

    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println(err)
            continue
        }
        go handleConnection(conn)
    }
}
    

通过上述代码,我们可以在端口8080上启动一个TCP服务器,当有客户端连接时,即开启一个协程处理请求,并返回响应。这样的并发模型使得Go语言在网络开发中表现出色。

3. 生成随机密码

使用Go语言生成随机密码是非常简单的,借助于crypto/rand包和字符串操作函数,我们可以快速实现一个随机密码生成器。

代码示例:

    package main

import (
    "crypto/rand"
    "fmt"
    "math/big"
)

func generateRandomPassword(length int) string {
    var characters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-+=<>?{}")
    password := make([]rune, length)
    
    for i := range password {
        randomIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(characters))))
        password[i] = characters[randomIndex.Int64()]
    }
    
    return string(password)
}

func main() {
    length := 10
    password := generateRandomPassword(length)
    fmt.Printf("Random Password: %s\n", password)
}
    

通过上述代码,我们可以快速生成指定长度的随机密码。这向我们展示了Go语言在字符串处理和随机数生成方面的便捷性。

结语

本文只是列举了一些有趣的Go语言demo,让我们感受到了这门语言的魅力和全面的应用能力。无论是在数据加密、并发网络服务器还是生成随机密码等领域,Go语言都展现出令人惊艳的特性。如果你还未尝试过Go语言,不妨动手实践一下这些demo,体会一下Go语言给开发者带来的乐趣与便利。

相关推荐