-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKitchenSink.go
More file actions
1510 lines (1245 loc) · 36 KB
/
KitchenSink.go
File metadata and controls
1510 lines (1245 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// KitchenSink.go - A comprehensive demonstration of Go language features
// This file showcases most Go language constructs with detailed explanations
package main
import (
"bufio"
"bytes"
"context"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math"
"math/big"
"net/http"
"os"
"reflect"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
)
// ============================================================================
// BASIC TYPES AND VARIABLES
// ============================================================================
// Constants - immutable values determined at compile time
const (
Pi = 3.14159265359 // Untyped constant
MaxInt int = 1<<31 - 1 // Typed constant
greeting = "Hello" // Private constant (lowercase)
PublicConst = "World" // Public constant (uppercase)
)
// Iota - Go's enum-like constant generator
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
Thursday // 4
Friday // 5
Saturday // 6
)
// Bit flags using iota
const (
ReadPermission = 1 << iota // 1 << 0 = 1
WritePermission // 1 << 1 = 2
ExecutePermission // 1 << 2 = 4
)
// Global variables (package-level)
var (
globalString string = "I'm a global variable"
globalInt int // Zero-valued to 0
globalBool bool // Zero-valued to false
globalFloat float64
globalComplex complex128 = 3 + 4i // Complex number
)
// ============================================================================
// CUSTOM TYPES AND STRUCTS
// ============================================================================
// Type alias - creates a new name for existing type
type MyInt int
type StringAlias = string // True alias (Go 1.9+)
// Struct - composite type grouping data
type Person struct {
Name string `json:"name" xml:"name"` // Struct tags for metadata
Age int `json:"age,omitempty"` // Omit if empty in JSON
Email string `json:"email" validate:"required"` // Custom validation tag
internal string // Unexported field (private)
Birthday time.Time `json:"-"` // Exclude from JSON
Nicknames []string `json:"nicknames,omitempty"` // Slice field
Attributes map[string]interface{} `json:"attrs"` // Map field
}
// Embedded struct (composition)
type Employee struct {
Person // Embedded/anonymous field - promotes Person's fields
EmployeeID string
Department string
Salary float64 `json:"-"` // Sensitive data, exclude from JSON
}
// Struct with anonymous fields
type Data struct {
int // Anonymous field
string // Anonymous field
*Person // Anonymous pointer field
}
// ============================================================================
// INTERFACES
// ============================================================================
// Interface - defines method signatures
type Speaker interface {
Speak() string
Listen(words string) error
}
// Empty interface - can hold any type
type Any interface{} // Same as interface{} or any (Go 1.18+)
// Interface embedding
type ReadWriter interface {
io.Reader // Embedded interface
io.Writer // Embedded interface
Close() error
}
// Type assertion interface
type Stringer interface {
String() string
}
// ============================================================================
// METHODS AND RECEIVERS
// ============================================================================
// Value receiver method - operates on copy
func (p Person) GetAge() int {
return p.Age
}
// Pointer receiver method - can modify the receiver
func (p *Person) SetAge(age int) {
p.Age = age
}
// Method with multiple return values
func (p Person) Validate() (bool, error) {
if p.Age < 0 {
return false, errors.New("age cannot be negative")
}
if p.Name == "" {
return false, errors.New("name is required")
}
return true, nil
}
// Implement Speaker interface for Person
func (p Person) Speak() string {
return fmt.Sprintf("Hi, I'm %s and I'm %d years old", p.Name, p.Age)
}
func (p Person) Listen(words string) error {
if words == "" {
return errors.New("no words to listen to")
}
fmt.Printf("%s heard: %s\n", p.Name, words)
return nil
}
// Implement Stringer interface (like ToString in other languages)
func (p Person) String() string {
return fmt.Sprintf("Person{Name: %s, Age: %d}", p.Name, p.Age)
}
// Method on custom type
func (m MyInt) Double() MyInt {
return m * 2
}
// ============================================================================
// FUNCTIONS
// ============================================================================
// Basic function with parameters and return value
func add(a, b int) int {
return a + b
}
// Multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Named return values
func rectangleArea(length, width float64) (area float64, perimeter float64) {
area = length * width
perimeter = 2 * (length + width)
return // Naked return - returns named values
}
// Variadic function - accepts variable number of arguments
func sum(numbers ...int) int {
total := 0
for _, n := range numbers {
total += n
}
return total
}
// Function as parameter (higher-order function)
func apply(fn func(int) int, value int) int {
return fn(value)
}
// Function returning function (closure)
func multiplier(factor int) func(int) int {
// Closure captures 'factor' from outer scope
return func(x int) int {
return x * factor
}
}
// Recursive function
func factorial(n int) int {
if n <= 1 {
return 1
}
return n * factorial(n-1)
}
// Defer - delays execution until surrounding function returns
func deferExample() {
defer fmt.Println("This prints last")
defer fmt.Println("This prints second to last") // LIFO order
fmt.Println("This prints first")
}
// Panic and recover - error handling mechanism
func panicRecoverExample() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Recovered from panic: %v\n", r)
}
}()
panic("Something went wrong!")
fmt.Println("This won't execute")
}
// ============================================================================
// POINTERS
// ============================================================================
func pointerDemo() {
var x int = 42
var ptr *int = &x // ptr holds address of x
fmt.Printf("Value of x: %d\n", x)
fmt.Printf("Address of x: %p\n", &x)
fmt.Printf("Value of ptr: %p\n", ptr)
fmt.Printf("Value ptr points to: %d\n", *ptr) // Dereferencing
*ptr = 100 // Modify value through pointer
fmt.Printf("New value of x: %d\n", x)
// Pointer to pointer
var ptrToPtr **int = &ptr
fmt.Printf("Pointer to pointer: %p\n", ptrToPtr)
// nil pointer
var nilPtr *string
if nilPtr == nil {
fmt.Println("Pointer is nil")
}
}
// ============================================================================
// ARRAYS AND SLICES
// ============================================================================
func arraySliceDemo() {
// Arrays - fixed size
var arr1 [5]int // Zero-valued array
arr2 := [5]int{1, 2, 3, 4, 5} // Array literal
arr3 := [...]int{1, 2, 3} // Compiler counts elements
arr4 := [5]int{1: 10, 3: 30} // Sparse initialization
fmt.Printf("Arrays: %v, %v, %v, %v\n", arr1, arr2, arr3, arr4)
// Slices - dynamic arrays
var slice1 []int // nil slice
slice2 := []int{1, 2, 3} // Slice literal
slice3 := make([]int, 5) // Length 5, capacity 5
slice4 := make([]int, 5, 10) // Length 5, capacity 10
slice5 := arr2[1:4] // Slice from array
// Slice operations
slice2 = append(slice2, 4, 5, 6) // Append elements
slice6 := append(slice2, slice3...) // Append slice to slice
// Slice slicing
subSlice := slice2[1:3] // Elements at index 1 and 2
fullSlice := slice2[:] // All elements
fromStart := slice2[:3] // First 3 elements
toEnd := slice2[2:] // From index 2 to end
// Capacity and length
fmt.Printf("Length: %d, Capacity: %d\n", len(slice4), cap(slice4))
// Copy slices
dest := make([]int, len(slice2))
copied := copy(dest, slice2)
fmt.Printf("Copied %d elements\n", copied)
// 2D slice
matrix := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
fmt.Printf("2D slice: %v\n", matrix)
_ = slice1
_ = slice5
_ = slice6
_ = subSlice
_ = fullSlice
_ = fromStart
_ = toEnd
}
// ============================================================================
// MAPS
// ============================================================================
func mapDemo() {
// Map creation
var map1 map[string]int // nil map
map2 := make(map[string]int) // Empty map
map3 := map[string]int{ // Map literal
"one": 1,
"two": 2,
"three": 3,
}
// Map operations
map2["key"] = 42 // Insert/update
value := map3["two"] // Get value
value, exists := map3["four"] // Check existence
delete(map3, "one") // Delete key
fmt.Printf("Value: %d, Exists: %v\n", value, exists)
// Iterate over map
for key, val := range map3 {
fmt.Printf("%s: %d\n", key, val)
}
// Map of structs
people := map[string]Person{
"p1": {Name: "Alice", Age: 30},
"p2": {Name: "Bob", Age: 25},
}
// Nested maps
nested := map[string]map[string]int{
"group1": {"a": 1, "b": 2},
"group2": {"c": 3, "d": 4},
}
_ = map1
_ = people
_ = nested
}
// ============================================================================
// CHANNELS AND GOROUTINES
// ============================================================================
func concurrencyDemo() {
// Goroutines - lightweight threads
go func() {
fmt.Println("Running in goroutine")
}()
// Channels - communication between goroutines
ch1 := make(chan int) // Unbuffered channel
ch2 := make(chan string, 10) // Buffered channel
// Send and receive
go func() {
ch1 <- 42 // Send
}()
value := <-ch1 // Receive
// Channel directions
sendOnly := make(chan<- int) // Send-only channel
receiveOnly := make(<-chan int) // Receive-only channel
// Select statement - multiplex channels
ch3 := make(chan int)
ch4 := make(chan string)
go func() {
ch3 <- 1
}()
go func() {
ch4 <- "hello"
}()
select {
case v1 := <-ch3:
fmt.Printf("Received from ch3: %d\n", v1)
case v2 := <-ch4:
fmt.Printf("Received from ch4: %s\n", v2)
case <-time.After(1 * time.Second):
fmt.Println("Timeout")
default:
fmt.Println("No channel ready")
}
// Close channel
ch5 := make(chan int, 3)
ch5 <- 1
ch5 <- 2
ch5 <- 3
close(ch5)
// Range over channel
for val := range ch5 {
fmt.Printf("Received: %d\n", val)
}
// Worker pool pattern
jobs := make(chan int, 100)
results := make(chan int, 100)
// Start workers
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
// Send jobs
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
// Collect results
for a := 1; a <= 5; a++ {
<-results
}
_ = value
_ = ch2
_ = sendOnly
_ = receiveOnly
}
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Printf("Worker %d processing job %d\n", id, j)
time.Sleep(100 * time.Millisecond)
results <- j * 2
}
}
// ============================================================================
// SYNCHRONIZATION PRIMITIVES
// ============================================================================
func syncDemo() {
// Mutex - mutual exclusion
var mu sync.Mutex
var counter int
for i := 0; i < 1000; i++ {
go func() {
mu.Lock()
counter++
mu.Unlock()
}()
}
// RWMutex - readers-writers lock
var rwMu sync.RWMutex
var data map[string]string = make(map[string]string)
// Multiple readers
go func() {
rwMu.RLock()
_ = data["key"]
rwMu.RUnlock()
}()
// Single writer
go func() {
rwMu.Lock()
data["key"] = "value"
rwMu.Unlock()
}()
// WaitGroup - wait for goroutines to finish
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Printf("Goroutine %d working\n", id)
}(i)
}
wg.Wait()
// Once - run function only once
var once sync.Once
initialize := func() {
fmt.Println("Initialized only once")
}
for i := 0; i < 3; i++ {
once.Do(initialize)
}
// Atomic operations
var atomicCounter int64
atomic.AddInt64(&atomicCounter, 1)
atomic.LoadInt64(&atomicCounter)
atomic.StoreInt64(&atomicCounter, 100)
atomic.CompareAndSwapInt64(&atomicCounter, 100, 200)
// Condition variable
cond := sync.NewCond(&mu)
ready := false
go func() {
mu.Lock()
for !ready {
cond.Wait()
}
mu.Unlock()
fmt.Println("Condition met!")
}()
mu.Lock()
ready = true
cond.Signal()
mu.Unlock()
// Pool - reusable object pool
pool := &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
buf := pool.Get().(*bytes.Buffer)
buf.WriteString("Hello")
pool.Put(buf)
}
// ============================================================================
// ERROR HANDLING
// ============================================================================
// Custom error type
type CustomError struct {
Code int
Message string
}
func (e CustomError) Error() string {
return fmt.Sprintf("Error %d: %s", e.Code, e.Message)
}
// Wrapping errors (Go 1.13+)
func errorHandlingDemo() error {
// Creating errors
err1 := errors.New("simple error")
err2 := fmt.Errorf("formatted error: %d", 42)
// Custom error
err3 := CustomError{Code: 404, Message: "Not Found"}
// Error wrapping
originalErr := errors.New("original error")
wrappedErr := fmt.Errorf("wrapped: %w", originalErr)
// Check wrapped errors
if errors.Is(wrappedErr, originalErr) {
fmt.Println("Error matches original")
}
// Type assertion for errors
var customErr CustomError
if errors.As(err3, &customErr) {
fmt.Printf("Custom error code: %d\n", customErr.Code)
}
// Multiple error handling
errs := []error{err1, err2, err3}
for _, err := range errs {
if err != nil {
log.Printf("Error occurred: %v", err)
}
}
return nil
}
// ============================================================================
// GENERICS (Go 1.18+)
// ============================================================================
// Generic function
func Min[T comparable](a, b T) T {
if a < b {
return a
}
return b
}
// Generic type constraint
type Number interface {
int | int32 | int64 | float32 | float64
}
func Sum[T Number](values []T) T {
var sum T
for _, v := range values {
sum += v
}
return sum
}
// Generic struct
type Stack[T any] struct {
items []T
}
func (s *Stack[T]) Push(item T) {
s.items = append(s.items, item)
}
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
item := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return item, true
}
// ============================================================================
// REFLECTION
// ============================================================================
func reflectionDemo() {
p := Person{Name: "Alice", Age: 30}
// Get type information
t := reflect.TypeOf(p)
v := reflect.ValueOf(p)
fmt.Printf("Type: %v, Kind: %v\n", t, t.Kind())
// Iterate struct fields
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
value := v.Field(i)
fmt.Printf("Field: %s, Type: %s, Value: %v, Tag: %s\n",
field.Name, field.Type, value, field.Tag)
}
// Modify value through reflection (requires pointer)
ptrValue := reflect.ValueOf(&p).Elem()
ageField := ptrValue.FieldByName("Age")
if ageField.CanSet() {
ageField.SetInt(31)
}
// Call method through reflection
method := v.MethodByName("Speak")
if method.IsValid() {
results := method.Call(nil)
fmt.Printf("Method result: %v\n", results[0])
}
// Check if implements interface
speakerType := reflect.TypeOf((*Speaker)(nil)).Elem()
implements := t.Implements(speakerType)
fmt.Printf("Implements Speaker: %v\n", implements)
}
// ============================================================================
// CONTEXT
// ============================================================================
func contextDemo() {
// Create contexts
ctx := context.Background() // Root context
ctxWithValue := context.WithValue(ctx, "key", "value") // With value
// With cancellation
ctxWithCancel, cancel := context.WithCancel(ctx)
defer cancel() // Ensure cleanup
// With deadline
deadline := time.Now().Add(5 * time.Second)
ctxWithDeadline, cancel2 := context.WithDeadline(ctx, deadline)
defer cancel2()
// With timeout
ctxWithTimeout, cancel3 := context.WithTimeout(ctx, 2*time.Second)
defer cancel3()
// Use context in goroutine
go func(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Printf("Context cancelled: %v\n", ctx.Err())
case <-time.After(1 * time.Second):
fmt.Println("Operation completed")
}
}(ctxWithTimeout)
// Get value from context
if value := ctxWithValue.Value("key"); value != nil {
fmt.Printf("Context value: %v\n", value)
}
_ = ctxWithCancel
_ = ctxWithDeadline
}
// ============================================================================
// FILE I/O
// ============================================================================
func fileIODemo() error {
// Write to file
data := []byte("Hello, Go!\n")
err := os.WriteFile("test.txt", data, 0644)
if err != nil {
return err
}
// Read entire file
content, err := os.ReadFile("test.txt")
if err != nil {
return err
}
fmt.Printf("File content: %s", content)
// Open file for reading
file, err := os.Open("test.txt")
if err != nil {
return err
}
defer file.Close()
// Read with buffer
reader := bufio.NewReader(file)
line, err := reader.ReadString('\n')
if err != nil && err != io.EOF {
return err
}
fmt.Printf("First line: %s", line)
// Create/open file for writing
writeFile, err := os.Create("output.txt")
if err != nil {
return err
}
defer writeFile.Close()
// Write with buffer
writer := bufio.NewWriter(writeFile)
writer.WriteString("Buffered write\n")
writer.Flush()
// File info
info, err := os.Stat("test.txt")
if err != nil {
return err
}
fmt.Printf("File: %s, Size: %d, Modified: %v\n",
info.Name(), info.Size(), info.ModTime())
// Directory operations
err = os.Mkdir("testdir", 0755)
if err != nil && !os.IsExist(err) {
return err
}
// List directory
entries, err := os.ReadDir(".")
if err != nil {
return err
}
for _, entry := range entries {
fmt.Printf("Entry: %s, IsDir: %v\n", entry.Name(), entry.IsDir())
}
// Clean up
os.Remove("test.txt")
os.Remove("output.txt")
os.RemoveAll("testdir")
return nil
}
// ============================================================================
// JSON HANDLING
// ============================================================================
func jsonDemo() error {
// Struct to JSON
p := Person{
Name: "Alice",
Age: 30,
Email: "alice@example.com",
Nicknames: []string{"Ally", "Al"},
Attributes: map[string]interface{}{
"height": 170,
"city": "New York",
},
}
// Marshal to JSON
jsonData, err := json.Marshal(p)
if err != nil {
return err
}
fmt.Printf("JSON: %s\n", jsonData)
// Pretty print JSON
prettyJSON, err := json.MarshalIndent(p, "", " ")
if err != nil {
return err
}
fmt.Printf("Pretty JSON:\n%s\n", prettyJSON)
// Unmarshal from JSON
var p2 Person
err = json.Unmarshal(jsonData, &p2)
if err != nil {
return err
}
fmt.Printf("Unmarshaled: %+v\n", p2)
// JSON with interface{}
var data interface{}
jsonStr := `{"name":"Bob","age":25,"hobbies":["reading","gaming"]}`
err = json.Unmarshal([]byte(jsonStr), &data)
if err != nil {
return err
}
// Type assertion for dynamic JSON
if m, ok := data.(map[string]interface{}); ok {
fmt.Printf("Name: %v\n", m["name"])
if hobbies, ok := m["hobbies"].([]interface{}); ok {
for _, hobby := range hobbies {
fmt.Printf("Hobby: %v\n", hobby)
}
}
}
// JSON encoder/decoder for streams
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.Encode(p)
decoder := json.NewDecoder(&buf)
var p3 Person
decoder.Decode(&p3)
return nil
}
// ============================================================================
// HTTP CLIENT/SERVER
// ============================================================================
func httpDemo() {
// HTTP Server
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
})
http.HandleFunc("/json", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Hello, JSON!",
})
})
// Start server in goroutine
go func() {
log.Println("Server starting on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}()
// Give server time to start
time.Sleep(100 * time.Millisecond)
// HTTP Client
client := &http.Client{
Timeout: 10 * time.Second,
}
// GET request
resp, err := client.Get("http://localhost:8080/World")
if err != nil {
log.Printf("GET error: %v", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Response: %s\n", body)
// POST request with JSON
jsonData := bytes.NewBuffer([]byte(`{"name":"test"}`))
resp2, err := client.Post("http://localhost:8080/json",
"application/json", jsonData)
if err != nil {
log.Printf("POST error: %v", err)
return
}
defer resp2.Body.Close()
}
// ============================================================================
// REGULAR EXPRESSIONS
// ============================================================================
func regexDemo() {
// Compile regex
re, err := regexp.Compile(`\d+`)
if err != nil {
log.Fatal(err)
}
text := "The year 2024 has 365 days"
// Find matches
match := re.FindString(text)
fmt.Printf("First match: %s\n", match)
allMatches := re.FindAllString(text, -1)
fmt.Printf("All matches: %v\n", allMatches)
// Replace
replaced := re.ReplaceAllString(text, "XXX")
fmt.Printf("Replaced: %s\n", replaced)
// Named groups
re2 := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})`)
match2 := re2.FindStringSubmatch("2024-03-15")
fmt.Printf("Date parts: %v\n", match2)
// Check if matches
matched := re.MatchString("123")
fmt.Printf("Matches: %v\n", matched)
}
// ============================================================================
// STRING MANIPULATION
// ============================================================================
func stringDemo() {
s := "Hello, Go World!"
// String operations
fmt.Printf("Length: %d\n", len(s))
fmt.Printf("Uppercase: %s\n", strings.ToUpper(s))
fmt.Printf("Lowercase: %s\n", strings.ToLower(s))
fmt.Printf("Title: %s\n", strings.Title(s))
// Substring operations
fmt.Printf("Contains 'Go': %v\n", strings.Contains(s, "Go"))
fmt.Printf("Starts with 'Hello': %v\n", strings.HasPrefix(s, "Hello"))
fmt.Printf("Ends with '!': %v\n", strings.HasSuffix(s, "!"))
fmt.Printf("Index of 'Go': %d\n", strings.Index(s, "Go"))
// Split and join
parts := strings.Split(s, " ")
fmt.Printf("Split: %v\n", parts)
joined := strings.Join(parts, "-")
fmt.Printf("Joined: %s\n", joined)