Go snippets
1. Get random string in Go
import (
"fmt"
"math/rand"
)
var probLetters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*1234567890")
func randString(length int) string {
b := make([]rune, length)
for i := range b {
b[i] = probLetters[rand.Intn(len(probLetters) - 1)]
}
return string(b)
}
fmt.Println(randString(10))
You can try here.
2. Scheduling with time.Sleep()
import (
"time"
)
func doSomething() {}
for true {
doSomething()
time.Sleep(time.Second * 10)
}
The doSomething()
will be invoked every 10 seconds.
3. Checking palindrome string
func isPalindrome(s string) bool {
var letters []rune
for _, r := range s {
if unicode.IsLetter(r) {
letters = append(letters, unicode.ToLower(r))
}
}
for i := range letters {
if letters[i] != letters[len(letters)-1-i] {
return false
}
}
return true
}
4. Fetching API with package net/http
func fetchAPI() {
URL := "https://jsonplaceholder.typicode.com/posts"
response, err := http.Get(URL)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
defer response.Body.Close()
data, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Print(string(data))
}
5. Padding string with certain character
func formatString(num int) string {
formatted := fmt.Sprintf("%04d", num)
return formatted
}
fmt.Println(formatString(5)) // Output: 0005
In the format string “%04d”, 0 specifies zero padding, and 4 specifies the width of the resulting string. So, %04d means format the number as a decimal integer (d) with a width of 4 characters, padded with zeros if necessary.
6. Prevent many goroutines access shared resources simultaneously
import (
"sync"
)
var mu sync.Mutex
func processFunction() {
// Lock the mutex before executing the function
mu.Lock()
defer mu.Unlock()
// Simulate some work
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
func main() {
// Launch several goroutines to invoke the function
for i := 0; i < 3; i++ {
go processFunction()
}
}