Creating Random Strings of a fixed length in Go.
Using rand.Int63 Function
Int63 returns a non-negative pseudo-random 63-bit integer as an int64 from the default Source.
package main
import (
"fmt"
"math/rand"
"time"
)
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func RandStringByLenth(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Int63()%int64(len(letters))]
}
return string(b)
}
func main() {
// Don't forget
rand.Seed(time.Now().UTC().UnixNano())
for range "012345" {
s := RandStringByLenth(6)
fmt.Println(s)
}
}
GjwtZy
wZotMg
qRKVLB
RDQtvQ
RRbTrB
gzMuMm
Don't forget about the rand.Seed(), otherwise you got the same string every first time launch.
Masking
We can maintain the equal distribution of letters by using only as many of the lowest bits of the random number as many is required to represent the number of letters. So here is the solution:
package main
import (
"fmt"
"math/rand"
"time"
)
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6
letterIdxMask = 1<<letterIdxBits - 1
letterIdxMax = 63 / letterIdxBits
)
func RandStringByLenth(n int) string {
b := make([]byte, n)
// A rand.Int63() generates 63 random bits, enough for letterIdxMax letters!
for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = rand.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letters) {
b[i] = letters[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
func main() {
// Don't forget
rand.Seed(time.Now().UTC().UnixNano())
for range "012345" {
s := RandStringByLenth(6)
fmt.Println(s)
}
}
SADUwS
ufPPAG
eNmPcJ
JMFEtV
NHkRrN
gOlDuC
Using base64 Function
If you want cryptographically secure random numbers, and the exact charset is flexible (say, base64 is fine), you can calculate exactly what the length of random characters you need from the desired output size.
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"math"
)
func RandStringByBase64(n int) string {
buff := make([]byte, int(math.Ceil(float64(n)/float64(1.33333333333))))
rand.Read(buff)
str := base64.RawURLEncoding.EncodeToString(buff)
return str[:n]
}
func main() {
for range "012345" {
s := RandStringByBase64(6)
fmt.Println(s)
}
}
QnPVHr
mTA0nZ
h4HPrV
Yj7ZS2
TF8jo9
KKqM5_
Reverse a String in Golang. Using range
a range on a string returns a rune which is a codepoint.
package main
import "fmt"
func Reverse(s string) (result string) {
for _, v := range s {
result = string(v) + result
}
return
}
func main() {
// !olleH
s := Reverse("Hello!")
fmt.Println(s)
// 界世,olleH
s = Reverse("Hello,世界")
fmt.Println(s)
}
!olleH
界世,olleH
Swapping the Letters
Reverse the string by swapping the letters.
package main
import "fmt"
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func main() {
// !olleH
s := Reverse("Hello!")
fmt.Println(s)
// 界世,olleH
s = Reverse("Hello,世界")
fmt.Println(s)
}
!olleH
界世,olleH
Reverse the order of an array. Using array_reverse Function
The array_reverse() return an array with elements in reverse order.
$arr = array("PHP", 8.1, 4);
$reversed = array_reverse($arr);
print_r($reversed);
$preserved = array_reverse($arr, true);
print_r($preserved);
Array
(
[0] => 4
[1] => 8.1
[2] => PHP
)
Array
(
[2] => 4
[1] => 8.1
[0] => PHP
)
Using Swapping Method
Here is another solution using same variable names as yours and using swapping method.
function Reverse($arr) {
for ($i=count($arr) - 1, $j = 0; $j < $i ; $i--, $j++) {
$temp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $temp;
}
return $arr;
}
// without using any PHP function and any other variable
function Reverse($arr) {
$count = count($arr);
for ($i=0; $i < $count/2 ; $i++) {
[$arr[$i], $arr[$count-$i-1]] = [$arr[$count-$i-1], $arr[$i]];
}
return $arr;
}
$arr = array("PHP", 8.1, 4);
$reversed = Reverse($arr);
print_r($reversed);
Array
(
[0] => 4
[1] => 8.1
[2] => PHP
)
Reverse a Unicode String in PHP. Using strrev Function
The strrev() reverse a string.
// !olleH
echo strrev("Hello!");
// does not support utf-8 encoding
strrev("Hello,世界");
!olleH
Using For Loop
FOR LOOP will start with the value of the length of the “original string – 1” value.
function Reverse($str) {
for ($i=strlen($str) - 1, $j = 0; $j < $i ; $i--, $j++) {
$temp = $str[$i];
$str[$i] = $str[$j];
$str[$j] = $temp;
}
return $str;
}
// !olleH
echo Reverse("Hello!");
!olleH
Using the Recursion Technique and the substr
We can also reverse a string using recursion and substr() function.
function Reverse($str) {
$len = strlen($str);
if($len == 1) {
return $str;
} else {
$len--;
return Reverse(substr($str, 1, $len))
.substr($str, 0, 1);
}
}
// !olleH
echo Reverse("Hello!");
!olleH
Reverse a Unicode string
This function support utf-8 encoding, Human Language and Character Encoding Support:
function mb_strrev($str){
$r = '';
for ($i = mb_strlen($str); $i>=0; $i--) {
$r .= mb_substr($str, $i, 1);
}
return $r;
}
// 界世,olleH
echo mb_strrev("Hello,世界");
Here's another way.
function mb_strrev($text)
{
return join('', array_reverse(
preg_split('~~u', $text, -1, PREG_SPLIT_NO_EMPTY)
));
}
// 界世,olleH
echo mb_strrev("Hello,世界");
Here's another approach using regex.
function mb_strrev($str){
preg_match_all('/./us', $str, $ar);
return implode(array_reverse($ar[0]));
}
// 界世,olleH
echo mb_strrev("Hello,世界");
Convert File Size to a human friendly format. Get file size in human-readable units like kilobytes (KB), Megabytes (MB) or GigaBytes (GB)
SI (Decimal 1 k = 1,000)
A metric prefix is a unit prefix that precedes a basic unit of measure to indicate a multiple or submultiple of the unit. List of SI prefixes: k、M、G、T、P、E、Z、Y.
package main
import (
"fmt"
"math"
)
func FormatByteSI(b int64) string {
const unit = 1000
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB",
float64(b)/float64(div), "kMGTPE"[exp])
}
func main() {
FormatByteSI(800) // 800 B
FormatByteSI(1024) // 1.0 kB
FormatByteSI(987654321) // 987.7 MB
FormatByteSI(1551859712) // 1.6 GB
FormatByteSI(math.MaxInt64) // 9.2 EB
}
800 B
1.0 kB
987.7 MB
1.6 GB
9.2 EB
IEC (binary 1 Ki = 1,024)
A binary prefix is a unit prefix for multiples of units in data processing, data transmission, and digital information, principally in association with the bit and the byte, to indicate multiplication by a power of 2. List of SI prefixes: Ki、Mi、Gi、Ti、Pi、Ei、Zi、Yi.
package main
import (
"fmt"
"math"
)
func FormatByteIEC(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB",
float64(b)/float64(div), "KMGTPE"[exp])
}
func main() {
FormatByteIEC(800) // 800 B
FormatByteIEC(1024) // 1.0 KiB
FormatByteIEC(987654321) // 941.9 MiB
FormatByteIEC(1551859712) // 1.4 GiB
FormatByteIEC(math.MaxInt64) // 8.0 EiB
}
800 B
1.0 KiB
941.9 MiB
1.4 GiB
8.0 EiB
Convert File Size
files, err := ioutil.ReadDir(".")
if err != nil {
// panic()
}
for _, file := range files {
fmt.Printf("%-6d %-6s %-6s\n", file.Size(), FormatByteSI(file.Size()), FormatByteIEC(file.Size()))
}
963 963 B 963 B
2197 2.2 kB 2.1 KiB
1172 1.2 kB 1.1 KiB
384 384 B 384 B
1165 1.2 kB 1.1 KiB
753 753 B 753 B
Extracting substrings in Go. Using the slice syntax
A slice is formed by specifying two indices, a low and high bound, separated by a colon:
// a[low : high]
s := "Hello,世界"
// e
fmt.Println(s[1:2])
fmt.Println(s[1:])
// Hello,世界
fmt.Println(s[:])
e
ello,世界
Hello,世界
Length of the the result is high — low.
Indices cannot be arbitrary numbers
negative numbers aren’t allowed. low ≤ high. high ≤ len(input).
s := "Hello,世界"
// negative numbers aren’t allowed
fmt.Println(s[-1:3])
// invalid argument: index -1 (constant of type int) must not be negative
// 12
fmt.Println(len(s))
// high ≤ len(input)
fmt.Println(s[1:20])
// panic: runtime error: slice bounds out of range [:20] with length 12
Only work with ASCII
Operating on strings alone will only work with ASCII and will count wrong when input is a non-ASCII UTF-8 encoded character, and will probably even corrupt characters since it cuts multibyte chars mid-sequence.
For strings that contain non-ASCII Unicode characters (such as emojis, characters from other languages, e.t.c.), a conversion to a rune slice is required before taking a subslice.
s := "Hello,世界"
// wrong, diamond-like shape
fmt.Println(s[6:7])
// 世
fmt.Println(s[6:9])
runes := []rune(s)
// 世
fmt.Println(string(runes[6:7]))
List of Golang Keywords.
Keywords
The following keywords are reserved and may not be used as identifiers.
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
They can be categorized as four groups:
Declaration
const, func, import, package, type and var are used to declare all kinds of code elements in Go programs.
##### const
The ‘const’ keyword is used to introduce a name for a scalar value like 2 or 3.14, etc.
##### func
The ‘func’ keyword is used to declare a function.
##### import
The ‘import’ keyword is used to import packages.
##### package
The code is grouped as a unit in a package. The ‘package’ keyword is used to define one.
##### type
We can use the ‘type’ keyword to introduce a new struct type.
##### var
The ‘var’ keyword is used to create the variables in the ‘Go’ language.
Control Flow
chan, interface, map and struct are used as parts in some composite type denotations.
##### chan
The ‘chan’ keyword is used to define a channel. In ‘Go’, you are allowed to run parallel pieces of code simultaneously.
##### interface
The ‘interface’ keyword is used to specify a method set. A method set is a list of methods for a type.
##### map
The ‘map’ keyword defines a map type. A map os an unordered collection of the key-value pairs.
##### struct
Struct is a collection of fields. We can use the ‘struct’ keyword followed by the field declarations.
Composite Types
break, case, continue, default, else, fallthrough, for, goto, if, range, return, select and switch are used to control flow of code.
##### break
The ‘break’ keyword lets you terminate a loop and continue execution of the rest of the code.
##### case
This is a form of a ‘switch’ construct. We specify a variable after the switch.
##### continue
The ‘continue’ keyword allows you to go back to the beginning of the ‘for’ loop.
##### default
The ‘default’ statement is optional but you need to use either case or default within the switch statement.
##### else
The ‘else’ keyword is used with the ‘if’ keyword to execute an alternate statement if a certain condition is false.
##### fallthrough
This keyword is used in a case within a switch statement. When we use this keyword, the next case is entered.
##### for
The ‘for’ keyword is used to begin a for loop.
##### goto
The ‘goto’ keyword offers a jump to a labeled statement without any condition.
##### if
The ‘if’ statement is used to check a certain condition within a loop.
##### range
The ‘range’ keyword lets you iterate items over the list items like a map or an array.
##### return
Go allows you to use the return values as variables and you can use the ‘return’ keyword for that purpose.
##### select
The ‘select’ keyword lets a goroutine to wait during the simultaneous communication operations.
##### switch
The ‘switch’ statement is used to start a loop and use the if-else logic within the block.
Function Modifier
defer and go are also control flow keywords, but in other specific manners.
##### defer
The ‘defer’ keyword is used to defer the execution of a function until the surrounding function executes.
##### go
The ‘go’ keyword triggers a goroutine which is managed by the golang-runtime.
Predeclared Names
In addition, there are about three dozen predeclared names like int and true for built-in con- stants, types, and functions.
##### Constants
true false iota nil
##### Types
int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr float32 float64 complex128 complex64 bool byte rune string error
##### Functions
make len cap new append copy close delete complex real imag panic recover
Formatting PHP Strings with printf and sprintf.
Using sprintf Function
The sprintf() return a formatted string.
sprintf(string $format, mixed ...$values): string
// iPhone 14 Pro
echo sprintf("%s %d Pro\n", "iPhone", 14);
// iPhone 14 Pro
printf("%s %d Pro\n", "iPhone", 14);
iPhone 14 Pro
iPhone 14 Pro
Specifying padding character
// .......14
echo sprintf("%'.9d\n", 14);
// 000000014
echo sprintf("%'.09d\n", 14);
// zero-padded integers
// 01-12
echo sprintf("%02d-%02d", 1, 12);
.......14
000000014
01-12
Formatting Currency
// 14.23
echo sprintf("%01.2f\n", 14.234);
// 14.24
echo sprintf("%01.2f\n", 14.239);
14.23
14.24
Using number_format Function
The number_format() format a number with grouped thousands.
number_format(
float $num,
int $decimals = 0,
?string $decimal_separator = ".",
?string $thousands_separator = ","
): string
$number = 1234.5678;
// 1234.57
echo number_format($number, 2, '.', '');
// 1,234.57
echo number_format($number, 2, '.', ',');
Printing all properties of an object.
Using print_r Function
The print_r() prints human-readable information about a variable. If given a string, int or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.
print_r(mixed $value, bool $return = false): string|bool
$i = 10;
print_r($i);
$arr = array(
'title' => 'Apple Watch 7',
'views' => 1000
);
print_r($arr);
10
Array
(
[title] => Apple Watch 7
[views] => 1000
)
Using var_dump Function
The var_dump() dumps information about a variable. This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
var_dump(mixed $value, mixed ...$values): void
$i = 10;
var_dump($i);
$arr = array(
'title' => 'Apple Watch 7',
'views' => 1000
);
var_dump($arr);
// This one returns the value of var_dump instead of outputting it.
function var_dump_ret($mixed = null) {
ob_start();
var_dump($mixed);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
int(10)
array(2) {
["title"]=>
string(13) "Apple Watch 7"
["views"]=>
int(1000)
}
Using var_export Function
var_export() gets structured information about the given variable. It is similar to var_dump() with one exception: the returned representation is valid PHP code.
var_export(mixed $value, bool $return = false): ?string
$i = 10;
var_export($i);
$arr = array(
'title' => 'Apple Watch 7',
'views' => 1000
);
$v = var_export($arr, true);
echo $v;
10
array (
'title' => 'Apple Watch 7',
'views' => 1000,
)
How Hashing Function Works and its Syntax.
MD5 Function
The md5() calculates the md5 hash of a string. Returns the hash as a 32-character hexadecimal number.
$str = "Google";
// 8b36e9207c24c76e6719268e49201d94
echo md5($str);
// bool(true)
md5('240610708') == md5('QNKCDZO')
The comparison is true because both md5() hashes start '0e' so PHP type juggling understands these strings to be scientific notation.
Hash Functions
The hash() function returns a hash value for the given data based on the algorithm like (md5, sha256).
hash(
string $algo,
string $data,
bool $binary = false,
array $options = []
): string
$str = "Google";
// md5:
$r = hash("md5", $str);
printf("%-7s %s\n", "md5", $r);
// sha256
$r = hash("sha256", $str);
printf("%-7s %s\n", "sha256", $r);
// crc32
$r = hash("crc32", $str);
printf("%-7s %s\n", "crc32", $r);
md5 8b36e9207c24c76e6719268e49201d94
sha256 ce770667e5f9b0d8f55367bb79419689d90c48451bb33f079f3a9a72ae132de8
crc32 a98f3368
hash_hmac Function
The hash_hmac() function generate a keyed hash value using the HMAC method.
hash_hmac(
string $algo,
string $data,
string $key,
bool $binary = false
): string
$str = "Google";
// md5
$r = hash("md5", $str);
printf("%-5s %s\n", "md5", $r);
// md5
$key = "apple";
$r = hash_hmac("md5", $str, $key);
printf("%-5s %s\n", "hmac", $r);
md5 8b36e9207c24c76e6719268e49201d94
hmac c7ed9855f3b7ac31b0ee6ae204b3d1c0
Length of the output
How long is hash function? The length of the output or hash depends on the hashing algorithm you use.
$str = "Google";
hash("md5", $str); // md5
hash("sha256", $str); // sha256
hash("crc32", $str); // crc32
foreach (hash_algos() as $v) {
$r = hash($v, $str);
printf("%-12s %3d %s\n", $v, strlen($r), $r);
}
md2 32 ef4cce74dab86220df3d2cde2bf7872d
md4 32 26cf807f0af0f1f3da3dd1b730367957
md5 32 8b36e9207c24c76e6719268e49201d94
sha1 40 2b681c0a24baff8899d7163cc7f805c75e1f44e4
sha224 56 b84e52794c142b49fe92323cc27a68fc89b67ee05f6941120e8ac020
sha256 64 ce770667e5f9b0d8f55367bb79419689d90c48451bb33f079f3a9a72ae132de8
sha384 96 2af172307e1317b9c04187cc7f664e5ea7907df8523c409bc2f226ab05f3ca031a966d86db52bc3a3600bd97bd8f2e50
sha512/224 56 291bb8a532905473148259bfe02161e02dc6e05a3cacd6feeaf985f1
sha512/256 64 13470697b72753e0eab9325818943321c7f16bf9ac76b76731e36f09ffd4f079
sha512 128 973807e34fb710b43bafbe55ffcbc7ba91235ee1388e816cb91439d895bd28815734c9886e6ec68262ed8b39f93850e628ba637866726d1e7b726c5e090b0299
sha3-224 56 1256deb617266d03dbab7d4cc5691577e0d771232c998bcab01d9466
sha3-256 64 f86f0d52d7d52195cadd91f21c50c9d756f291798352132de3ed94e098279611
sha3-384 96 68c57cd259865ee3984afc4f00af1a40530bf1ca2ba1aafe7adbf912cd6bbef2755d6d1b936b4fc431b7e6ee6531a956
sha3-512 128 3ad0f436f4de7e5f33a2a4d3707514ec6a33201883959493110c9a9eb5d1dbb6386b58978004d257a446f9cd8fe3439c469af6cc3105ec7d30e3724881e830b7
ripemd128 32 c9dd129bb987a91e85c94abd31558735
ripemd160 40 a986a86f6241845eaa3c9875a58e123b67933cfe
ripemd256 64 0305fc62ad0eed097e19ffb71c8274c49ef6766fa35785dc3c1a5357ff40abe8
ripemd320 80 43b67aed55307a827b92423ed8a6cc2316a8b976c075ed08d8ed9bdbbf56ab2c2a62f9f4625818ff
whirlpool 128 6cff68ca32b1eccc5d8e4da6a5d0c2ebd7e7f27da9883744e6ecbcbfec246ccab86db69690795a454a2ca59ef862bf355447d1a7d90df7de78efd2d4980db0de
tiger128,3 32 90a8c6cd64b63e2b69ca530ce72a12ac
tiger160,3 40 90a8c6cd64b63e2b69ca530ce72a12ac5e951c8f
tiger192,3 48 90a8c6cd64b63e2b69ca530ce72a12ac5e951c8f1c66e76d
tiger128,4 32 4bc0eaf32a5d23c9b9471001d50011d1
tiger160,4 40 4bc0eaf32a5d23c9b9471001d50011d13c4b7041
tiger192,4 48 4bc0eaf32a5d23c9b9471001d50011d13c4b7041dc26d6bd
snefru 64 6cd79d0616aedb2c77bda3cb086de5ba2df50ab0914d89de28147424a6c29deb
snefru256 64 6cd79d0616aedb2c77bda3cb086de5ba2df50ab0914d89de28147424a6c29deb
gost 64 c746a4916b524a8ee3c2d17e422604e958a3f3b0a1af5e9b48fdffc17289dbe8
gost-crypto 64 e99bcc7cd375ba552cdfa4738b02686d166f7516b12c9a34f2ca7f793ab2c448
adler32 8 0809025e
crc32 8 a98f3368
crc32b 8 62b0f067
fnv132 8 ef7f4f70
fnv1a32 8 e3b85fa6
fnv164 16 c9b5f41dc6c6b290
fnv1a64 16 d517473001a04866
joaat 8 30359b9f
haval128,3 32 6db80f18a37f1c7376c12b096d08a8cf
haval160,3 40 a0c42322bc198714b776d345c454f9281b01a666
haval192,3 48 7d15ecf012ccab23a237aa8a8b9c9a53ec9f7c34335cf1cf
haval224,3 56 db9e76463ef171e0a40aab1a0bbaaf40fcb9374b52cf250427facc5f
haval256,3 64 6c3b9c7f01eebb13a04d500fddfa6bb561ca70083bbd957960a1faa4ee3c027d
haval128,4 32 89b80917072d844deb7e73ce8d1210f1
haval160,4 40 0a6f00ae5da588cf85829798965f8c443e7aa611
haval192,4 48 e786ed6fe5c7b145e45e1f0ffea8a3d74b2747f9f4f2b583
haval224,4 56 c9610a8024d01588a4e134a38b27da49545bdb53d52caf6c7f5cc4a8
haval256,4 64 2658e0d1d84c2148206e4b3e50fcc0748878f07599475d6acf98c00ff62304f5
haval128,5 32 0c00b8283c4b5be93ed282cc9dd58ec1
haval160,5 40 71a0ccc422d64c00b6fbac61c32722c62dadde54
haval192,5 48 fb47a69eca151a9678fdce96a003e32a58dc0d2e2a135b1a
haval224,5 56 168fa42b4d0b1bd9b0602b337aefa93ff418b47cfe8be73e10b6145d
haval256,5 64 87cde1d87a5fe43caa8e060b1d0aca628dc7280b648c9b234217eb5ad095fafc
Reduce Bandwidth Usage by Supporting If-Modified-Since in PHP.
If-Modified-Since
The If-Modified-Since request HTTP header makes the request conditional: the server sends back the requested resource, with a 200 status, only if it has been last modified after the given date. If the resource has not been modified since, the response is a 304 without any body; the Last-Modified response header of a previous request contains the date of last modification.
header('Last-Modified: Mon, 04 Apr 2022 11:14:54 GMT');
header('Etag: "13ae4368810e6594"');
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html; charset=UTF-8
Date: Tue, 05 Apr 2022 02:34:28 GMT
Etag: W/"13ae4368810e659493f54575ddecc096d8350cf751dd0b7a921640eb9e13463d"
Last-Modified: Mon, 04 Apr 2022 11:14:54 GMT
Server: nginx
Transfer-Encoding: chunked
Vary: Accept-Encoding
Greenwich Mean Time. HTTP dates are always expressed in GMT, never in local time.
Handling If-Modified-Since
If the If-Modified-Since request header is present, then it can be parsed to get a timestamp that can be compared against the modification time. If the modification time is older than the request time, a 304 response can be returned instead of generating the page.
$updatedTime = filemtime($file);
$updatedTime = strtotime("2022-04-11 11:14:54");
$gmtTime = gmdate('D, d M Y H:i:s T', $updatedTime);
header('Last-Modified: ' . $gmtTime );
$conent = "content";
// $etag = md5_file($file);
// hash
$etag = hash('sha256', $conent);
// using CRC32
$etag = crc32($conent);
header(sprintf('Etag: "%s"', $etag));
// HTTP_IF_MODIFIED_SINCE || If-None-Match
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $gmtTime === $_SERVER['HTTP_IF_MODIFIED_SINCE'] ||
isset($_SERVER['If-None-Match']) && $etag === $_SERVER['If-None-Match']) {
http_response_code(304);
header('X-MODIFIED-SINCE: MATCH');
die();
}
The most common use case is to update a cached entity that has no associated ETag.
curl: If-Modified-Since
Type the following curl command:
curl header
curl -v -H 'If-Modified-Since: Mon, 11 Apr 2022 11:14:54 GMT' https://installmd.com/c/77/go/fetching-a-url
HTTP/1.1 304 Not Modified
Server: nginx
Date: Tue, 05 Apr 2022 03:12:29 GMT
Connection: keep-alive
Last-Modified: Mon, 11 Apr 2022 11:14:54 GMT
Etag: "4274335913"
X-MODIFIED-SINCE: MATCH
Reading from a url resource in Go. Fetching a URL
Go provides a collection of packages, grouped under net, that make it easy to send and receive information through the Internet. Package http provides HTTP client and server implementations.
package main
import (
"io/ioutil"
"net/http"
)
func main() {
url := "https://go.dev/"
resp, err := http.Get(url)
if err != nil {
// panic
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
// upload image
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
// post form
resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})
}
The client must close the response body when finished with it.
For control over HTTP client headers
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
resp, err := client.Get("http://example.com")
// ...
req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...
// For control over proxies ...
tr := &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
DisableCompression: true,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://example.com")
Fetching URLs Concurrently
One of the most interesting and novel aspects of Go is its support for concurrent program- ming.
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
)
func fetch(url string, ch chan<- string) {
start := time.Now()
resp, err := http.Get(url)
if err != nil {
ch <- fmt.Sprint(err) // send to channel ch
return
}
defer resp.Body.Close()
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
if err != nil {
ch <- fmt.Sprintf("while reading %s: %v", url, err)
return
}
secs := time.Since(start).Seconds()
ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url)
}
func main() {
urls := []string{"https://go.dev/", "https://www.google.com/"}
ch := make(chan string)
for _, url := range urls {
go fetch(url, ch)
}
for range urls {
fmt.Println(<-ch) // receive from channel ch
}
}
0.95s 15227 https://www.google.com/
1.13s 58557 https://go.dev/
Questions
How to read gzipped data from http response in Golang?
Golang by default will automatically decode the body of gzipped response. If the Transport requests gzip on its own and gets a gzipped response, it's transparently decoded in the Response.Body. However, if the user explicitly requested gzip it is not automatically uncompressed.
Format a string without printing in Go. Basics
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler.
fmt.Sprintf
Sprintf formats according to a format specifier and returns the resulting string.
// func Sprintf(format string, a ...interface{}) string
s := fmt.Sprintf("Apple iOS %s", "15.4")
// floating-point number
s := fmt.Sprintf("Apple iOS %f", 15.4)
// any value
s := fmt.Sprintf("Apple iOS %v", 15.4)
Apple iOS 15.4
Apple iOS 15.400000
Apple iOS 15.4
fmt.Printf
Printf formats according to a format specifier and writes to standard output. It returns the number of bytes written and any write error encountered.
// func Printf(format string, a ...interface{}) (n int, err error)
fmt.Printf("Apple iOS %s\n", "15.4")
Apple iOS 15.4
The verbs
Printf has over a dozen such conversions, which Go programmers call verbs.
The verbs:
##### %v
the value in a default format when printing structs, the plus flag (%+v) adds field names
##### %#v
a Go-syntax representation of the value
##### %T
a Go-syntax representation of the type of the value
##### %%
a literal percent sign; consumes no value
##### %t
the word true or false
##### %b
base 2
##### %c
the character represented by the corresponding Unicode code point
##### %d
base 10
##### %o
base 8
##### %O
base 8 with 0o prefix
##### %q
a single-quoted character literal safely escaped with Go syntax.
##### %x
base 16, with lower-case letters for a-f
##### %X
base 16, with upper-case letters for A-F
##### %U
Unicode format: U+1234; same as "U+%04X"
##### %b
decimalless scientific notation with exponent a power of two, in the manner of strconv.FormatFloat with the 'b' format, e.g. -123456p-78
##### %e
scientific notation, e.g. -1.234456e+78
##### %E
scientific notation, e.g. -1.234456E+78
##### %f
decimal point but no exponent, e.g. 123.456
##### %F
synonym for %f
##### %g %e
for large exponents, %f otherwise. Precision is discussed below.
##### %G %E
for large exponents, %F otherwise
##### %x
hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20
##### %X
upper-case hexadecimal notation, e.g. -0X1.23ABCP+20
##### %s
the uninterpreted bytes of the string or slice
##### %q
a double-quoted string safely escaped with Go syntax
##### %x
base 16, lower-case, two characters per byte
##### %X
base 16, upper-case, two characters per byte
##### %f
default width, default precision
##### %9f
width 9, default precision
##### %.2f
default width, precision 2
##### %9.2f
width 9, precision 2
##### %9.f
width 9, precision 0
##### +
always print a sign for numeric values; guarantee ASCII-only output for %q (%+q)
##### -
pad with spaces on the right rather than the left (left-justify the field)
##### #
alternate format: add leading 0b for binary (%#b), 0 for octal (%#o), 0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p); for %q, print a raw (backquoted) string if strconv.CanBackquote returns true; always print a decimal point for %e, %E, %f, %F, %g and %G; do not remove trailing zeros for %g and %G; write e.g. U+0078 'x' if the character is printable for %U (%#U).
##### ' '
(space) leave a space for elided sign in numbers (% d); put spaces between bytes printing strings or slices in hex (% x, % X)
##### 0
pad with leading zeros rather than spaces; for numbers, this moves the padding after the sign
Converting Json to string in Golang. Decoding JSON Into Structs
Go offers built-in support for JSON encoding and decoding, including to and from built-in and custom data types.
Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.
package main
import (
"encoding/json"
)
type Message struct {
Name string
Version int64
}
func main() {
s := `{"name":"Android", "version":13, "code":1}`
var m Message
// func Unmarshal(data []byte, v interface{}) error
err := json.Unmarshal([]byte(s), &m)
if err != nil {
// panic
}
}
If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.
Unmarshal will decode only the fields that it can find in the destination type.
Marshaling Structured Data
To encode JSON data we use the json.Marshal function.
m := Message{
Name: "Android",
Version: 13,
}
// func Marshal(v interface{}) ([]byte, error)
b, _ := json.Marshal(&m)
fmt.Println(string(b))
{"Name":"Android","Version":13}
Decoding arbitrary data
Without knowing this data’s structure, we can decode it into an map[string]interface{} value with Unmarshal:
s := `{"name":"Android", "version":13}`
// var m interface{}
var m map[string]interface{}
err := json.Unmarshal([]byte(s), &m)
// s := `[{"name":"Android", "version":13}]`
// map[] json: cannot unmarshal array into Go value of type map[string]interface {}
map[name:Android version:13]
Ignoring Empty Fields
In some cases, we would want to ignore a field in our JSON output, if its value is empty. We can use the “-” property for this purpose.
type Message struct {
Name string
Version int64 `json:"-"`
}
m := Message{
Name: "Android",
Version: 13,
}
b, err := json.Marshal(&m)
{"Name":"Android"}
How do you check if a string contains a substring?. Using String.prototype.includes
The includes() method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false as appropriate.
'Google Docs will start'.includes('Docs'); // => true
// includes return true for empty substring
'Google Docs will start'.includes(''); // => true
// case-sensitive
'Google Docs will start'.includes('docs'); // => false
String.prototype.indexOf
includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found.
'Google Docs will start'.indexOf('Docs') !== -1; // => true
// an empty string is a substring of every string
'Google Docs will start'.indexOf('') !== -1; // => true
// case-sensitive
'Google Docs will start'.indexOf('Docs') !== -1; // => false
Polyfill
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (search instanceof RegExp) {
throw TypeError('first argument must not be a RegExp');
}
if (start === undefined) { start = 0; }
return this.indexOf(search, start) !== -1;
};
}
Go test string contains substring. Using strings.Contains Function
How do I check if a string is a substring of another string in Go? Use the function Contains from the strings package.
Contains function returns a boolean value. It returns true if the substring is present in the string, or false if not.
s := "Apple's new iPad Air is $30 off"
// func Contains(s, substr string) bool
res := strings.Contains(s, "iPad") // res = true
res := strings.Contains(s, "ipad") // res = fasle
// case-insensitive
res := strings.Contains(strings.ToLower(s), strings.ToLower("ipad")) // res = true
Using strings.Index Function
Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.
strings.Contains internally calls strings.Index.
s := "Apple's new iPad Air is $30 off"
// func Index(s, substr string) int
i := strings.Index(s, "iPad") // i = 12
i := strings.Index(s, "ipad") // i = -1
// case-insensitive
i := strings.Index(strings.ToLower(s), strings.ToLower("ipad")) // i = 12
Using strings.Split Function
Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.
s := "Apple's new iPad Air is $30 off"
// func Split(s, sep string) []string
ss := strings.Split(s, "iPad") // len(ss) >= 2
Using strings.Count Function
Count counts the number of non-overlapping instances of substr in s. If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
s := "Apple's new iPad Air is $30 off"
// func Count(s, substr string) int
i := strings.Count(s, "iPad") // i = 1
i := strings.Count(s, "ipad") // i = 0
Using regexp.MatchString Function
MatchString reports whether the string s contains any match of the regular expression pattern.
s := "Apple's new iPad Air is $30 off"
// func MatchString(pattern string, s string) (matched bool, err error)
matched, _ := regexp.MatchString("iPad", s) // matched = true
matched, _ := regexp.MatchString("ipad", s) // matched = false
// case-insensitive
matched, _ := regexp.MatchString("(?i)ipad", s) // matched = true
// regexp.MustCompile
b := regexp.MustCompile("(?i)ipad").MatchString(s) // b = true
Interface variable conversion in Golang. Type Assertion
To convert interface to int64 in Go, Using Type Assertion.
A type assertion provides access to an interface value's underlying concrete value.
package main
import "fmt"
// t := i.(T)
// t, ok := i.(T)
func main() {
var v interface{} = 1
// interface to int
i, ok := v.(int)
fmt.Println(i, ok)
// int to int64
i64 := int64(i)
s := fmt.Sprintf("Type: %T, %d", i64, i64)
fmt.Println(s)
i64 = v.(int64) // panic
}
1 true
Type: int64, 1
panic: interface conversion: interface {} is int, not int64
If i does not hold a T, the statement will trigger a panic.
Type switches
A type switch is like a regular switch statement, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value.
func i2num(i interface{}) (int64, error) {
switch v := i.(type) {
case int64:
return v, nil
case int:
return int64(v), nil
case string:
return strconv.ParseInt(v, 10, 64)
default:
return 0, errors.New("type error")
}
}
// i, err := i2num("34")
// i, err := i2num("34.2")
// fmt.Println(i, err)
0 strconv.ParseInt: parsing "34.2": invalid syntax
Type casting an interface to a string in go. Using fmt.Sprintf Function
To convert interface to string in Go, use fmt.Sprintf function.
Sprintf formats according to a format specifier and returns the resulting string.
package main
import "fmt"
var x = []interface{}{
"abc",
1,
3.14,
[]int{1, 2, 3},
struct {
A int
B string
}{
A: 10,
B: "code",
},
}
func main() {
// Method fmt.Sprintf("value: %v", v)
for _, v := range x {
str := fmt.Sprintf("%v", v)
fmt.Println(str)
}
// Method fmt.Sprint(v)
for _, v := range x {
str := fmt.Sprint(v)
fmt.Println(str)
}
}
abc
1
3.14
[1 2 3]
{10 code}
abc
1
3.14
[1 2 3]
{10 code}
fmt.Sprint(val) is equivalent to fmt.Sprintf("%v", val)
If the %v verb is used with the # flag (%#v) and the operand implements the GoStringer interface, that will be invoked.
// Method fmt.Sprintf("value: %#v", v)
for _, v := range x {
str := fmt.Sprintf("%#v", v)
fmt.Println(str)
}
"abc"
1
3.14
[]int{1, 2, 3}
struct { A int; B string }{A:10, B:"code"}
Type Assertion
A type assertion provides access to an interface value's underlying concrete value.
package main
import "fmt"
func main() {
var i interface{} = "golang"
// Method t := i.(T)
s := i.(string)
fmt.Println(s)
// Method t, ok := i.(T)
s, ok := i.(string)
fmt.Println(s, ok)
f := i.(float64) // panic
fmt.Println(f)
}
golang
golang true
panic: interface conversion: interface {} is string, not float64
If i does not hold a T, the statement will trigger a panic.
Hello, World! is the first basic program in any programming language.source code
package main
import "fmt"
func main() {
fmt.Println("Hello,世界,こんにちは,안녕하세요")
}
To run the program
Go is a compiled language. The Go toolchain converts a source program and the things it depends on into instructions in the native machine language of a computer.
use go run
go run helloworld.go
Hello,世界,こんにちは,안녕하세요
Go natively handles Unicode, so it can process text in all the world’s languages.
using go build
If the program is more than a one-shot experiment, it’s likely that you would want to compile it once and save the compiled result for later use. That is done with go build:
use go build
go build helloworld.go
./helloworld
Hello,世界,こんにちは,안녕하세요
The most common numeric conversions are Atoi. strconv.Atoi Function
Package strconv implements conversions to and from string representations of basic data types.
package main
import (
"fmt"
"strconv"
)
func main() {
i, err := strconv.Atoi("10") // i = 10
if err != nil {
//handle error
}
fmt.Printf("%T, %v\n", i, i)
//If the input string isn’t in the integer format, then the function returns zero.
i, err = strconv.Atoi("abc10") // i = 0
if err != nil {
//handle error
fmt.Println(err)
}
fmt.Printf("%T, %v\n", i, i)
i, err = strconv.Atoi("9223372036854775809") // i = 9223372036854775807
if err != nil {
//handle error
fmt.Println(err)
}
fmt.Printf("%T, %v\n", i, i)
}
int, 10
strconv.Atoi: parsing "abc10": invalid syntax
int, 0
strconv.Atoi: parsing "9223372036854775809": value out of range
int, 9223372036854775807
Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.
strconv.ParseInt Function
ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.
package main
import (
"fmt"
"strconv"
)
func main() {
// func strconv.ParseInt(s string, base int, bitSize int) (i int64, err error)
// fastest
v64 := "-10"
if s, err := strconv.ParseInt(v64, 10, 64); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
// contains invalid digits
v64 = "abc1"
if s, err := strconv.ParseInt(v64, 10, 64); err != nil {
fmt.Println(err)
fmt.Printf("%T, %v\n", s, s)
}
// func ParseUint(s string, base int, bitSize int) (uint64, error)
// ParseUint is like ParseInt but for unsigned numbers.
v64 = "100"
if s, err := strconv.ParseUint(v64, 10, 64); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
}
int64, -10
strconv.ParseInt: parsing "abc1": invalid syntax
int64, 0
uint64, 100
fmt.Sscanf Function
Sscanf scans the argument string, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.
package main
import "fmt"
func main() {
var name string
var car int
var dead int
// not terribly fast but most flexible
n, err := fmt.Sscanf("80-Car Pileup on Pennsylvania Highway Leaves 6 Dead", "%d-Car Pileup on %s Highway Leaves %d Dead", &car, &name, &dead)
if err != nil {
panic(err)
}
fmt.Printf("%d: %s, %d, %d\n", n, name, car, dead)
}
3: Pennsylvania, 80, 6
3 ways to find a key in a map. Use second return value directly in an if statement
If "BST" is indeed present in the map, the body of the if statement will be executed and v will be local to that scope.
package main
import "fmt"
func main() {
dict := map[string]int{
"UTC": 0 * 60 * 60,
"BST": 1 * 60 * 60,
}
if _, ok := dict["UTC"]; ok {
//do something here
fmt.Println(dict["UTC"])
}
}
3600
To test for presence in the map without worrying about the actual value, you can use the blank identifier (_) in place of the usual variable for the value.
Check second return value
if statements in Go can include both a condition and an initialization statement.
m := map[string]int{
"foo": 1,
"bar": 2
}
v, ok := m["foo"] // v == 1 ok == true
v, ok = m["foooo"] // v == 0 ok == false
_, ok = m["foo"] // ok == true
Check for zero value
if the map is nil or does not contain such an entry, a[x] is the zero value for the element type of M.
m := map[string]int{
"foo": 1
}
v := m["foo"] // v == 1
v = m["fooooo"] // v == 0 (zero value)
user interface to the TELNET protocol.
Telnet is an application protocol used on the Internet or local area network to provide a bidirectional interactive text-oriented communication facility using a virtual terminal connection. User data is interspersed in-band with Telnet control information in an 8-bit byte oriented data connection over the Transmission Control Protocol (TCP).
Installing Telnet Client on Linux
RHEL / CentOS / Fedora
dnf install telnet
Ubuntu / Debian
apt-get install telnet
Verify
telnet installmd.com 80
Trying ...
Connected to installmd.com.
Escape character is '^]'.
Connection closed by foreign host.
Telnet client
telnet IP/HOST PORT
Help
telnet --help
info telnet
man telnet
GET /path/to/file.html HTTP/1.1
Host: installmd.com
Connection: close
The syntax for the telnet command is as follows:
Usage:
telnet [-468EFKLacdfrx] [-X authtype] [-b hostalias] [-e escapechar] [-k realm] [-l user] [-n tracefile] [host [port]]
OPTIONS:
##### -4
Force IPv4 address resolution.
##### -6
Force IPv6 address resolution.
##### -7
Strip 8th bit on input and output. Telnet is 8-bit clean by default but doesn't send the TELNET BINARY option unless forced.
##### -8
Specifies an 8-bit data path. This causes an attempt to negotiate the TELNET BINARY option on both input and output.
##### -E
Stops any character from being recognized as an escape character.
##### -F
If Kerberos V5 authentication is being used, the -F option allows the local credentials to be forwarded to the remote system, including any cre‐dentials that have already been forwarded into the local environment.
##### -K
Specifies no automatic login to the remote system.
##### -L
Specifies an 8-bit data path on output. This causes the BINARY option to be negotiated on output.
##### -X atype
Disables the atype type of authentication.
##### -a
Attempt automatic login. Currently, this sends the user name via the USER variable of the ENVIRON option if supported by the remote system. The name used is that of the current user as returned by getlogin(2) if it agrees with the current user ID, otherwise it is the name associated with the user ID.
##### -b hostalias
Uses bind(2) on the local socket to bind it to an aliased address (see ifconfig(8) and the ''alias'' specifier) or to the address of another interface than the one naturally chosen by connect(2). This can be useful when connecting to services which use IP addresses for authentication and reconfiguration of the server is undesirable (or impossible).
##### -c
Disables the reading of the user's .telnetrc file. (See the toggle skiprc command on this man page.)
##### -d
Sets the initial value of the debug toggle to TRUE.
##### -e escapechar
Sets the initial telnet escape character to escapechar. If escapechar is omitted, then there will be no escape character.
##### -f
If Kerberos V5 authentication is being used, the -f option allows the local credentials to be forwarded to the remote system.
##### -k realm
If Kerberos authentication is being used, the -k option requests that telnet obtain tickets for the remote host in realm realm instead of the remote host's realm, as determined by krb_realmofhost.
##### -l user
When connecting to the remote system, if the remote system understands the ENVIRON option, then user will be sent to the remote system as the value for the variable USER. This option implies the -a option. This option may also be used with the open command.
##### -n tracefile
Opens tracefile for recording trace information. See the set tracefile command below.
##### -r
Specifies a user interface similar to rlogin(1). In this mode, the escape character is set to the tilde (~) character, unless modified by the -e option.
##### -x
Turns on encryption of the data stream if possible.
##### host
Indicates the official name, an alias, or the Internet address of a remote host.
##### port
Indicates a port number (address of an application). If a number is not specified, the default telnet port is used.
Create the DIRECTORY(ies), if they do not already exist.
mkdir command in Linux allows the user to create directories (also referred to as folders in some operating systems ). This command can create multiple directories at once as well as set the permissions for the directories.
New Directory
mkdir newdir
Help
mkdir --help
info mkdir
man mkdir
version information
mkdir --version
mkdir (GNU coreutils) 8.22
How to Create Parent Directories
make parent
mkdir -p /data/go
print a message
mkdir -v -p /data/go
mkdir: created directory ‘folder’
The syntax for the mkdir command is as follows:
Usage:
mkdir [OPTION]... DIRECTORY...
OPTIONS:
##### -m, --mode=MODE
set file mode (as in chmod), not a=rwx - umask
##### -p, --parents
no error if existing, make parent directories as needed
##### -v, --verbose
print a message for each created directory
##### -Z
set SELinux security context of each created directory to the default type
##### --context[=CTX]
like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX
##### --help
display this help and exit
##### --version
output version information and exit
history command is used to view the previously executed command.
The history command works with the command history list. When the command is issued with no options, it prints the history list.
The History library provides a history expansion feature that is similar to the history expansion provided by `csh'. This section describes the syntax used to manipulate the history information.
History
history
Help
grep --help
info history
man history
826 ll
827 mkdir software
To see a certain number of commands, you can pass a number to history on the command line.
10 commands
history 10
history | tail -n 10
Repeating Commands
!897
the last command
!!
the last command that started with cd
!cd
!cd:p
!?aliases
history | grep aliases
Deleting Commands
history -d 83
history -d 22 32
history -d -5
897 history 10
The syntax for the history command is as follows:
Usage:
history [-c] [-d offset] [n]
history -awrn [filename]
history -ps arg [arg...]
OPTIONS:
##### -d
Remove history entry at offset which from the history.
##### -c
Clearing the History List
terminate a process.
kill is a command that is used in several popular operating systems to send signals to running processes.
The command kill sends the specified signal to the specified process or process group. If no signal is specified, the TERM signal is sent. The TERM signal will kill processes which do not catch this signal. For other processes, it may be necessary to use the KILL (9) signal, since this signal cannot be caught.
To display all the available signals you can use below command option:
signals
kill -l
Help
man kill
info kill
the process ID
kill -s TERM 1234
kill -TERM 1234
kill -15 1234
kill -s KILL 1234
kill -KILL 1234
kill -9 1234
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1 64) SIGRTMAX
Terminating Processes Using the kill Command
killing
kill -9 $(pidof chrome)
reload nginx
kill -1 30251
kill
The syntax for the kill command is as follows:
Usage:
kill [-s signal|-p] [-q sigval] [-a] [--] pid...
kill -l [signal]
OPTIONS:
##### -s, --signal
Specify the signal to send. The signal may be given as a signal name or number.
##### -p, --pid
Specify that kill should only print the process id (pid) of the named processes, and not send any signals.
##### -l, --list [signal]
Print a list of signal names, or convert signal given as argument to a name. The signals are found in /usr/include/linux/signal.h
##### -L, --table
Similar to -l, but will print signal names and their corresponding numbers.
##### -p, --pid
Specify that kill should only print the process id (pid) of the named processes, and not send any signals.
##### -q, --queue sigval
Use sigqueue(2) rather than kill(2) and the sigval argument is used to specify an integer to be sent with the signal. If the receiving process has installed a handler for this signal using the SA_SIGINFO flag to sigaction(2), then it can obtain this data via the si_value field of the siginfo_t structure.
Print the first 10 lines of each FILE to standard output.
head is a program on Unix and Unix-like operating systems used to display the beginning of a text file or piped data.
By default, head will print the first 10 lines of its input to the standard output.
Print
head filename
Help
head --help
info head
man head
version information
head --version
head (GNU coreutils) 8.22
Display a Specific Number of Lines
first K lines
head -n 20 filename
Number of Bytes
head -c 100 filename
head -c 5k filename
using pipes
echo $RANDOM | sha512sum | head -c 24 ; echo
dd466c8fd2c8f9c53d35c629
The syntax for the head command is as follows:
Usage:
head [OPTION]... [FILE]...
OPTIONS:
##### -c, --bytes=[-]K
print the first K bytes of each file;
with the leading '-', print all but the last K bytes of each file
##### -n, --lines=[-]K
print the first K lines instead of the first 10; with the leading '-', print all but the last K lines of each file
##### -q, --quiet, --silent
never print headers giving file names
##### -v, --verbose
always print headers giving file names
##### --help
display this help and exit
##### --version
output version information and exit
K may have a multiplier suffix:b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.
Compress or uncompress FILEs.
Gzip reduces the size of the named files using Lempel-Ziv coding (LZ77). Whenever possible, each file is replaced by one with the extension .gz, while keeping the same ownership modes, access and modi‐fication times.
Compress
gzip -k filename.md
Help
gzip --help
gzip -h
info gzip
man gzip
version information
gzip --version
gzip -V
filename.md.gz
gzip 1.5
Compressing Files with gzip
Keep the original file
gzip -k filename.md
gzip -c filename.md > filename.md.gz
Verbose output
gzip -v filename.md
multiple files
gzip file1 file2 file3
directory
gzip -r folder
standard input
history | gzip -c > history.gz
Decompressing
gzip -d filename.md.gz
filename.md: -18.2% -- replaced with filename.md.gz
The syntax for the gzip command is as follows:
Usage:
gzip [OPTION]... [FILE]...
OPTIONS:
##### -c, --stdout
write on standard output, keep original files unchanged
##### -d, --decompress
decompress
##### -f, --force
force overwrite of output file and compress links
##### -h, --help
give this help
##### -l, --list
list compressed file contents
##### -L, --license
display software license
##### -n, --no-name
do not save or restore the original name and time stamp
##### -N, --name
save or restore the original name and time stamp
##### -q, --quiet
suppress all warnings
##### -r, --recursive
operate recursively on directories
##### -S, --suffix=SUF
use suffix SUF on compressed files
##### -t, --test
test compressed file integrity
##### -v, --verbose
verbose mode
##### -V, --version
display version number
##### -1, --fast
compress faster
##### -9, --best
compress better
##### --rsyncable
Make rsync-friendly archive
With no FILE, or when FILE is -, read standard input.