├── .github └── workflows │ ├── check.yml │ └── sync.yml ├── .gitignore ├── README.md ├── bin └── gophersnippets ├── docs ├── CNAME ├── css │ ├── highlight.css │ └── spectre.min.css ├── how-to-calculate-the-hamming-distance-between-two-strings.html ├── how-to-calculate-the-sum-of-multiple-numbers.html ├── how-to-check-if-a-slice-contains-a-specific-element.html ├── how-to-check-if-a-string-ends-with-a-substring.html ├── how-to-check-if-a-string-is-lowercase.html ├── how-to-check-if-a-string-is-uppercase.html ├── how-to-check-if-a-string-starts-with-substring.html ├── how-to-check-if-a-type-satisfies-an-interface-at-runtime.html ├── how-to-check-if-string-is-valid-json.html ├── how-to-check-that-a-time-value-is-a-specific-day-of-the-week.html ├── how-to-concatenate-strings.html ├── how-to-convert-int-to-string.html ├── how-to-copy-a-map.html ├── how-to-count-the-number-of-words-in-a-string.html ├── how-to-create-a-set-using-a-map.html ├── how-to-create-multiple-loggers.html ├── how-to-define-a-custom-string-representation-for-a-type.html ├── how-to-define-a-custom-string-representation-of-a-type.html ├── how-to-delete-an-element-from-a-slice.html ├── how-to-disable-log-output.html ├── how-to-filter-a-slice.html ├── how-to-find-the-maximum-element-of-a-slice.html ├── how-to-find-the-minimum-element-of-a-slice.html ├── how-to-format-go-code-programmatically.html ├── how-to-get-the-md5-checksum-of-a-string.html ├── how-to-get-the-sha1-checksum-of-a-string.html ├── how-to-get-the-sha256-checksum-of-a-string.html ├── how-to-include-the-filename-and-the-line-number-in-a-logger-output.html ├── how-to-measure-the-execution-time-of-a-function.html ├── how-to-parse-comments-from-go-code.html ├── how-to-pretty-print-json.html ├── how-to-print-a-raw-http-response.html ├── how-to-print-go-version.html ├── how-to-print-information-about-the-operating-system-architecture-and-pointer-size.html ├── how-to-print-the-binary-representation-of-an-integer.html ├── how-to-print-the-same-variable-multiple-times-using-printf.html ├── how-to-read-an-http-response-status-code.html ├── how-to-remove-duplicate-elements-from-a-slice.html ├── how-to-reverse-a-slice.html ├── how-to-reverse-a-string.html ├── how-to-shuffle-a-slice.html ├── how-to-split-a-slice-in-chunks.html ├── how-to-test-a-function-that-panics.html ├── index.html └── what-is-the-maximum-value-of-numeric-types.html ├── snippets ├── how-to-calculate-the-hamming-distance-between-two-strings │ ├── main_test.go │ └── metadata.yml ├── how-to-calculate-the-sum-of-multiple-numbers │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-slice-contains-a-specific-element │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-string-ends-with-a-substring │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-string-is-lowercase │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-string-is-uppercase │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-string-starts-with-substring │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-type-satisfies-an-interface-at-runtime │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-string-is-valid-json │ ├── main_test.go │ └── metadata.yml ├── how-to-check-that-a-time-value-is-a-specific-day-of-the-week │ ├── main_test.go │ └── metadata.yml ├── how-to-concatenate-strings │ ├── main_test.go │ └── metadata.yml ├── how-to-convert-int-to-string │ ├── main_test.go │ └── metadata.yml ├── how-to-copy-a-map │ ├── main_test.go │ └── metadata.yml ├── how-to-count-the-number-of-words-in-a-string │ ├── main_test.go │ └── metadata.yml ├── how-to-create-a-set-using-a-map │ ├── main_test.go │ └── metadata.yml ├── how-to-create-multiple-loggers │ ├── main_test.go │ └── metadata.yml ├── how-to-define-a-custom-string-representation-for-a-type │ ├── main_test.go │ └── metadata.yml ├── how-to-delete-an-element-from-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-disable-log-output │ ├── main_test.go │ └── metadata.yml ├── how-to-filter-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-find-the-maximum-element-of-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-find-the-minimum-element-of-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-format-go-code-programmatically │ ├── main_test.go │ └── metadata.yml ├── how-to-get-the-md5-checksum-of-a-string │ ├── main_test.go │ └── metadata.yml ├── how-to-get-the-sha1-checksum-of-a-string │ ├── main_test.go │ └── metadata.yml ├── how-to-get-the-sha256-checksum-of-a-string │ ├── main_test.go │ └── metadata.yml ├── how-to-include-the-filename-and-the-line-number-in-a-logger-output │ ├── main_test.go │ └── metadata.yml ├── how-to-measure-the-execution-time-of-a-function │ ├── main_test.go │ └── metadata.yml ├── how-to-parse-comments-from-go-code │ ├── main_test.go │ └── metadata.yml ├── how-to-pretty-print-json │ ├── main_test.go │ └── metadata.yml ├── how-to-print-a-raw-http-response │ ├── main_test.go │ └── metadata.yml ├── how-to-print-go-version │ ├── main_test.go │ └── metadata.yml ├── how-to-print-information-about-the-operating-system-architecture-and-pointer-size │ ├── main_test.go │ └── metadata.yml ├── how-to-print-the-binary-representation-of-an-integer │ ├── main_test.go │ └── metadata.yml ├── how-to-print-the-same-variable-multiple-times-using-printf │ ├── main_test.go │ └── metadata.yml ├── how-to-read-an-http-response-status-code │ ├── main_test.go │ └── metadata.yml ├── how-to-remove-duplicate-elements-from-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-reverse-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-reverse-a-string │ ├── main_test.go │ └── metadata.yml ├── how-to-shuffle-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-split-a-slice-in-chunks │ ├── main_test.go │ └── metadata.yml ├── how-to-test-a-function-that-panics │ ├── main_test.go │ └── metadata.yml └── what-is-the-maximum-value-of-numeric-types │ ├── main_test.go │ └── metadata.yml └── tools └── templates ├── html_index.html ├── html_page.html ├── issue.tmpl └── readme.md /.github/workflows/check.yml: -------------------------------------------------------------------------------- 1 | name: check-pr 2 | on: 3 | pull_request: 4 | branches: 5 | - master 6 | jobs: 7 | check-pr: 8 | name: check-pr 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - uses: actions/setup-go@v1 13 | with: 14 | go-version: 1.14.2 15 | - name: go vet 16 | run: | 17 | cd snippets 18 | go vet ./... 19 | - name: code compiles on playground, includes tests and has the correct format 20 | run: | 21 | ./bin/gophersnippets -pr-check -playground -playground-ua="gophersnippets.com/v1" 22 | -------------------------------------------------------------------------------- /.github/workflows/sync.yml: -------------------------------------------------------------------------------- 1 | name: sync-issues-with-content 2 | on: 3 | push: 4 | branches: 5 | - master 6 | jobs: 7 | sync-content-issues: 8 | name: sync-issues-with-content 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | with: 13 | persist-credentials: false 14 | - name: generate html content 15 | run: | 16 | GITHUBTOKEN=${{ secrets.GITHUBTOKEN }} GITHUB_REPOSITORY=${{ github.repository }} ./bin/gophersnippets -github-issues -playground -playground-ua="gophersnippets.com/v1" 17 | git config --global user.email "${{ secrets.GIT_EMAIL }}" 18 | git config --global user.name "${{ secrets.GIT_NAME }}" 19 | git add . 20 | git diff --staged --quiet || git commit -m "generate html content" 21 | - name: Push changes 22 | uses: ad-m/github-push-action@master 23 | with: 24 | github_token: ${{ secrets.GITHUBTOKEN }} 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea -------------------------------------------------------------------------------- /bin/gophersnippets: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/psampaz/gophersnippets/ca75d4a5c068ee21e8c5b37b1e9d6c4ba60fb16d/bin/gophersnippets -------------------------------------------------------------------------------- /docs/CNAME: -------------------------------------------------------------------------------- 1 | gophersnippets.com -------------------------------------------------------------------------------- /docs/css/highlight.css: -------------------------------------------------------------------------------- 1 | /* Background */ .chroma { background-color: #f9f9f9 } 2 | /* Error */ .chroma .err { } 3 | /* LineTableTD */ .chroma .lntd { vertical-align: top; padding: 0; margin: 0; border: 0; } 4 | /* LineTable */ .chroma .lntable { border-spacing: 0; padding: 0; margin: 0; border: 0; width: auto; overflow: auto; display: block; } 5 | /* LineHighlight */ .chroma .hl { display: block; width: 100%;background-color: #e5e5e5 } 6 | /* LineNumbersTable */ .chroma .lnt { margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #7f7f7f } 7 | /* LineNumbers */ .chroma .ln { margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #7f7f7f } 8 | /* Keyword */ .chroma .k { color: #008000; font-weight: bold } 9 | /* KeywordConstant */ .chroma .kc { color: #008000; font-weight: bold } 10 | /* KeywordDeclaration */ .chroma .kd { color: #008000; font-weight: bold } 11 | /* KeywordNamespace */ .chroma .kn { color: #008000; font-weight: bold } 12 | /* KeywordPseudo */ .chroma .kp { color: #008000 } 13 | /* KeywordReserved */ .chroma .kr { color: #008000; font-weight: bold } 14 | /* KeywordType */ .chroma .kt { color: #b00040 } 15 | /* NameAttribute */ .chroma .na { color: #7d9029 } 16 | /* NameBuiltin */ .chroma .nb { color: #008000 } 17 | /* NameClass */ .chroma .nc { color: #0000ff; font-weight: bold } 18 | /* NameConstant */ .chroma .no { color: #880000 } 19 | /* NameDecorator */ .chroma .nd { color: #aa22ff } 20 | /* NameEntity */ .chroma .ni { color: #999999; font-weight: bold } 21 | /* NameException */ .chroma .ne { color: #d2413a; font-weight: bold } 22 | /* NameFunction */ .chroma .nf { color: #0000ff } 23 | /* NameLabel */ .chroma .nl { color: #a0a000 } 24 | /* NameNamespace */ .chroma .nn { color: #0000ff; font-weight: bold } 25 | /* NameTag */ .chroma .nt { color: #008000; font-weight: bold } 26 | /* NameVariable */ .chroma .nv { color: #19177c } 27 | /* LiteralString */ .chroma .s { color: #ba2121 } 28 | /* LiteralStringAffix */ .chroma .sa { color: #ba2121 } 29 | /* LiteralStringBacktick */ .chroma .sb { color: #ba2121 } 30 | /* LiteralStringChar */ .chroma .sc { color: #ba2121 } 31 | /* LiteralStringDelimiter */ .chroma .dl { color: #ba2121 } 32 | /* LiteralStringDoc */ .chroma .sd { color: #ba2121; font-style: italic } 33 | /* LiteralStringDouble */ .chroma .s2 { color: #ba2121 } 34 | /* LiteralStringEscape */ .chroma .se { color: #bb6622; font-weight: bold } 35 | /* LiteralStringHeredoc */ .chroma .sh { color: #ba2121 } 36 | /* LiteralStringInterpol */ .chroma .si { color: #bb6688; font-weight: bold } 37 | /* LiteralStringOther */ .chroma .sx { color: #008000 } 38 | /* LiteralStringRegex */ .chroma .sr { color: #bb6688 } 39 | /* LiteralStringSingle */ .chroma .s1 { color: #ba2121 } 40 | /* LiteralStringSymbol */ .chroma .ss { color: #19177c } 41 | /* LiteralNumber */ .chroma .m { color: #666666 } 42 | /* LiteralNumberBin */ .chroma .mb { color: #666666 } 43 | /* LiteralNumberFloat */ .chroma .mf { color: #666666 } 44 | /* LiteralNumberHex */ .chroma .mh { color: #666666 } 45 | /* LiteralNumberInteger */ .chroma .mi { color: #666666 } 46 | /* LiteralNumberIntegerLong */ .chroma .il { color: #666666 } 47 | /* LiteralNumberOct */ .chroma .mo { color: #666666 } 48 | /* Operator */ .chroma .o { color: #666666 } 49 | /* OperatorWord */ .chroma .ow { color: #aa22ff; font-weight: bold } 50 | /* Comment */ .chroma .c { color: #408080; font-style: italic } 51 | /* CommentHashbang */ .chroma .ch { color: #408080; font-style: italic } 52 | /* CommentMultiline */ .chroma .cm { color: #408080; font-style: italic } 53 | /* CommentSingle */ .chroma .c1 { color: #408080; font-style: italic } 54 | /* CommentSpecial */ .chroma .cs { color: #408080; font-style: italic } 55 | /* CommentPreproc */ .chroma .cp { color: #bc7a00 } 56 | /* CommentPreprocFile */ .chroma .cpf { color: #bc7a00 } 57 | /* GenericDeleted */ .chroma .gd { color: #a00000 } 58 | /* GenericEmph */ .chroma .ge { font-style: italic } 59 | /* GenericError */ .chroma .gr { color: #ff0000 } 60 | /* GenericHeading */ .chroma .gh { color: #000080; font-weight: bold } 61 | /* GenericInserted */ .chroma .gi { color: #00a000 } 62 | /* GenericOutput */ .chroma .go { color: #888888 } 63 | /* GenericPrompt */ .chroma .gp { color: #000080; font-weight: bold } 64 | /* GenericStrong */ .chroma .gs { font-weight: bold } 65 | /* GenericSubheading */ .chroma .gu { color: #800080; font-weight: bold } 66 | /* GenericTraceback */ .chroma .gt { color: #0044dd } 67 | /* GenericUnderline */ .chroma .gl { text-decoration: underline } 68 | /* TextWhitespace */ .chroma .w { color: #bbbbbb } -------------------------------------------------------------------------------- /docs/how-to-check-if-a-string-ends-with-a-substring.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 6 | 7 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | "strings" 26 | ) 27 | 28 | func Example() { 29 | fmt.Println(strings.HasSuffix("abcdefg", "fg")) 30 | fmt.Println(strings.HasSuffix("abcdefg", "Fg")) 31 | // Output: 32 | // true 33 | // false 34 | } 35 |36 | 37 |
38 | by psampaz - 39 | source code - comment below or here 41 |
42 | 49 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | "strings" 26 | ) 27 | 28 | func Example() { 29 | fmt.Println(strings.HasPrefix("abcdefg", "ab")) 30 | fmt.Println(strings.HasPrefix("abcdefg", "Ab")) 31 | // Output: 32 | // true 33 | // false 34 | } 35 |36 | 37 |
38 | by psampaz - 39 | source code - comment below or here 41 |
42 | 49 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "encoding/json" 25 | "fmt" 26 | ) 27 | 28 | func Example() { 29 | valid := `{"foo":"bar"}` 30 | invalid := `}{` 31 | 32 | fmt.Println(json.Valid([]byte(valid))) 33 | fmt.Println(json.Valid([]byte(invalid))) 34 | // Output: 35 | // true 36 | // false 37 | } 38 |39 | 40 |
41 | by psampaz - 42 | source code - comment below or here 44 |
45 | 52 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | "time" 26 | ) 27 | 28 | func Example() { 29 | // The time package offers a time.Weekday() method which returns 30 | // a time.Weekday value https://pkg.go.dev/time?tab=doc#Weekday 31 | now := time.Now() 32 | if now.Weekday() == time.Tuesday { 33 | fmt.Println("The day on Go playground is always Tuesday") 34 | } 35 | // Output: 36 | // The day on Go playground is always Tuesday 37 | } 38 |39 | 40 |
41 | by psampaz - 42 | source code - comment below or here 44 |
45 | 52 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | "strings" 26 | ) 27 | 28 | func Example() { 29 | // Create a slice of the strings that you want to join together 30 | strs := []string{"aa", "bb", "cc"} 31 | //Use the strings.Join function to join them, by passing the desired separator 32 | fmt.Println(strings.Join(strs, "-")) 33 | fmt.Println(strings.Join(strs, ", ")) 34 | fmt.Println(strings.Join(strs, "")) 35 | // Output: 36 | // aa-bb-cc 37 | // aa, bb, cc 38 | // aabbcc 39 | } 40 |41 | 42 |
43 | by psampaz - 44 | source code - comment below or here 46 |
47 | 54 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | "strconv" 26 | ) 27 | 28 | func Example_itoa() { 29 | // Converting an int to a string can be done 30 | // using the `strconv.Itoa` (integer to ascii) function 31 | a := strconv.Itoa(1234) 32 | fmt.Printf("%q\n", a) 33 | // Output: 34 | // "1234" 35 | } 36 | 37 | func Example_formatInt() { 38 | // `strconv.Itoa` is calls internally 39 | // `FormatInt(int64(i), 10)` so another way 40 | // to convert an int to a string is the following: 41 | b := strconv.FormatInt(int64(1234), 10) 42 | fmt.Printf("%q\n", b) 43 | // Output: 44 | // "1234" 45 | } 46 | 47 | func Example_sprintf() { 48 | // A third way would be to use the `fmt.Sprintf` method: 49 | c := fmt.Sprintf("%d", 1234) 50 | fmt.Printf("%q\n", c) 51 | // Output: 52 | // "1234" 53 | } 54 |55 | 56 |
57 | by psampaz - 58 | source code - comment below or here 60 |
61 | 68 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | "strings" 26 | ) 27 | 28 | // strings.Fields() splits a string around one or more 29 | // consecutive whitespaces (https://golang.org/pkg/unicode/#IsSpace) 30 | // The number of fields is the actual number of words 31 | func CountWords(s string) int { 32 | return len(strings.Fields(s)) 33 | } 34 | 35 | // If the words are not separated by whitespaces 36 | // but with comma (a csv row for example) or whatever else, 37 | // you can use the strings.FieldsFunc() and explicitly define 38 | // the points of split 39 | func CountWordsFunc(s string, f func(rune) bool) int { 40 | return len(strings.FieldsFunc(s, f)) 41 | } 42 | 43 | func ExampleCountWords() { 44 | wc := CountWords(" How to count words? \n") 45 | fmt.Println(wc) 46 | // Output: 47 | // 4 48 | } 49 | 50 | func ExampleCountWordsFunc() { 51 | f := func(c rune) bool { 52 | return c == ',' 53 | } 54 | wc := CountWordsFunc("word1, word2, word3", f) 55 | fmt.Println(wc) 56 | // Output: 57 | // 3 58 | } 59 |60 | 61 |
62 | by psampaz - 63 | source code - comment below or here 65 |
66 | 73 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import "fmt" 24 | 25 | // A set is a unordered collection of unique data. 26 | // Go does not have a built-in set data structure 27 | // but you can easily create one using a map 28 | func Example() { 29 | // The map keys are a unique unordered collection. 30 | // So if you just ignore the values, a map can be viewed as a set 31 | // The most space optimized way to do this is to use the empty struct 32 | // as the map value type, since the empty struct (a struct with no fields) 33 | // occupies zero bytes of storage 34 | // https://dave.cheney.net/2014/03/25/the-empty-struct 35 | set := make(map[string]struct{}) 36 | fmt.Println(set) 37 | // Add new elements in the set 38 | set["a"] = struct{}{} 39 | set["b"] = struct{}{} 40 | set["c"] = struct{}{} 41 | fmt.Println(set) 42 | 43 | // Check if an element exists in the set 44 | if _, exists := set["a"]; exists { 45 | fmt.Println("a exists in the set") 46 | } 47 | // Delete an element from the set 48 | delete(set, "b") 49 | fmt.Println(set) 50 | // Output: 51 | // map[] 52 | // map[a:{} b:{} c:{}] 53 | // a exists in the set 54 | // map[a:{} c:{}] 55 | } 56 |57 | 58 |
59 | by psampaz - 60 | source code - comment below or here 62 |
63 | 70 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "log" 25 | "os" 26 | ) 27 | 28 | func Example() { 29 | // You can create as many loggers you want using the log.New method 30 | // Each logger can write logs in different targets, use different prefix 31 | // and different settings 32 | logger1 := log.New(os.Stdout, "logger1: ", log.LstdFlags) 33 | logger2 := log.New(os.Stdout, "logger2: ", log.LstdFlags|log.Lmicroseconds) 34 | logger1.Println("Message from logger1") 35 | logger2.Println("Message from logger2") 36 | // Output: 37 | // logger1: 2009/11/10 23:00:00 Message from logger1 38 | // logger2: 2009/11/10 23:00:00.000000 Message from logger2 39 | } 40 |41 | 42 |
43 | by psampaz - 44 | source code - comment below or here 46 |
47 | 54 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import "fmt" 24 | 25 | // UserA does not implement the Stringer interface 26 | type UserA struct { 27 | FirstName string 28 | LastName string 29 | } 30 | 31 | // UserB implements the Stringer interface 32 | type UserB struct { 33 | FirstName string 34 | LastName string 35 | } 36 | 37 | func (u UserB) String() string { 38 | return fmt.Sprintf("First name is %s, last name is %s", u.FirstName, u.LastName) 39 | } 40 | 41 | // BoolA does implements the Stringer interface 42 | type BoolA bool 43 | 44 | // BoolB implements the Stringer interface 45 | type BoolB bool 46 | 47 | func (b BoolB) String() string { 48 | if b { 49 | return "Yes" 50 | } else { 51 | return "No" 52 | } 53 | } 54 | 55 | // To control the string representation of a type 56 | // the type needs to implement the Stringer interface 57 | // https://pkg.go.dev/fmt?tab=doc#Stringer 58 | // type Stringer interface { 59 | // String() string 60 | // } 61 | // The String method is used to print values passed as an operand 62 | // to any format that accepts a string or to an unformatted printer 63 | // such as Print. 64 | func Example() { 65 | a := UserA{"John", "Doe"} 66 | b := UserB{"John", "Doe"} 67 | c := BoolA(true) 68 | d := BoolB(true) 69 | 70 | fmt.Println(a) 71 | fmt.Println(b) 72 | fmt.Println(c) 73 | fmt.Println(d) 74 | // Output: 75 | // {John Doe} 76 | // First name is John, last name is Doe 77 | // true 78 | // Yes 79 | } 80 |81 | 82 |
83 | by psampaz - 84 | source code - comment below or here 86 |
87 | 94 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "io/ioutil" 25 | "log" 26 | ) 27 | 28 | func Example() { 29 | // If you want to disable log output (during test for example) 30 | // you have to set the logger ouput to ioutil.Discard 31 | // which is an io.Writer on which all Write calls succeed 32 | // without doing anything 33 | log.SetOutput(ioutil.Discard) 34 | log.Println("log disabled") 35 | // Output: 36 | // 37 | } 38 |39 | 40 |
41 | by psampaz - 42 | source code - comment below or here 44 |
45 | 52 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
// Code can be formatted programmatically in the same way like running go fmt, 22 | // using the go/format package 23 | package main 24 | 25 | import ( 26 | "fmt" 27 | "go/format" 28 | "log" 29 | ) 30 | 31 | func Example() { 32 | unformatted := ` 33 | package main 34 | import "fmt" 35 | 36 | func main( ) { 37 | x := 12 38 | fmt.Printf( "%d", x ) 39 | } 40 | 41 | 42 | ` 43 | formatted, err := format.Source([]byte(unformatted)) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | fmt.Printf("%s", string(formatted)) 48 | // Output: 49 | // package main 50 | // 51 | // import "fmt" 52 | // 53 | // func main() { 54 | // x := 12 55 | // fmt.Printf("%d", x) 56 | // } 57 | } 58 |59 | 60 |
61 | by psampaz - 62 | source code - comment below or here 64 |
65 | 72 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "crypto/md5" 25 | "fmt" 26 | "testing" 27 | ) 28 | 29 | func md5Checksum(s string) string { 30 | return fmt.Sprintf("%x", md5.Sum([]byte(s))) 31 | } 32 | 33 | func Test_md5Checksum(t *testing.T) { 34 | tests := []struct { 35 | name string 36 | s string 37 | want string 38 | }{ 39 | { 40 | name: "empty string", 41 | s: "", 42 | want: "d41d8cd98f00b204e9800998ecf8427e", 43 | }, 44 | { 45 | name: "hello world", 46 | s: "hello world", 47 | want: "5eb63bbbe01eeed093cb22bb8f5acdc3", 48 | }, 49 | } 50 | for _, tt := range tests { 51 | t.Run(tt.name, func(t *testing.T) { 52 | if got := md5Checksum(tt.s); got != tt.want { 53 | t.Errorf("md5Checksum(%q) = %v, want %v", tt.s, got, tt.want) 54 | } 55 | }) 56 | } 57 | } 58 |59 | 60 |
61 | by psampaz - 62 | source code - comment below or here 64 |
65 | 72 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "crypto/sha1" 25 | "fmt" 26 | "testing" 27 | ) 28 | 29 | func Sha1Checksum(s string) string { 30 | return fmt.Sprintf("%x", sha1.Sum([]byte(s))) 31 | } 32 | 33 | func Test_Sha1Checksum(t *testing.T) { 34 | tests := []struct { 35 | name string 36 | s string 37 | want string 38 | }{ 39 | { 40 | name: "empty string", 41 | s: "", 42 | want: "da39a3ee5e6b4b0d3255bfef95601890afd80709", 43 | }, 44 | { 45 | name: "hello world", 46 | s: "hello world", 47 | want: "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed", 48 | }, 49 | } 50 | for _, tt := range tests { 51 | t.Run(tt.name, func(t *testing.T) { 52 | if got := Sha1Checksum(tt.s); got != tt.want { 53 | t.Errorf("Sha1Checksum(%q) = %v, want %v", tt.s, got, tt.want) 54 | } 55 | }) 56 | } 57 | } 58 |59 | 60 |
61 | by psampaz - 62 | source code - comment below or here 64 |
65 | 72 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "crypto/sha256" 25 | "fmt" 26 | "testing" 27 | ) 28 | 29 | func Sha256Checksum(s string) string { 30 | return fmt.Sprintf("%x", sha256.Sum256([]byte(s))) 31 | } 32 | 33 | func Test_Sha256Checksum(t *testing.T) { 34 | tests := []struct { 35 | name string 36 | s string 37 | want string 38 | }{ 39 | { 40 | name: "empty string", 41 | s: "", 42 | want: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", 43 | }, 44 | { 45 | name: "hello world", 46 | s: "hello world", 47 | want: "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9", 48 | }, 49 | } 50 | for _, tt := range tests { 51 | t.Run(tt.name, func(t *testing.T) { 52 | if got := Sha256Checksum(tt.s); got != tt.want { 53 | t.Errorf("Sha256Checksum(%q) = %v, want %v", tt.s, got, tt.want) 54 | } 55 | }) 56 | } 57 | } 58 |59 | 60 |
61 | by psampaz - 62 | source code - comment below or here 64 |
65 | 72 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "log" 25 | "os" 26 | ) 27 | 28 | func Example() { 29 | // You can configure the output format of a logger using 30 | // flags https://golang.org/pkg/log/#pkg-constants 31 | // Use log.LshortfileIf to print the filename without 32 | // the full path and the line number or 33 | // Use log.Llongfile to print the filename with 34 | // the full path and the line number 35 | // The log.Llongfile example is not included below 36 | // because playground use different path each time 37 | log.SetOutput(os.Stdout) 38 | log.SetFlags(log.Lshortfile) 39 | log.Println("Hello world") 40 | // Output: 41 | // prog.go:20: Hello world 42 | } 43 |44 | 45 |
46 | by psampaz - 47 | source code - comment below or here 49 |
50 | 57 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
// This example demonstrates simple execution time calculation 22 | // If you need a detailed report on a function's performance 23 | // you should use Go benchmark functions 24 | // https://golang.org/pkg/testing/#hdr-Benchmarks 25 | // https://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go 26 | package main 27 | 28 | import ( 29 | "fmt" 30 | "time" 31 | ) 32 | 33 | func f() { 34 | // first we calculate the exact time the function 35 | // started the execution 36 | start := time.Now() 37 | // Then we calculate the execution time duration 38 | // inside a deferred function, since it will be execute after f() returns 39 | defer func(start time.Time) { 40 | dur := time.Since(start) 41 | fmt.Printf("f() took %0.0f to execute", dur.Seconds()) 42 | }(start) 43 | // pause the execution for 2 seconds 44 | time.Sleep(2 * time.Second) 45 | } 46 | 47 | func Example() { 48 | f() 49 | // Output: 50 | // f() took 2 to execute 51 | } 52 |53 | 54 |
55 | by psampaz - 56 | source code - comment below or here 58 |
59 | 66 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
// Comments from Go code can be parsed using 22 | // go/parser package 23 | package main 24 | 25 | import ( 26 | "fmt" 27 | "go/parser" 28 | "go/token" 29 | ) 30 | 31 | func Example() { 32 | src := ` 33 | // Calculator package provides methods 34 | // for basic int calculation 35 | package calculator 36 | 37 | // Import of fmt package 38 | import "fmt" 39 | 40 | // Add adds two integers 41 | func Add(a, b int) int { 42 | // calculate the result 43 | result := a + b 44 | // return the result 45 | return result 46 | } 47 | ` 48 | fs := token.NewFileSet() 49 | f, err := parser.ParseFile(fs, "", src, parser.ParseComments) 50 | if err != nil { 51 | fmt.Println(err) 52 | return 53 | } 54 | 55 | for _, c := range f.Comments { 56 | fmt.Println(c.Text()) 57 | } 58 | // Output: 59 | // Calculator package provides methods 60 | // for basic int calculation 61 | // 62 | // Import of fmt package 63 | // 64 | // Add adds two integers 65 | // 66 | // calculate the result 67 | // 68 | // return the result 69 | } 70 |71 | 72 |
73 | by psampaz - 74 | source code - comment below or here 76 |
77 | 84 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "encoding/json" 25 | "fmt" 26 | ) 27 | 28 | type Student struct { 29 | Name string 30 | Age string 31 | Lessons []string 32 | } 33 | 34 | func Example() { 35 | s := Student{ 36 | Name: "John", 37 | Age: "17", 38 | Lessons: []string{ 39 | "Mathematics", 40 | "Computer science", 41 | "Philosophy", 42 | }, 43 | } 44 | 45 | // By using json.Marshal the output will be one line json string 46 | // which is difficult to read or debug 47 | jsonBytes, err := json.Marshal(s) 48 | if err != nil { 49 | fmt.Println(err) 50 | } 51 | fmt.Printf("\nUgly print:\n%s\n", jsonBytes) 52 | 53 | // The easiest way to achieve a human readable and pretty print 54 | // is to use the json.MarshalIndent 55 | jsonBytes, err = json.MarshalIndent(s, "", "\t") 56 | if err != nil { 57 | fmt.Println(err) 58 | } 59 | fmt.Printf("\nPretty print:\n%s\n", jsonBytes) 60 | // Output: 61 | // 62 | // Ugly print: 63 | // {"Name":"John","Age":"17","Lessons":["Mathematics","Computer science","Philosophy"]} 64 | // 65 | // Pretty print: 66 | // { 67 | // "Name": "John", 68 | // "Age": "17", 69 | // "Lessons": [ 70 | // "Mathematics", 71 | // "Computer science", 72 | // "Philosophy" 73 | // ] 74 | // } 75 | } 76 |77 | 78 |
79 | by psampaz - 80 | source code - comment below or here 82 |
83 | 90 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | "log" 26 | "net/http" 27 | "net/http/httptest" 28 | "net/http/httputil" 29 | ) 30 | 31 | func Example() { 32 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 33 | w.Header().Set("Date", "Wed, 01 Jan 2020 00:00:00 GMT") 34 | w.WriteHeader(http.StatusOK) 35 | w.Write([]byte("hello world")) 36 | })) 37 | defer ts.Close() 38 | 39 | resp, err := http.Get(ts.URL) 40 | if err != nil { 41 | fmt.Println(err) 42 | } 43 | defer resp.Body.Close() 44 | 45 | // DumpResponse returns wire representation 46 | // of the http response 47 | dump, err := httputil.DumpResponse(resp, true) 48 | if err != nil { 49 | log.Fatal(err) 50 | } 51 | // %q is used here to make the testable example work 52 | // use %s to print in multiple lines: 53 | // HTTP/1.1 200 OK 54 | // Content-Length: 11 55 | // Content-Type: text/plain; charset=utf-8 56 | // Date: Wed, 01 Jan 2020 00:00:00 GMT 57 | // 58 | // hello world 59 | fmt.Printf("%q", dump) 60 | // Output: 61 | // "HTTP/1.1 200 OK\r\nContent-Length: 11\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Wed, 01 Jan 2020 00:00:00 GMT\r\n\r\nhello world" 62 | } 63 |64 | 65 |
66 | by psampaz - 67 | source code - comment below or here 69 |
70 | 77 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | "runtime" 26 | ) 27 | 28 | func Example() { 29 | fmt.Printf("Go version: %s\n", runtime.Version()) 30 | // Output: 31 | // Go version: go1.14.2 32 | } 33 |34 | 35 |
36 | by psampaz - 37 | source code - comment below or here 39 |
40 | 47 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | "runtime" 26 | "unsafe" 27 | ) 28 | 29 | func Example() { 30 | fmt.Printf("running program's operating system target: %s\n", runtime.GOOS) 31 | fmt.Printf("running program's architecture target: %s\n", runtime.GOARCH) 32 | var ptr uintptr 33 | ptrSize := int(unsafe.Sizeof(ptr)) 34 | fmt.Printf("pointer size: %d\n", ptrSize) 35 | // Output: 36 | // running program's operating system target: linux 37 | // running program's architecture target: amd64 38 | // pointer size: 8 39 | } 40 |41 | 42 |
43 | by psampaz - 44 | source code - comment below or here 46 |
47 | 54 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | ) 26 | 27 | func Example() { 28 | // The %b verb print the binary representation of an integer 29 | for x := 0; x < 16; x++ { 30 | fmt.Printf("%b\n", x) 31 | } 32 | // If you want the output to have the same length, 8 bits for example 33 | // use the %08b notation which means: 34 | // print binary, use 8 digits for the output, pad with leading zeros 35 | fmt.Println("fixed length of 8 digits:") 36 | for x := 0; x < 16; x++ { 37 | fmt.Printf("%08b\n", x) 38 | } 39 | // Output: 40 | // 0 41 | // 1 42 | // 10 43 | // 11 44 | // 100 45 | // 101 46 | // 110 47 | // 111 48 | // 1000 49 | // 1001 50 | // 1010 51 | // 1011 52 | // 1100 53 | // 1101 54 | // 1110 55 | // 1111 56 | // fixed length of 8 digits: 57 | // 00000000 58 | // 00000001 59 | // 00000010 60 | // 00000011 61 | // 00000100 62 | // 00000101 63 | // 00000110 64 | // 00000111 65 | // 00001000 66 | // 00001001 67 | // 00001010 68 | // 00001011 69 | // 00001100 70 | // 00001101 71 | // 00001110 72 | // 00001111 73 | } 74 |75 | 76 |
77 | by psampaz - 78 | source code - comment below or here 80 |
81 | 88 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | ) 26 | 27 | func Example() { 28 | // You can print multiple times the same variable using argument indexes 29 | // The notation [n] before the verb, means use the nth argument after the format. 30 | // The above applies to Printf, Sprintf, and Fprintf 31 | fmt.Printf("%[1]d %[1]d\n", 5) 32 | fmt.Printf("%[2]d %[2]d %[1]d %[1]d\n", 5, 6) 33 | // Output: 34 | // 5 5 35 | // 6 6 5 5 36 | } 37 |38 | 39 |
40 | by psampaz - 41 | source code - comment below or here 43 |
44 | 51 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | "net/http" 26 | "net/http/httptest" 27 | ) 28 | 29 | func Example() { 30 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 31 | w.WriteHeader(http.StatusOK) 32 | w.Write([]byte("hello world")) 33 | })) 34 | defer ts.Close() 35 | 36 | resp, err := http.Get(ts.URL) 37 | if err != nil { 38 | fmt.Println(err) 39 | } 40 | defer resp.Body.Close() 41 | 42 | fmt.Printf("%s\n", resp.Status) 43 | fmt.Printf("%d\n", resp.StatusCode) 44 | // Output: 45 | // 200 OK 46 | // 200 47 | } 48 |49 | 50 |
51 | by psampaz - 52 | source code - comment below or here 54 |
55 | 62 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import "testing" 24 | 25 | func f(shouldPanic bool) string { 26 | if shouldPanic { 27 | panic("function panicked") 28 | } 29 | return "function didn't panic" 30 | } 31 | 32 | func Test_f(t *testing.T) { 33 | t.Run("panics", func(t *testing.T) { 34 | // If the function panics, recover() will 35 | // return a non nil value. 36 | defer func() { 37 | if r := recover(); r == nil { 38 | t.Errorf("function should panic") 39 | } 40 | }() 41 | 42 | f(true) 43 | }) 44 | 45 | t.Run("does not panic", func(t *testing.T) { 46 | shouldPanic := false 47 | want := "function didn't panic" 48 | if got := f(shouldPanic); got != want { 49 | t.Errorf("f(%v) = %v, want %v", shouldPanic, got, want) 50 | } 51 | }) 52 | 53 | } 54 |55 | 56 |
57 | by psampaz - 58 | source code - comment below or here 60 |
61 | 68 |Code snippets with tests and testable examples for the Go programming language
16 |21 |
package main 22 | 23 | import ( 24 | "fmt" 25 | "math" 26 | ) 27 | 28 | func Example() { 29 | fmt.Println("Max int8:", math.MaxInt8) 30 | fmt.Println("Max int16:", math.MaxInt16) 31 | fmt.Println("Max int32:", math.MaxInt32) 32 | fmt.Println("Max int64:", math.MaxInt64) 33 | fmt.Println("Max uint8:", math.MaxUint8) 34 | fmt.Println("Max uint16:", math.MaxUint16) 35 | fmt.Println("Max uint32:", math.MaxUint32) 36 | // See https://github.com/golang/go/issues/19621 37 | fmt.Println("Max uint64:", uint64(math.MaxUint64)) 38 | fmt.Println("Max float32:", math.MaxFloat32) 39 | fmt.Println("Max float64:", math.MaxFloat64) 40 | // Output: 41 | // Max int8: 127 42 | // Max int16: 32767 43 | // Max int32: 2147483647 44 | // Max int64: 9223372036854775807 45 | // Max uint8: 255 46 | // Max uint16: 65535 47 | // Max uint32: 4294967295 48 | // Max uint64: 18446744073709551615 49 | // Max float32: 3.4028234663852886e+38 50 | // Max float64: 1.7976931348623157e+308 51 | } 52 |53 | 54 |
55 | by psampaz - 56 | source code - comment below or here 58 |
59 | 66 |Code snippets with tests and testable examples for the Go programming language
15 | {{ $repo := .Repo}} 16 |25 | by psampaz - source code 26 |
27 |Code snippets with tests and testable examples for the Go programming language
16 |21 | {{.Snippet.GetHighlightedCode}} 22 |
23 |24 | by psampaz - 25 | source code - comment below or here 27 |
28 | 35 |