├── .vscode ├── settings.json ├── vscode-kanban.json ├── tasks.json └── launch.json ├── gowiki ├── test.txt~ ├── data.txt ├── TestPage.txt ├── test.txt ├── wiki ├── view.html ├── edit.html ├── newwiki.go ├── json.go └── wiki.go ├── GopherJS └── First step.go ├── Template ├── design.css └── csstemplate.go ├── Command ├── run.sh ├── main.go ├── cobra-readme.md ├── cmd │ ├── bye.go │ ├── hello.go │ └── root.go └── LICENSE ├── Server ├── simpleGoServer │ ├── public │ │ ├── css │ │ │ └── custom.css │ │ └── index.html │ ├── server │ │ ├── con │ │ │ └── Database.go │ │ ├── models │ │ │ └── User.go │ │ └── controllers │ │ │ └── UserController.go │ ├── simpleGoServer.iml │ └── main.go └── gzip header.go ├── .DS_Store ├── ImageGrayScale ├── fiveyears.jpg ├── fiveyears_gray.png └── grayscale.go ├── Protobuf ├── GoProtoClient │ ├── csv.csv │ └── protoClient.go ├── GoProtoServer │ ├── CSVValues.csv │ └── protoServer.go ├── ProtoTest.proto ├── Addressbook │ ├── addressbook.proto │ └── addressbook.pb.go └── ProtobufTest │ └── ProtoTest.pb.go ├── Zap Logging ├── env.sh ├── .gitignore ├── README.md ├── src │ ├── globallogger │ │ ├── main.go │ │ └── README.md │ ├── customencoder │ │ ├── main.go │ │ └── README.md │ ├── customlogger │ │ ├── main.go │ │ └── README.md │ └── simple1 │ │ ├── main.go │ │ └── README.md └── LICENSE ├── Email ├── template.html └── first.go ├── NSQLearning ├── producer.go ├── consumer.go └── README.md ├── Redis ├── Reflect │ └── printStruct.go └── redisgo.go ├── Job scheduler └── scheduler.go ├── .gitignore ├── Cryptography ├── sha256.go ├── sha1.go └── AES.go ├── OpenAPI&Swagger ├── swagger.json └── main.go ├── Hariprasad.iml ├── DesignPatterns ├── Creational │ ├── Prototype │ │ └── prototype.go │ └── Builder │ │ └── builder.go ├── Functional │ ├── Generator │ │ └── main.go │ └── Observer │ │ └── main.go ├── CloudDistributed │ └── CircuitBreaker │ │ └── CircuitBreaker.go └── Structural │ └── Decorator │ ├── dynamic-function.go │ ├── static-window.go │ └── dynamic-window.go ├── CSV └── sample.go ├── AST └── ZupZup │ ├── sample.go │ └── parser.go ├── PDF ├── havaltica.go ├── Unicodepdf.go ├── goFpdf.go └── Image.go ├── Yaag └── Yaag.go ├── Http ├── httptest.go ├── cookies.go ├── websocket │ ├── Server.go │ └── index.html ├── uploadAnddonwload.go └── middleware.go ├── Errors └── stacktrace.go ├── README.md ├── Time ├── timepackage.go └── 24TO12.go ├── File ├── getFileName.go └── fileCache.go ├── SQL └── connect.go ├── Profiling └── new.go ├── GTK └── main.go ├── Benchmark └── fibonacci_test.go ├── GoRoutines ├── race │ └── main.go ├── runner │ ├── main │ │ └── runner_example.go │ └── runner.go ├── atomic │ └── main.go ├── buffered │ └── main.go └── unbuffered │ └── main.go ├── DOSSimple └── main.go ├── MongoDB ├── Functions.go ├── student-collection.go ├── person-collection.go ├── javascript.js └── crud.go ├── Gorilla ├── session.go └── context.go ├── Proxy └── reverseProxy.go ├── Pool ├── main │ └── pool_example.go └── Pool.go ├── Regex └── gobrace.go ├── JWT └── jwtSHA512.go ├── Money └── money.go └── Interpreter └── interpreter.go /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | } -------------------------------------------------------------------------------- /gowiki/test.txt~: -------------------------------------------------------------------------------- 1 | Hello World 2 | -------------------------------------------------------------------------------- /gowiki/data.txt: -------------------------------------------------------------------------------- 1 | this is new data -------------------------------------------------------------------------------- /GopherJS/First step.go: -------------------------------------------------------------------------------- 1 | package main 2 | -------------------------------------------------------------------------------- /gowiki/TestPage.txt: -------------------------------------------------------------------------------- 1 | This is the sample page -------------------------------------------------------------------------------- /gowiki/test.txt: -------------------------------------------------------------------------------- 1 | Hello World sdf 2 | -------------------------------------------------------------------------------- /Template/design.css: -------------------------------------------------------------------------------- 1 | halo 2 | mari belajar golang 3 | -------------------------------------------------------------------------------- /Command/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | echo "Hello World" 3 | 4 | -------------------------------------------------------------------------------- /Server/simpleGoServer/public/css/custom.css: -------------------------------------------------------------------------------- 1 | h1{ 2 | color: red; 3 | } -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hariprasadraja/golang-workspace/HEAD/.DS_Store -------------------------------------------------------------------------------- /gowiki/wiki: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hariprasadraja/golang-workspace/HEAD/gowiki/wiki -------------------------------------------------------------------------------- /.vscode/vscode-kanban.json: -------------------------------------------------------------------------------- 1 | { 2 | "todo": [], 3 | "in-progress": [], 4 | "testing": [], 5 | "done1": [] 6 | } -------------------------------------------------------------------------------- /ImageGrayScale/fiveyears.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hariprasadraja/golang-workspace/HEAD/ImageGrayScale/fiveyears.jpg -------------------------------------------------------------------------------- /gowiki/view.html: -------------------------------------------------------------------------------- 1 |

{{.Title}}

2 |

[edit]

3 |
{{printf "%s" .Body}}
4 | -------------------------------------------------------------------------------- /ImageGrayScale/fiveyears_gray.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hariprasadraja/golang-workspace/HEAD/ImageGrayScale/fiveyears_gray.png -------------------------------------------------------------------------------- /Protobuf/GoProtoClient/csv.csv: -------------------------------------------------------------------------------- 1 | itemid,itemname,itemvalue,itemType 2 | 1,FirstItemName,222,0 3 | 2,SecondItemName,333,1 4 | 3,ThirdItemName,444,2 5 | 4,FourthItemName,555,0 6 | 5,FifthItemName,666,3 7 | -------------------------------------------------------------------------------- /Zap Logging/env.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | THIS_DIR=$(cd $(dirname $BASH_SOURCE) && pwd) 4 | export GOPATH=$THIS_DIR GOBIN=$THIS_DIR/bin 5 | 6 | if [[ ! $PATH == *$THIS_DIR* ]]; then 7 | export PATH=$PATH:$GOBIN 8 | fi 9 | -------------------------------------------------------------------------------- /Email/template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Template 6 | 7 | 8 | 9 |

This is the trail mail for learning

10 |
Thank you
11 | 12 | -------------------------------------------------------------------------------- /gowiki/edit.html: -------------------------------------------------------------------------------- 1 |

Editing {{.Title}}

2 | 3 |
4 |
6 |
7 |
8 | 9 | 10 | -------------------------------------------------------------------------------- /Server/simpleGoServer/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Simple Go server 6 | 7 | 8 | 9 | 10 |

{{.greetings}}

11 | 12 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "label": "echo", 8 | "type": "shell", 9 | "command": "echo Hello" 10 | } 11 | ] 12 | } -------------------------------------------------------------------------------- /Protobuf/GoProtoServer/CSVValues.csv: -------------------------------------------------------------------------------- 1 | 2,GoClient,This is a Go Protobuf client!!,1,FirstItemName,222,0 2 | 2,GoClient,This is a Go Protobuf client!!,2,SecondItemName,333,1 3 | 2,GoClient,This is a Go Protobuf client!!,3,ThirdItemName,444,2 4 | 2,GoClient,This is a Go Protobuf client!!,4,FourthItemName,555,0 5 | 2,GoClient,This is a Go Protobuf client!!,5,FifthItemName,666,3 6 | -------------------------------------------------------------------------------- /NSQLearning/producer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/bitly/go-nsq" 5 | "log" 6 | ) 7 | 8 | func main() { 9 | config := nsq.NewConfig() 10 | w, _ := nsq.NewProducer("127.0.0.1:4160", config) 11 | 12 | err := w.Publish("write_test", []byte("test")) 13 | if err != nil { 14 | log.Panic("Could not connect", err.Error()) 15 | } 16 | 17 | w.Stop() 18 | } 19 | -------------------------------------------------------------------------------- /Redis/Reflect/printStruct.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | ) 7 | 8 | func main() { 9 | x := struct { 10 | Foo string 11 | Bar int 12 | }{"foo", 2} 13 | 14 | v := reflect.ValueOf(x) 15 | values := make([]interface{}, v.NumField()) 16 | for i := 0; i < v.NumField(); i++ { 17 | values[i] = v.Field(i).Interface() 18 | } 19 | 20 | fmt.Println(values) 21 | } 22 | -------------------------------------------------------------------------------- /Job scheduler/scheduler.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/onatm/clockwerk" 6 | "time" 7 | ) 8 | 9 | type DummyJob struct{} 10 | 11 | func (d DummyJob) Run() { 12 | fmt.Println("Every 2 seconds") 13 | } 14 | 15 | func main() { 16 | var job DummyJob 17 | c := clockwerk.New() 18 | c.Every(2 * time.Second).Do(job) 19 | c.Start() 20 | time.Sleep(10 * time.Minute) 21 | } 22 | -------------------------------------------------------------------------------- /Zap Logging/.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | 16 | /pkg 17 | /bin 18 | debug 19 | /.vscode 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | *.idea/ 26 | 27 | Learning/ -------------------------------------------------------------------------------- /Cryptography/sha256.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/sha256" 5 | "encoding/base64" 6 | ) 7 | 8 | func main() { 9 | SHAEncode("123456789") 10 | } 11 | 12 | func SHAEncode(target string) (output string) { 13 | targetBytes := []byte(target) 14 | 15 | enc := sha256.New() 16 | enc.Write(targetBytes) 17 | 18 | output = base64.StdEncoding.EncodeToString(enc.Sum(nil)) 19 | println(output) 20 | return 21 | } 22 | -------------------------------------------------------------------------------- /Server/simpleGoServer/server/con/Database.go: -------------------------------------------------------------------------------- 1 | package con 2 | 3 | import ( 4 | "gopkg.in/mgo.v2" 5 | "log" 6 | "os" 7 | ) 8 | 9 | var Db *mgo.Database 10 | 11 | func DbConnection() { 12 | session, err := mgo.Dial("localhost:27017") 13 | if err != nil { 14 | log.Println("Error in dial mongo db") 15 | os.Exit(1) 16 | } 17 | 18 | session.SetMode(mgo.Monotonic, true) 19 | Db = session.DB("simpleGoServer") 20 | } 21 | -------------------------------------------------------------------------------- /OpenAPI&Swagger/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "components": {}, 3 | "info": {}, 4 | "openapi": "3.0.0", 5 | "servers": [{ 6 | "url": "http://localhost:8080", 7 | "description": "This is my test server", 8 | "variables": { 9 | "Variable": { 10 | "default": "anything", 11 | "description": "this is server variable" 12 | } 13 | } 14 | }] 15 | } -------------------------------------------------------------------------------- /Hariprasad.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /Redis/redisgo.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "gopkg.in/redis.v3" 5 | "log" 6 | ) 7 | 8 | func main() { 9 | client := redis.NewClient(&redis.Options{ 10 | Addr: "localhost:6379", 11 | Password: "", // no password set 12 | DB: 0, // use default DB 13 | }) 14 | 15 | _, err := client.Ping().Result() 16 | if err != nil { 17 | log.Println("Redis connection err:", err) 18 | } 19 | 20 | client.Set("name", "Hariprasad", 0) 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Server/simpleGoServer/server/models/User.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "gopkg.in/mgo.v2/bson" 5 | "time" 6 | ) 7 | 8 | type User struct { 9 | ID bson.ObjectId `json:"id" bson:"_id,omitempty"` 10 | Name string `json:"name" bson:"name"` 11 | EmailID string `json:"emailID" bson:"emailID"` 12 | DateCreated time.Time `json:"dateCreated" bson:"dateCreated"` 13 | LastUpdated time.Time `json:"lastUpdated" bson:"lastUpdated"` 14 | } 15 | -------------------------------------------------------------------------------- /Server/simpleGoServer/simpleGoServer.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /DesignPatterns/Creational/Prototype/prototype.go: -------------------------------------------------------------------------------- 1 | package Design_Pattern 2 | 3 | import ( 4 | "log" 5 | "runtime" 6 | ) 7 | 8 | type Struct1 struct { 9 | Name string 10 | } 11 | 12 | func main() { 13 | 14 | // In golang struct are immutable, if we 15 | 16 | a := Struct1{"Old things"} 17 | b := a 18 | b.Name = "New Value" 19 | runtime.GC() 20 | log.Println("A:", a.Name, "B:", b.Name) 21 | 22 | c := &Struct1{"Old things"} 23 | d := a 24 | d.Name = "New Value" 25 | 26 | log.Println("C:", c.Name, "D:", d.Name) 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Protobuf/ProtoTest.proto: -------------------------------------------------------------------------------- 1 | package ProtobufTest; 2 | 3 | message TestMessage { 4 | required string clientName = 1; 5 | required int32 clientId = 2; 6 | optional string description = 3 [default = "NONE"]; 7 | repeated MsgItem messageitems = 4; 8 | 9 | enum ItemType { 10 | TypeX = 0; 11 | TypeY = 1; 12 | TypeZ = 2; 13 | } 14 | 15 | message MsgItem { 16 | required int32 id = 1; 17 | optional string itemName = 2; 18 | optional int32 itemValue = 3; 19 | optional ItemType itemType = 4; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /CSV/sample.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/csv" 5 | "log" 6 | "os" 7 | ) 8 | 9 | var data = []string{"Reason", "Request", "Error"} 10 | 11 | func main() { 12 | file, err := os.Create("result.csv") 13 | defer file.Close() 14 | if err != nil { 15 | log.Fatal("Failed to create csv file, Error: ", err.Error()) 16 | } 17 | 18 | writer := csv.NewWriter(file) 19 | defer writer.Flush() 20 | 21 | err = writer.Write(data) 22 | if err != nil { 23 | log.Fatal("Failed to write into the file, Error: ", err.Error()) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /AST/ZupZup/sample.go: -------------------------------------------------------------------------------- 1 | // Sample program for golang ast parsing. 2 | // Source: https://zupzup.org/go-ast-traversal/ 3 | 4 | package main 5 | 6 | import "fmt" 7 | import "strings" 8 | 9 | func main() { 10 | hello := "Hello" 11 | world := "World" 12 | words := []string{hello, world} 13 | SayHello(words) 14 | } 15 | 16 | // SayHello says Hello 17 | func SayHello(words []string) { 18 | fmt.Println(joinStrings(words)) 19 | } 20 | 21 | // joinStrings joins strings 22 | func joinStrings(words []string) string { 23 | return strings.Join(words, ", ") 24 | } 25 | -------------------------------------------------------------------------------- /PDF/havaltica.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/jung-kurt/gofpdf" 7 | ) 8 | 9 | func main() { 10 | pdf := gofpdf.New("P", "mm", "A4", "/home/parvathavarthinik/kpm/goworkspace/src/github.com/jung-kurt/gofpdf/font/") 11 | pdf.AddFont("Helvetica", "", "helvetica_1251.json") 12 | pdf.AddPage() 13 | pdf.SetFont("Helvetica", "", 16) 14 | tr := pdf.UnicodeTranslatorFromDescriptor("cp1251") 15 | pdf.Cell(15, 50, tr("русский текст")) 16 | err := pdf.OutputFileAndClose("test.pdf") 17 | if err != nil { 18 | log.Println(err) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /DesignPatterns/Functional/Generator/main.go: -------------------------------------------------------------------------------- 1 | // This file explains Generator Pattern in golang. 2 | // source: https://github.com/tensor-programming/pattern-tutorial/blob/master/generator/main.go 3 | 4 | package main 5 | 6 | import "fmt" 7 | 8 | func fibGenerator(n int) chan int { 9 | out := make(chan int) 10 | 11 | go func() { 12 | defer close(out) 13 | for i, j := 0, 1; i < n; i, j = i+j, i { 14 | out <- i 15 | } 16 | 17 | }() 18 | 19 | return out 20 | } 21 | 22 | func main() { 23 | for x := range fibGenerator(10000000) { 24 | fmt.Println(x) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Cryptography/sha1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/sha1" 5 | "encoding/json" 6 | "fmt" 7 | ) 8 | 9 | func main() { 10 | 11 | s := make(map[string]string) 12 | 13 | s["name"] = "hari" 14 | s["roll"] = "dev" 15 | 16 | h := sha2.New() 17 | data1, _ := json.Marshal(s) 18 | h.Write(data1) 19 | bs := h.Sum(nil) 20 | fmt.Printf("%x\n", bs) 21 | 22 | d := make(map[string]string) 23 | d["roll"] = "dev" 24 | d["name"] = "hari" 25 | data2, _ := json.Marshal(d) 26 | h = sha1.New() 27 | h.Write(data2) 28 | ss := h.Sum(nil) 29 | fmt.Printf("%x\n", ss) 30 | 31 | } 32 | -------------------------------------------------------------------------------- /NSQLearning/consumer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "sync" 6 | 7 | "github.com/bitly/go-nsq" 8 | ) 9 | 10 | func main() { 11 | 12 | wg := &sync.WaitGroup{} 13 | wg.Add(1) 14 | 15 | config := nsq.NewConfig() 16 | q, _ := nsq.NewConsumer("write_test", "ch", config) 17 | q.AddHandler(nsq.HandlerFunc(func(message *nsq.Message) error { 18 | log.Printf("Got a message: %v", message) 19 | wg.Done() 20 | return nil 21 | })) 22 | 23 | err := q.ConnectToNSQD("127.0.0.1:4160") 24 | if err != nil { 25 | log.Panic("Could not connect") 26 | } 27 | wg.Wait() 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Zap Logging/README.md: -------------------------------------------------------------------------------- 1 | # Using the zap logging library 2 | 3 | This repository provides some examples of using [Uber's zap](https://github.com/uber-go/zap) Go logging library 4 | 5 | Install the zap library before trying out the examples: 6 | 7 | ```console 8 | $ source env.sh 9 | 10 | $ go get -u go.uber.org/zap 11 | 12 | $ go run src/simple1/main.go 13 | ``` 14 | 15 | ## Examples 16 | 17 | * [Simplest usage using presets](./src/simple1) 18 | * [Creating a custom logger](./src/customlogger) 19 | * [Using the global logger](./src/globallogger) 20 | * [Creating custom encoders for metadata fields](./src/customencoder) -------------------------------------------------------------------------------- /Yaag/Yaag.go: -------------------------------------------------------------------------------- 1 | //Yaag is the one of the simple api document generator. 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "github.com/hariprasadraja/yaag/middleware" 7 | "github.com/hariprasadraja/yaag/yaag" 8 | "net/http" 9 | ) 10 | 11 | func handler(w http.ResponseWriter, r *http.Request) { 12 | fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) 13 | } 14 | 15 | func main() { 16 | yaag.Init(&yaag.Config{On: true, DocTitle: "Core", DocPath: "apidoc.html", BaseUrls: map[string]string{"Production": "", "Staging": ""}}) 17 | http.HandleFunc("/", middleware.HandleFunc(handler)) 18 | http.ListenAndServe(":8080", nil) 19 | } 20 | -------------------------------------------------------------------------------- /Http/httptest.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "net/http/httptest" 7 | //"log" 8 | ) 9 | 10 | func main() { 11 | //handler := func(w http.ResponseWriter, r *http.Request) { 12 | // io.WriteString(w, "Hello World!") 13 | //} 14 | 15 | req := httptest.NewRequest("GET", "http://localhost:8085/accounts", nil) 16 | 17 | w := httptest.NewRecorder() 18 | //handler(w, req) 19 | 20 | resp := w.Result() 21 | body, _ := ioutil.ReadAll(resp.Body) 22 | 23 | fmt.Println(resp.StatusCode) 24 | fmt.Println(resp.Header.Get("Content-Type")) 25 | fmt.Println(string(body)) 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Protobuf/Addressbook/addressbook.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package tutorial; 3 | 4 | 5 | message Person { 6 | string name = 1; 7 | int32 id = 2; // Unique ID number for this person. 8 | string email = 3; 9 | 10 | enum PhoneType { 11 | MOBILE = 0; 12 | HOME = 1; 13 | WORK = 2; 14 | } 15 | 16 | message PhoneNumber { 17 | string number = 1; 18 | PhoneType type = 2; 19 | } 20 | 21 | repeated PhoneNumber phones = 4; 22 | } 23 | 24 | // Our address book file is just one of these. 25 | message AddressBook { 26 | repeated Person people = 1; 27 | } 28 | 29 | 30 | -------------------------------------------------------------------------------- /PDF/Unicodepdf.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/signintech/gopdf" 5 | "log" 6 | ) 7 | 8 | func main() { 9 | pdf := gopdf.GoPdf{} 10 | pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: 595.28, H: 841.89}}) //595.28, 841.89 = A4 11 | pdf.AddPage() 12 | err := pdf.AddTTFFont("wts11", "/home/parvathavarthinik/Downloads/UnicodeFonts-IlaSundaram-Set1/UniIla.Sundaram-01.ttf") 13 | if err != nil { 14 | log.Print(err.Error()) 15 | return 16 | } 17 | 18 | err = pdf.SetFont("wts11", "", 14) 19 | if err != nil { 20 | log.Print(err.Error()) 21 | return 22 | } 23 | 24 | pdf.Cell(nil, "") 25 | pdf.WritePdf("hello.pdf") 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Errors/stacktrace.go: -------------------------------------------------------------------------------- 1 | // Errors package Stack Trace usages... 2 | package Errors 3 | 4 | import ( 5 | "fmt" 6 | 7 | "github.com/pkg/errors" 8 | ) 9 | 10 | // printErrStack prints the needed stack trace for the errors created via db operations. 11 | func printErrStack(err error, length int) error { 12 | type stackTracer interface { 13 | StackTrace() errors.StackTrace 14 | } 15 | 16 | err = errors.Wrap(err, "Error") 17 | newErr, ok := err.(stackTracer) 18 | if !ok { 19 | panic("oops, err does not implement stackTracer") 20 | } 21 | 22 | st := newErr.StackTrace() 23 | fmt.Printf("%+v\n", st[:length]) // Required four frames. 24 | 25 | return nil 26 | } 27 | -------------------------------------------------------------------------------- /NSQLearning/README.md: -------------------------------------------------------------------------------- 1 | # NSQ Implemention: 2 | 3 | ## Run below three commands before running NSQ Implementation. 4 | 5 | ### 1. nsqlookupd - a demon which manages NSQ topology information. 6 | nohup nsqlookupd & 7 | 8 | ### 2. nsqd - a daemon that receives, queues, and delivers messages to clients. 9 | 10 | 11 | ```bash 12 | # consumer and producers must be in connect with this tcp connection listing on port 4160. 13 | 14 | nohup nsqd --lookupd-tcp-address=127.0.0.1:4160 & 15 | ``` 16 | 17 | ### 3. nsqadmin - Web UI to view aggregated cluster stats in realtime and perform various administrative tasks. 18 | 19 | ```bash 20 | nohup nsqadmin --lookupd-http-address=127.0.0.1:4161 & 21 | ``` -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Launch", 9 | "type": "go", 10 | "request": "launch", 11 | "mode": "debug", 12 | "remotePath": "", 13 | "port": 2345, 14 | "host": "127.0.0.1", 15 | "program": "${fileDirname}", 16 | "env": {}, 17 | "args": [], 18 | "showLog": true 19 | } 20 | ] 21 | } -------------------------------------------------------------------------------- /Command/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2019 NAME HERE 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package main 17 | 18 | import "golang-workspace/Command/cmd" 19 | 20 | func main() { 21 | cmd.Execute() 22 | } 23 | -------------------------------------------------------------------------------- /Http/cookies.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "log" 6 | "net/http" 7 | "strconv" 8 | ) 9 | 10 | func main() { 11 | http.HandleFunc("/", foo) 12 | http.Handle("/favicon.ico", http.NotFoundHandler()) 13 | http.ListenAndServe(":8000", nil) 14 | } 15 | 16 | func foo(res http.ResponseWriter, req *http.Request) { 17 | 18 | cookie, err := req.Cookie("my-cookie") 19 | 20 | if err == http.ErrNoCookie { 21 | cookie = &http.Cookie{ 22 | Name: "my-cookie", 23 | Value: "0", 24 | } 25 | } 26 | log.Print(cookie.Value) 27 | 28 | count, err := strconv.Atoi(cookie.Value) 29 | if err != nil { 30 | log.Fatalln(err) 31 | } 32 | count++ 33 | cookie.Value = strconv.Itoa(count) 34 | 35 | http.SetCookie(res, cookie) 36 | 37 | io.WriteString(res, cookie.Value) 38 | } 39 | -------------------------------------------------------------------------------- /Http/websocket/Server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | 8 | "golang.org/x/net/websocket" 9 | ) 10 | 11 | func Echo(ws *websocket.Conn) { 12 | var err error 13 | 14 | for { 15 | var reply string 16 | if err = websocket.Message.Receive(ws, &reply); err != nil { 17 | fmt.Println("Can't receive") 18 | break 19 | } 20 | 21 | fmt.Println("Received back from client: " + reply) 22 | msg := "Received: " + reply 23 | fmt.Println("Sending to client: " + msg) 24 | 25 | err := websocket.Message.Send(ws, msg) 26 | if err != nil { 27 | panic(err) 28 | } 29 | } 30 | } 31 | 32 | func main() { 33 | if err := http.ListenAndServe(":1234", websocket.Handler(Echo)); err != nil { 34 | log.Fatal("ListenAndServe:", err) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Golang WorkSpace 2 | 3 | A Collection of works and other experimental works in golang. 4 | 5 | Since this workspace is getting huge, i have started moving things into diffrent branches. 6 | checkout to the other branches and see what you can get from there. 7 | 8 | Enjoy :) 9 | 10 | 11 | 12 | 13 | 14 | 35 | -------------------------------------------------------------------------------- /Time/timepackage.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func main() { 9 | 10 | now := time.Now() 11 | fmt.Println(now) 12 | fmt.Println(now.Format(time.RFC3339)) 13 | fmt.Println(now.Format(time.RFC822)) 14 | fmt.Println(now.Format(time.RFC1123Z)) 15 | fmt.Println(now.Format(time.RFC850)) 16 | 17 | //seconds :=now.Unix() 18 | //fmt.Println(seconds) 19 | //nanoseconds := now.UnixNano() 20 | //fmt.Println(nanoseconds) 21 | 22 | // 23 | //then := time.Date( 24 | // 2009, 11, 17, 20, 34, 58, 651387237, time.UTC) 25 | //fmt.Println(then) 26 | //fmt.Println(then.Weekday()) 27 | //fmt.Println(then.After(now)) 28 | //fmt.Println(then.Before(now)) 29 | //fmt.Println(then.Equal(now)) 30 | //timediffrence := then.Sub(now) 31 | //fmt.Println(timediffrence) 32 | 33 | } 34 | -------------------------------------------------------------------------------- /File/getFileName.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "path/filepath" 6 | "reflect" 7 | "runtime" 8 | "time" 9 | ) 10 | 11 | func main() { 12 | getFileName(1) 13 | time.Sleep(time.Hour) 14 | } 15 | 16 | func getFileName(shift int) { 17 | go func() { 18 | pc, file, line, ok := runtime.Caller(shift) 19 | log.Println(reflect.TypeOf(pc)) 20 | var s []uintptr 21 | s = append(s, pc) 22 | log.Println(reflect.TypeOf(file)) 23 | log.Println(file) 24 | log.Println(reflect.TypeOf(line)) 25 | log.Println(line) 26 | if !ok { 27 | file = "???" 28 | line = 0 29 | } else { 30 | file = filepath.Base(file) 31 | } 32 | function := runtime.FuncForPC(pc) 33 | log.Println("functionname", function.Name()) 34 | log.Println() 35 | 36 | //fmt.Printf("%s:%d", file, line) 37 | //frames :=runtime.CallersFrames(s) 38 | 39 | }() 40 | } 41 | -------------------------------------------------------------------------------- /Zap Logging/src/globallogger/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "go.uber.org/zap" 7 | ) 8 | 9 | func main() { 10 | fmt.Printf("\n*** Using the global logger out of the box\n\n") 11 | 12 | zap.S().Infow("An info message", "iteration", 1) 13 | 14 | fmt.Printf("\n*** After replacing the global logger with a development logger\n\n") 15 | logger, _ := zap.NewDevelopment() 16 | zap.ReplaceGlobals(logger) 17 | zap.S().Infow("An info message", "iteration", 1) 18 | 19 | fmt.Printf("\n*** After replacing the global logger with a production logger\n\n") 20 | logger, _ = zap.NewProduction() 21 | undo := zap.ReplaceGlobals(logger) 22 | zap.S().Infow("An info message", "iteration", 1) 23 | 24 | fmt.Printf("\n*** After undoing the last replacement of the global logger\n\n") 25 | undo() 26 | zap.S().Infow("An info message", "iteration", 1) 27 | 28 | } 29 | -------------------------------------------------------------------------------- /SQL/connect.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | 7 | _ "github.com/go-sql-driver/mysql" 8 | ) 9 | 10 | func main() { 11 | db := connectSQL() 12 | defer db.Close() 13 | 14 | query := "SELECT * From shop;" 15 | rows, err := db.Query(query) 16 | if err != nil { 17 | panic(err) 18 | } 19 | 20 | defer rows.Close() 21 | for rows.Next() { 22 | var data struct { 23 | article int 24 | dealer string 25 | price string 26 | } 27 | 28 | rows.Scan(&data.article, &data.dealer, &data.price) 29 | fmt.Printf("%+v\n", data) 30 | } 31 | } 32 | 33 | func connectSQL() *sql.DB { 34 | db, err := sql.Open("mysql", "root:hariprasad@tcp(127.0.0.1:3306)/menagerie") 35 | if err != nil { 36 | panic(err) 37 | } 38 | 39 | err = db.Ping() 40 | if err != nil { 41 | panic("sorry, failed to connect db") 42 | } 43 | 44 | return db 45 | } 46 | -------------------------------------------------------------------------------- /Http/websocket/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 21 |

WebSocket Echo Test

22 |
23 |

24 | Message: 25 |

26 |
27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Time/24TO12.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | ) 7 | 8 | func main() { 9 | 10 | 11 | minuites := []int{500, 330} 12 | for i := 0; i < len(minuites); i++ { 13 | data := getTime(minuites[i]) 14 | log.Println(data) 15 | } 16 | } 17 | 18 | func getTime(minuite int) string { 19 | var currentMinuite string 20 | var hour int 21 | var minuites int 22 | hour = time / 60 23 | minuites = time % 60 24 | currentMinuite = fmt.Sprint(minuites) 25 | 26 | if len(currentMinuite) == 1 { 27 | currentMinuite = "0" + currentMinuite 28 | } 29 | check := false 30 | if hour >= 12 { 31 | check = true 32 | hour = hour - 12 33 | } 34 | hoursData := fmt.Sprint(hour) 35 | 36 | if len(hoursData) == 1 { 37 | hoursData = "0" + hoursData 38 | } 39 | finalData := hoursData + ":" + currentMinuite + "PM" 40 | if check { 41 | finalData = hoursData + ":" + currentMinuite + "AM" 42 | } 43 | 44 | return finalData 45 | } 46 | -------------------------------------------------------------------------------- /PDF/goFpdf.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/jung-kurt/gofpdf" 5 | "io/ioutil" 6 | "log" 7 | ) 8 | 9 | func main() { 10 | pdf := gofpdf.New("P", "mm", "A4", "/home/parvathavarthinik/kpm/goworkspace/src/github.com/jung-kurt/gofpdf/font/") 11 | //pdf.AddFont("Calligrapher", "", "TSCu_SaiIndira.json") 12 | //pdf.AddFont("Calligrapher", "", "SaiEmbed-forPDF.json") 13 | 14 | json, _ := ioutil.ReadFile("/home/parvathavarthinik/kpm/goworkspace/src/github.com/jung-kurt/gofpdf/font/UniIla.Sundaram-01.json") 15 | 16 | zip, _ := ioutil.ReadFile("/home/parvathavarthinik/kpm/goworkspace/src/github.com/jung-kurt/gofpdf/font/UniIla.Sundaram-01.z") 17 | 18 | pdf.AddFontFromBytes("Calligrapher", "", json, zip) 19 | pdf.AddPage() 20 | //ln := pdf.UnicodeTranslatorFromDescriptor("") 21 | log.Print(`t`) 22 | pdf.SetCompression(true) 23 | pdf.SetFont("Calligrapher", "", 35) 24 | pdf.Cell(0, 10, `தயாதளமனகரைந`) 25 | fileStr := "gofpdf.pdf" 26 | 27 | err := pdf.OutputFileAndClose(fileStr) 28 | if err != nil { 29 | log.Print(err) 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Profiling/new.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "log" 6 | "os" 7 | "runtime" 8 | "runtime/pprof" 9 | ) 10 | 11 | var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`") 12 | var memprofile = flag.String("memprofile", "", "write memory profile to `file`") 13 | 14 | func main() { 15 | 16 | flag.Parse() 17 | if *cpuprofile != "" { 18 | f, err := os.Create(*cpuprofile) 19 | if err != nil { 20 | log.Fatal("could not create CPU profile: ", err) 21 | } 22 | if err := pprof.StartCPUProfile(f); err != nil { 23 | log.Fatal("could not start CPU profile: ", err) 24 | } 25 | defer pprof.StopCPUProfile() 26 | } 27 | 28 | // ... rest of the program ... 29 | 30 | if *memprofile != "" { 31 | f, err := os.Create(*memprofile) 32 | if err != nil { 33 | log.Fatal("could not create memory profile: ", err) 34 | } 35 | runtime.GC() // get up-to-date statistics 36 | if err := pprof.WriteHeapProfile(f); err != nil { 37 | log.Fatal("could not write memory profile: ", err) 38 | } 39 | f.Close() 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /GTK/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/conformal/gotk3/gtk" 5 | "log" 6 | ) 7 | 8 | func main() { 9 | // Initialize GTK without parsing any command line arguments. 10 | gtk.Init(nil) 11 | 12 | // Create a new toplevel window, set its title, and connect it to the 13 | // "destroy" signal to exit the GTK main loop when it is destroyed. 14 | win, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) 15 | if err != nil { 16 | log.Fatal("Unable to create window:", err) 17 | } 18 | win.SetTitle("Simple Example") 19 | win.Connect("destroy", func() { 20 | gtk.MainQuit() 21 | }) 22 | 23 | // Create a new label widget to show in the window. 24 | l, err := gtk.LabelNew("Hello, gotk3!") 25 | if err != nil { 26 | log.Fatal("Unable to create label:", err) 27 | } 28 | 29 | // Add the label to the window. 30 | win.Add(l) 31 | 32 | // Set the default window size. 33 | win.SetDefaultSize(800, 600) 34 | 35 | // Recursively show all widgets contained in this window. 36 | win.ShowAll() 37 | 38 | // Begin executing the GTK main loop. This blocks until 39 | // gtk.MainQuit() is run. 40 | gtk.Main() 41 | } 42 | -------------------------------------------------------------------------------- /Zap Logging/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Sandip Bhattacharya 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Template/csstemplate.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "text/template" 6 | ) 7 | 8 | type Header struct { 9 | Background string 10 | Color string 11 | } 12 | 13 | type Inventory struct { 14 | Material string 15 | Count uint 16 | } 17 | 18 | func main() { 19 | change := &Header{"white", "black"} 20 | tmpl, err := template.New("template").ParseFiles("design.css") 21 | if err != nil { 22 | panic(err) 23 | } 24 | 25 | err = tmpl.ExecuteTemplate(w, "design.css", change) 26 | if err != nil { 27 | panic(err) 28 | } 29 | //sweaters := Inventory{"wool", 17} 30 | //tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}") 31 | //if err != nil { panic(err) } 32 | //err = tmpl.Execute(os.Stdout, sweaters) 33 | //if err != nil { panic(err) } 34 | 35 | //filePath := "design.css" 36 | // 37 | //var file, err = os.OpenFile(filePath, os.O_RDWR, 0644) 38 | //defer file.Close() 39 | // 40 | //// write some text to file 41 | //file.WriteString("halo\n") 42 | // 43 | //file.WriteString("mari belajar golang\n") 44 | // 45 | // 46 | //// save changes 47 | //err = file.Sync() 48 | //if err !=nil{ 49 | // panic(err) 50 | //} 51 | 52 | } 53 | -------------------------------------------------------------------------------- /Benchmark/fibonacci_test.go: -------------------------------------------------------------------------------- 1 | // A sample Benchmarking example for fibonacci sequeance. 2 | 3 | package Benchmarking 4 | 5 | import ( 6 | "testing" 7 | ) 8 | 9 | func Fib(n int) int { 10 | if n < 2 { 11 | return n 12 | } 13 | return Fib(n-1) + Fib(n-2) 14 | } 15 | 16 | func benchmarkFib(i int, b *testing.B) { 17 | // run the Fib function b.N times 18 | for n := 0; n < b.N; n++ { 19 | Fib(i) 20 | } 21 | } 22 | 23 | func BenchmarkFib1(b *testing.B) { benchmarkFib(1, b) } 24 | func BenchmarkFib2(b *testing.B) { benchmarkFib(2, b) } 25 | func BenchmarkFib3(b *testing.B) { benchmarkFib(3, b) } 26 | func BenchmarkFib10(b *testing.B) { benchmarkFib(10, b) } 27 | func BenchmarkFib20(b *testing.B) { benchmarkFib(20, b) } 28 | func BenchmarkFib40(b *testing.B) { benchmarkFib(40, b) } 29 | 30 | func TestFib(t *testing.T) { 31 | type args struct { 32 | n int 33 | } 34 | tests := []struct { 35 | name string 36 | args args 37 | want int 38 | }{ 39 | // TODO: Add test cases. 40 | } 41 | for _, tt := range tests { 42 | t.Run(tt.name, func(t *testing.T) { 43 | if got := Fib(tt.args.n); got != tt.want { 44 | t.Errorf("Fib() = %v, want %v", got, tt.want) 45 | } 46 | }) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /GoRoutines/race/main.go: -------------------------------------------------------------------------------- 1 | // This sample program demonstrates how to create race 2 | // conditions in our programs. We don't want to do this. 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "log" 8 | "sync" 9 | ) 10 | 11 | var ( 12 | // counter is a variable incremented by all goroutines. 13 | counter int 14 | wg sync.WaitGroup 15 | ) 16 | 17 | // main is the entry point for all Go programs. 18 | // Run: go run --race main.go 19 | func main() { 20 | 21 | // Create two goroutines. 22 | go incCounter(1) 23 | go incCounter(2) 24 | fmt.Println("Final Counter:", counter) 25 | } 26 | 27 | // incCounter increments the package level counter variable. 28 | func incCounter(id int) { 29 | // Schedule the call to Done to tell main we are done. 30 | defer wg.Done() 31 | for count := 0; count < 1; count++ { 32 | 33 | // Capture the value of Counter. 34 | value := counter 35 | 36 | // Yield the thread and be placed back in queue. 37 | log.Println("before scheduling.. by Routine: ", id) 38 | // runtime.Gosched() 39 | log.Println("After scheduling... by Routine: ", id) 40 | // Increment our local value of Counter. 41 | value++ 42 | // Store the value back into Counter. 43 | counter = value 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Command/cobra-readme.md: -------------------------------------------------------------------------------- 1 | cobra-example 2 | ============= 3 | 4 | An example application built with [cobra](https://github.com/spf13/cobra) 5 | 6 | # Steps 7 | 8 | 1. Install cobra 9 | 10 | `go get github.com/spf13/cobra/cobra` 11 | 12 | 2. Initialize cobra-example application 13 | 14 | `$GOPATH/bin/cobra init github.com/dharmeshkakadia/cobra-example` 15 | 16 | 3. Add `hello` and `bye` sub commands to our example app 17 | 18 | `$GOPATH/bin/cobra add hello` 19 | 20 | `$GOPATH/bin/cobra add bye` 21 | 22 | 4. Edit `cmd/hello.go`, `cmd/bye.go` and `main.go` to reflect the command description and logic required. 23 | 24 | 5. Run `main.go`. You would see full help and subcommands 25 | 26 | ``` 27 | go run main.go 28 | 29 | This application shows how to create modern CLI 30 | applications in go using Cobra CLI library 31 | 32 | Usage: 33 | cobra-example [command] 34 | 35 | Available Commands: 36 | bye says bye 37 | hello says hello 38 | help Help about any command 39 | 40 | Flags: 41 | --config string config file (default is $HOME/.cobra-example.yaml) 42 | -h, --help help for cobra-example 43 | -t, --toggle Help message for toggle 44 | ``` 45 | -------------------------------------------------------------------------------- /GoRoutines/runner/main/runner_example.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "golang-workspace/GoRoutines/runner" 5 | "log" 6 | "os" 7 | "sync" 8 | "time" 9 | ) 10 | 11 | // timeout is the number of second the program has to finish. 12 | const timeout = 1 * time.Millisecond 13 | 14 | var wg = sync.WaitGroup{} 15 | 16 | func main() { 17 | log.Println("Starting work.") 18 | 19 | // Create a new timer value for this run. 20 | r := runner.New(timeout) 21 | wg.Add(4) 22 | 23 | // Add the tasks to be run. 24 | r.Add(createTask(), createTask(), createTask(), createTask()) 25 | 26 | // Run the tasks and handle the result. 27 | if err := r.Start(); err != nil { 28 | switch err { 29 | case runner.ErrTimeout: 30 | log.Println("Terminating due to timeout.") 31 | os.Exit(1) 32 | case runner.ErrInterrupt: 33 | log.Println("Terminating due to interrupt.") 34 | os.Exit(2) 35 | } 36 | } 37 | 38 | wg.Wait() 39 | log.Println("Process ended.") 40 | } 41 | 42 | // createTask returns an example task that sleeps for the specified 43 | // number of seconds based on the id. 44 | func createTask() func(int) { 45 | return func(id int) { 46 | log.Printf("Processor - Task #%d.", id) 47 | time.Sleep(time.Duration(id) * time.Second) 48 | wg.Done() 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Server/gzip header.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "compress/gzip" 5 | "encoding/json" 6 | "net/http" 7 | //"log" 8 | "log" 9 | ) 10 | 11 | func main() { 12 | 13 | http.HandleFunc("/", ResponseHandler) 14 | http.ListenAndServe(":9999", nil) 15 | 16 | } 17 | 18 | func ResponseHandler(w http.ResponseWriter, r *http.Request) { 19 | //var render interface{} 20 | msg := "This si the response" 21 | res := make(map[string]interface{}) 22 | res["message"] = msg 23 | resByte, _ := json.MarshalIndent(res, "", " ") 24 | //render = msg 25 | //log.Println(render) 26 | log.Println(resByte) 27 | w.Header().Add("Accept-Charset", "utf-8") 28 | w.Header().Add("Content-Type", "application/json") 29 | w.Header().Set("Content-Encoding", "gzip") 30 | w.WriteHeader(http.StatusOK) 31 | // Gzip data 32 | gz := gzip.NewWriter(w) 33 | //gz.Write(render.([]byte)) 34 | gz.Write(resByte) 35 | gz.Close() 36 | 37 | } 38 | 39 | func JsonGetHandler(w http.ResponseWriter, r *http.Request) { 40 | // create header 41 | 42 | } 43 | 44 | func RenderJSON(w http.ResponseWriter, status int, res interface{}) { 45 | resByte, _ := json.MarshalIndent(res, "", " ") 46 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 47 | w.WriteHeader(status) 48 | w.Write(resByte) 49 | } 50 | -------------------------------------------------------------------------------- /OpenAPI&Swagger/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | 7 | "github.com/davecgh/go-spew/spew" 8 | "github.com/getkin/kin-openapi/openapi3" 9 | ) 10 | 11 | func main() { 12 | server := &openapi3.Server{ 13 | URL: "http://localhost:8080", 14 | Description: "This is my test server", 15 | Variables: map[string]*openapi3.ServerVariable{ 16 | "Variable": { 17 | Enum: []interface{}{}, 18 | Default: "anything", 19 | Description: "this is server variable", 20 | }, 21 | }, 22 | } 23 | 24 | swagger := openapi3.Swagger{ 25 | OpenAPI: "3.0.0", 26 | } 27 | 28 | swagger.AddServer(server) 29 | 30 | data, err := swagger.MarshalJSON() 31 | if err != nil { 32 | 33 | // TEMP: Snippet for debugging. remove it before commit 34 | spew.Printf("\n err= %+v \n\n", err) 35 | 36 | } 37 | 38 | file, err := os.Create("swagger.json") 39 | defer file.Close() 40 | if err != nil { 41 | log.Fatal("Failed to create file, Error: ", err.Error()) 42 | } 43 | 44 | // Write bytes to file 45 | byteSlice := data 46 | bytesWrittern, err := file.Write(byteSlice) 47 | if err != nil { 48 | log.Fatal(err) 49 | } 50 | 51 | // TEMP: Snippet for debugging. remove it before commit 52 | spew.Printf("\n byteswrittern= %+v \n\n", bytesWrittern) 53 | } 54 | -------------------------------------------------------------------------------- /Zap Logging/src/globallogger/README.md: -------------------------------------------------------------------------------- 1 | # Using global loggers 2 | 3 | zap also seems to offer global loggers - `zap.L()` for the mandatory structure logger, and `zap.S()`, for the _Sugared_ logger. 4 | 5 | From what I have seen, these loggers are not meant to be used out of the box (like `log.Print()` in the standard library), but rather their purpose seems only to provide a shared logger throughout the code. If you really want to use it, you need to [replace](https://godoc.org/go.uber.org/zap#ReplaceGlobals) the core with that of a different logger. You are also provided a way to _undo_ a replacement. Out of the box, the global loggers have no output. 6 | 7 | ```console 8 | $ go run src/globallogger/main.go 9 | 10 | *** Using the global logger out of the box 11 | 12 | 13 | *** After replacing the global logger with a development logger 14 | 15 | 2018-05-02T16:24:40.992-0700 INFO globallogger/main.go:17 An info message {"iteration": 1} 16 | 17 | *** After replacing the global logger with a production logger 18 | 19 | {"level":"info","ts":1525303480.993161,"caller":"globallogger/main.go:22","msg":"An info message","iteration":1} 20 | 21 | *** After undoing the last replacement of the global logger 22 | 23 | 2018-05-02T16:24:40.993-0700 INFO globallogger/main.go:26 An info message {"iteration": 1} 24 | ``` 25 | 26 | -------------------------------------------------------------------------------- /Http/uploadAnddonwload.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "log" 6 | "net/http" 7 | //"fmt" 8 | "bytes" 9 | "github.com/julienschmidt/httprouter" 10 | "gopkg.in/mgo.v2" 11 | "os" 12 | ) 13 | 14 | type Files struct { 15 | File []byte 16 | } 17 | 18 | func download(res http.ResponseWriter, req *http.Request, _ httprouter.Params) { 19 | session, _ := mgo.Dial("localhost:27017") 20 | Files := &Files{} 21 | res.Header().Set("Content-Disposition", "attachment;") 22 | session.DB("uploads").C("files").Find(nil).One(Files) 23 | res.Write(Files.File) 24 | log.Println("file is downloaded") 25 | } 26 | func uploadHandler(res http.ResponseWriter, req *http.Request, _ httprouter.Params) { 27 | 28 | file, _, _ := req.FormFile("file") 29 | 30 | buffer := bytes.Buffer{} 31 | io.Copy(&buffer, file) 32 | 33 | session, err := mgo.Dial("localhost:27017") 34 | if err != nil { 35 | os.Exit(1) 36 | } 37 | defer session.Close() 38 | Files := &Files{ 39 | File: buffer.Bytes()} 40 | session.DB("uploads").C("files").Insert(Files) 41 | 42 | session.DB("uploads").C("files").Find(nil).One(Files) 43 | res.Write(Files.File) 44 | //fmt.Fprintf(res,Files.File) 45 | } 46 | func main() { 47 | router := httprouter.New() 48 | router.POST("/upload", uploadHandler) 49 | router.GET("/download", download) 50 | http.ListenAndServe(":8080", router) 51 | } 52 | -------------------------------------------------------------------------------- /GoRoutines/atomic/main.go: -------------------------------------------------------------------------------- 1 | // This sample program demonstrates how to use the atomic 2 | // package functions Store and Load to provide safe access 3 | // to numeric types. 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "sync" 9 | "sync/atomic" 10 | "time" 11 | ) 12 | 13 | var ( 14 | // shutdown is a flag to alert running goroutines to shutdown. 15 | shutdown int64 16 | // wg is used to wait for the program to finish. 17 | wg sync.WaitGroup 18 | ) 19 | 20 | // main is the entry point for all Go programs. 21 | func main() { 22 | // Add a count of two, one for each goroutine. 23 | wg.Add(2) 24 | // Create two goroutines. 25 | go doWork("A") 26 | go doWork("B") 27 | // Give the goroutines time to run. 28 | time.Sleep(1 * time.Second) 29 | // Safely flag it is time to shutdown. 30 | fmt.Println("Shutdown Now") 31 | atomic.StoreInt64(&shutdown, 1) 32 | // Wait for the goroutines to finish. 33 | wg.Wait() 34 | } 35 | 36 | // doWork simulates a goroutine performing workP and 37 | // checking the Shutdown flag to terminate early. 38 | func doWork(name string) { 39 | // Schedule the call to Done to tell main we are done. 40 | 41 | defer wg.Done() 42 | for { 43 | fmt.Printf("Doing %s Work\n", name) 44 | time.Sleep(250 * time.Millisecond) 45 | // Do we need to shutdown. 46 | if atomic.LoadInt64(&shutdown) == 1 { 47 | fmt.Printf("Shutting %s Down\n", name) 48 | break 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /DesignPatterns/Creational/Builder/builder.go: -------------------------------------------------------------------------------- 1 | package Design_Pattern 2 | 3 | import "strconv" 4 | import "fmt" 5 | 6 | type Color string 7 | type Make string 8 | type Model string 9 | 10 | const ( 11 | BLUE Color = "blue" 12 | RED = "red" 13 | ) 14 | 15 | type Car interface { 16 | Drive() string 17 | Stop() string 18 | } 19 | 20 | type CarBuilder interface { 21 | TopSpeed(int) CarBuilder 22 | Paint(Color) CarBuilder 23 | Build() Car 24 | } 25 | 26 | type carBuilder struct { 27 | speedOption int 28 | color Color 29 | } 30 | 31 | func (cb *carBuilder) TopSpeed(speed int) CarBuilder { 32 | cb.speedOption = speed 33 | return cb 34 | } 35 | 36 | func (cb *carBuilder) Paint(color Color) CarBuilder { 37 | cb.color = color 38 | return cb 39 | } 40 | 41 | func (cb *carBuilder) Build() Car { 42 | return &car{ 43 | topSpeed: cb.speedOption, 44 | color: cb.color, 45 | } 46 | } 47 | 48 | func New() CarBuilder { 49 | return &carBuilder{} 50 | } 51 | 52 | type car struct { 53 | topSpeed int 54 | color Color 55 | } 56 | 57 | func (c *car) Drive() string { 58 | return "Driving at speed: " + strconv.Itoa(c.topSpeed) 59 | } 60 | 61 | func (c *car) Stop() string { 62 | return "Stopping a " + string(c.color) + " car" 63 | } 64 | 65 | func main() { 66 | builder := New() 67 | car := builder.TopSpeed(50).Paint(BLUE).Build() 68 | 69 | fmt.Println(car.Drive()) 70 | fmt.Println(car.Stop()) 71 | } 72 | -------------------------------------------------------------------------------- /DesignPatterns/CloudDistributed/CircuitBreaker/CircuitBreaker.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "log" 6 | "net/http" 7 | 8 | "github.com/sony/gobreaker" 9 | ) 10 | 11 | var cb *gobreaker.CircuitBreaker 12 | 13 | func init() { 14 | var st gobreaker.Settings 15 | st.Name = "HTTP GET" 16 | st.ReadyToTrip = func(counts gobreaker.Counts) bool { 17 | failureRatio := float64(counts.TotalFailures) / float64(counts.Requests) 18 | return counts.Requests >= 3 && failureRatio >= 0.6 19 | } 20 | 21 | st.OnStateChange = func(name string, from gobreaker.State, to gobreaker.State) { 22 | log.Printf("Name: %#+v", name) 23 | log.Printf("From: %#+v", from) 24 | log.Printf("to: %#+v", to) 25 | } 26 | cb = gobreaker.NewCircuitBreaker(st) 27 | } 28 | 29 | // Get wraps http.Get in CircuitBreaker. 30 | func Get(url string) ([]byte, error) { 31 | var i = 0 32 | body, err := cb.Execute(func() (interface{}, error) { 33 | log.Printf("count: %#+v", i) 34 | i = i + 1 35 | resp, err := http.Get(url) 36 | if err != nil { 37 | return nil, err 38 | } 39 | 40 | defer resp.Body.Close() 41 | body, err := ioutil.ReadAll(resp.Body) 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | return body, nil 47 | }) 48 | if err != nil { 49 | return nil, err 50 | } 51 | 52 | return body.([]byte), nil 53 | } 54 | 55 | func main() { 56 | 57 | for { 58 | Get("http://192.168.2.12:8085") 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /DOSSimple/main.go: -------------------------------------------------------------------------------- 1 | // Simple Dos Attack with Concurrency. 2 | // Works well on Insecure websites and web applications. 3 | 4 | // How It works? 5 | //1. Just Set up max go routines which to achive Distributed attack. 6 | //2. Each Routine does infinite number of request to attack url . 7 | //3. After few micro seconds, try to vist the attack url via browser. 8 | //4. Boom !!! 9 | 10 | package main 11 | 12 | import ( 13 | "fmt" 14 | "log" 15 | "net/http" 16 | "os" 17 | "strconv" 18 | "sync" 19 | ) 20 | 21 | func main() { 22 | 23 | logFile, err := os.OpenFile("DOSSimple/attack.log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0777) 24 | if err != nil { 25 | fmt.Printf("Error in openning log file: %s", err.Error()) 26 | os.Exit(1) 27 | } 28 | 29 | log.SetOutput(logFile) 30 | 31 | attackUrl := "http://localhost:8080/" 32 | 33 | maxProcess := 0 34 | 35 | var wg sync.WaitGroup 36 | wg.Add(maxProcess) 37 | for i := 0; i < maxProcess; i++ { 38 | process := "PROCS[" + strconv.Itoa(i) + "]" 39 | go attackService(attackUrl, process) 40 | log.Print("check", i) 41 | } 42 | 43 | wg.Wait() 44 | } 45 | 46 | func attackService(attackUrl string, routine string) { 47 | i := 0 48 | for { 49 | _, err := http.Get(attackUrl) 50 | if err != nil { 51 | log.Printf("Error in %s, times %s - error: %+v", routine, i, err.Error()) 52 | i++ 53 | continue 54 | } 55 | 56 | i++ 57 | log.Printf("routine: %+v times: %+v", routine, i) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /PDF/Image.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "github.com/golang/freetype" 7 | "github.com/jung-kurt/gofpdf" 8 | "image" 9 | "image/draw" 10 | "image/jpeg" 11 | "io/ioutil" 12 | "log" 13 | ) 14 | 15 | func main() { 16 | 17 | dataFont, err := ioutil.ReadFile("/home/parvathavarthinik/Downloads/UnicodeFonts-IlaSundaram-Set1/Link to UniIla.Sundaram-01.ttf") 18 | f, err := freetype.ParseFont(dataFont) 19 | if err != nil { 20 | fmt.Printf("%v", err) 21 | } 22 | 23 | dst := image.NewRGBA(image.Rect(0, 0, 800, 600)) 24 | draw.Draw(dst, dst.Bounds(), image.White, image.ZP, draw.Src) 25 | c := freetype.NewContext() 26 | c.SetDst(dst) 27 | c.SetClip(dst.Bounds()) 28 | c.SetSrc(image.Black) 29 | c.SetFont(f) 30 | c.DrawString("யளனகயளக", freetype.Pt(0, 16)) 31 | pdf := gofpdf.New("P", "mm", "A4", "") 32 | pdf.AddPage() 33 | buf := new(bytes.Buffer) 34 | err = jpeg.Encode(buf, dst, nil) 35 | 36 | if err != nil { 37 | fmt.Printf("%v", err) 38 | } 39 | 40 | reader := bytes.NewReader(buf.Bytes()) 41 | //textName := "text1" 42 | //pdf.RegisterImageReader(textName, "jpg", reader) 43 | pdf.AddFontFromReader("new", "", reader) 44 | pdf.SetFont("new", "", 35) 45 | pdf.Cell(0, 10, `தயாதளமனகரைந`) 46 | fileStr := "gofpdf.pdf" 47 | err = pdf.OutputFileAndClose(fileStr) 48 | if err != nil { 49 | log.Print(err) 50 | } 51 | 52 | //pdf.Image(textName, 15, 15, 0, 0, false, "jpg", 0, "") 53 | //pdf.OutputFileAndClose("test.pdf") 54 | } 55 | -------------------------------------------------------------------------------- /MongoDB/Functions.go: -------------------------------------------------------------------------------- 1 | package MgoDb 2 | 3 | import ( 4 | "gopkg.in/mgo.v2" 5 | "gopkg.in/mgo.v2/bson" 6 | "log" 7 | //"net/http" 8 | //"encoding/json" 9 | //"io/ioutil" 10 | //"github.com/julienschmidt/httprouter" 11 | //"net/http" 12 | ) 13 | 14 | type Data struct { 15 | Id string `bson:"_id"` 16 | Value bson.JavaScript `bson:"value"` 17 | } 18 | 19 | func main() { 20 | 21 | res := make(map[string]interface{}) 22 | //router := httprouter.New() 23 | //router.Handle("POST","/check",handler) 24 | 25 | //if err := http.ListenAndServe(":1234",router); err != nil { 26 | // log.Fatal("ListenAndServe:", err) 27 | //} 28 | //js := mongoNow() 29 | DB := connectDatabase() 30 | //data := Data{"add",js} 31 | 32 | //DB.C("StackOverFlow").Insert( struct{Value interface{}}{Value: mongoNow()}) 33 | // DB.C("system.js").Insert(&data) 34 | 35 | err := DB.Run(bson.M{"eval": "add(5,5);"}, res) 36 | if err != nil { 37 | log.Println(err) 38 | } else { 39 | for key, val := range res { 40 | log.Println(key, " : ", val) 41 | } 42 | } 43 | } 44 | 45 | func mongoNow() bson.JavaScript { 46 | 47 | return bson.JavaScript{ 48 | // place your function in here in string 49 | Code: "function add(a,b){return a+b}", 50 | } 51 | } 52 | 53 | func connectDatabase() *mgo.Database { 54 | session, err := mgo.Dial("localhost:27017") 55 | if err != nil { 56 | log.Print(err) 57 | } 58 | session.SetMode(mgo.Monotonic, true) 59 | return session.DB("test") 60 | } 61 | -------------------------------------------------------------------------------- /Email/first.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "gopkg.in/gomail.v2" 6 | "io" 7 | "log" 8 | ) 9 | 10 | func main() { 11 | 12 | //{ 13 | // "Username": "User Name", 14 | // "Password": "", 15 | // "From": "Site name", or your domine 16 | // "Server": "", 17 | // "Port": 587 18 | //} 19 | 20 | // using smpt 21 | log.Println(sendEmail("template.html", "to email", "Testing")) 22 | 23 | // no smtp 24 | //Nosmtp() 25 | 26 | } 27 | 28 | func sendEmail(htmlTemplate, to, subject string) bool { 29 | msg := gomail.NewMessage() 30 | msg.SetHeader("From", "Sender email") 31 | msg.SetHeader("To", to) 32 | msg.SetHeader("Subject", subject) 33 | msg.SetBody("text/html", htmlTemplate) 34 | dialer := gomail.NewPlainDialer("{server name}", 587, "{user name}", "{password}") 35 | err := dialer.DialAndSend(msg) 36 | if err != nil { 37 | log.Print("Sending mail to "+to+": ", err) 38 | return false 39 | } 40 | 41 | return true 42 | } 43 | 44 | func Nosmtp() { 45 | m := gomail.NewMessage() 46 | m.SetHeader("From", "") 47 | m.SetHeader("To", "") 48 | m.SetHeader("Subject", "Hello!") 49 | m.SetBody("text/plain", "Hello!") 50 | 51 | s := gomail.SendFunc(func(from string, to []string, msg io.WriterTo) error { 52 | // Implements you email-sending function, for example by calling 53 | // an API, or running postfix, etc. 54 | fmt.Println("From:", from) 55 | fmt.Println("To:", to) 56 | return nil 57 | }) 58 | 59 | if err := gomail.Send(s, m); err != nil { 60 | panic(err) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Zap Logging/src/customencoder/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | 7 | "go.uber.org/zap" 8 | "go.uber.org/zap/zapcore" 9 | ) 10 | 11 | func SyslogTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { 12 | enc.AppendString(t.Format("Jan 2 15:04:05")) 13 | } 14 | 15 | func CustomLevelEncoder(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) { 16 | enc.AppendString("[" + level.CapitalString() + "]") 17 | } 18 | 19 | func main() { 20 | 21 | cfg := zap.Config{ 22 | Encoding: "console", 23 | OutputPaths: []string{"stderr"}, 24 | EncoderConfig: zapcore.EncoderConfig{ 25 | MessageKey: "message", 26 | TimeKey: "time", 27 | EncodeTime: zapcore.ISO8601TimeEncoder, 28 | LevelKey: "level", 29 | EncodeLevel: zapcore.CapitalLevelEncoder, 30 | }, 31 | } 32 | 33 | fmt.Printf("\n*** Using standard ISO8601 time encoder\n\n") 34 | 35 | // avoiding copying of atomic values 36 | cfg.Level = zap.NewAtomicLevelAt(zapcore.DebugLevel) 37 | 38 | logger, _ := cfg.Build() 39 | logger.Info("This should have an ISO8601 based time stamp") 40 | 41 | fmt.Printf("\n*** Using a custom time encoder\n\n") 42 | 43 | cfg.EncoderConfig.EncodeTime = SyslogTimeEncoder 44 | 45 | logger, _ = cfg.Build() 46 | logger.Info("This should have a syslog style time stamp") 47 | 48 | fmt.Printf("\n*** Using a custom level encoder\n\n") 49 | 50 | cfg.EncoderConfig.EncodeLevel = CustomLevelEncoder 51 | 52 | logger, _ = cfg.Build() 53 | logger.Info("This should have a interesting level name") 54 | 55 | } 56 | -------------------------------------------------------------------------------- /AST/ZupZup/parser.go: -------------------------------------------------------------------------------- 1 | // Sample program for golang ast parsing 2 | // 3 | // Source: https://zupzup.org/go-ast-traversal/ 4 | 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "go/ast" 10 | "go/parser" 11 | "go/printer" 12 | "go/token" 13 | "log" 14 | "os" 15 | "strings" 16 | 17 | "github.com/davecgh/go-spew/spew" 18 | ) 19 | 20 | func main() { 21 | fset := token.NewFileSet() 22 | node, err := parser.ParseFile(fset, "AST/ZupZup/sample.go", nil, parser.ParseComments) 23 | if err != nil { 24 | log.Fatal(err) 25 | } 26 | 27 | fmt.Println("Imports:") 28 | for _, i := range node.Imports { 29 | fmt.Println(i.Path.Value) 30 | } 31 | 32 | fmt.Println("Comments:") 33 | for _, c := range node.Comments { 34 | fmt.Print(c.Text()) 35 | } 36 | 37 | fmt.Println("Functions:") 38 | for _, f := range node.Decls { 39 | fn, ok := f.(*ast.FuncDecl) 40 | if !ok { 41 | continue 42 | } 43 | fmt.Println(fn.Name.Name) 44 | } 45 | 46 | ast.Inspect(node, func(n ast.Node) bool { 47 | // Find Return Statements 48 | ret, ok := n.(*ast.ReturnStmt) 49 | if ok { 50 | fmt.Printf("return statement found on line %d:\n\t", fset.Position(ret.Pos()).Line) 51 | printer.Fprint(os.Stdout, fset, ret) 52 | } 53 | 54 | // Find Functions 55 | fn, ok := n.(*ast.FuncDecl) 56 | if ok { 57 | var exported string 58 | if fn.Name.IsExported() { 59 | exported = "exported " 60 | } 61 | fmt.Printf("%sfunction declaration found on line %d: \n\t%s\n", exported, fset.Position(fn.Pos()).Line, fn.Name.Name) 62 | } 63 | 64 | return true 65 | }) 66 | } 67 | -------------------------------------------------------------------------------- /Gorilla/session.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | //"fmt" 5 | //"github.com/nu7hatch/gouuid" 6 | "github.com/gorilla/sessions" 7 | "log" 8 | "net/http" 9 | ) 10 | 11 | // For this code to run, you will need this package: 12 | // go get github.com/nu7hatch/gouuid 13 | 14 | func main() { 15 | 16 | http.HandleFunc("/", foo) 17 | http.Handle("/favicon.ico", http.NotFoundHandler()) 18 | http.ListenAndServe(":9999", nil) 19 | } 20 | 21 | func get(w http.ResponseWriter, req *http.Request) { 22 | 23 | } 24 | 25 | func foo(w http.ResponseWriter, req *http.Request) { 26 | // 27 | //cookie, err := req.Cookie("session-id") 28 | //if err != nil { 29 | // id, err := uuid.NewV4() 30 | // if err != nil { 31 | // log.Fatalln(err) 32 | // } 33 | // cookie = &http.Cookie{ 34 | // Name: "session-id", 35 | // Value: id.String(), 36 | // // Secure: true, 37 | // HttpOnly: true, 38 | // } 39 | // http.SetCookie(w, cookie) 40 | //} 41 | //fmt.Println(cookie) 42 | 43 | store := sessions.NewCookieStore([]byte("ahdsjffiwuhajdbnf")) 44 | log.Println("store:", store) 45 | store1 := sessions.NewCookieStore([]byte("anotherkey")) 46 | log.Println("store1:", store1) 47 | 48 | data, err := store.Get(req, "session-name") 49 | log.Println("data:", data) 50 | if err != nil { 51 | log.Println("Error in data") 52 | } 53 | data1, err := store.Get(req, "session-name1") 54 | if err != nil { 55 | log.Println("Error in data1") 56 | } 57 | log.Println("data1:", data1) 58 | 59 | data.Values["Foo"] = "hi" 60 | data.Values["Another data"] = "Hello World" 61 | data.Save(req, w) 62 | w.Write([]byte("Session is created")) 63 | } 64 | -------------------------------------------------------------------------------- /Command/cmd/bye.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2019 NAME HERE 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package cmd 17 | 18 | import ( 19 | "fmt" 20 | 21 | "github.com/spf13/cobra" 22 | ) 23 | 24 | // byeCmd represents the bye command 25 | var byeCmd = &cobra.Command{ 26 | Use: "bye", 27 | Short: "A brief description of your command", 28 | Long: `A longer description that spans multiple lines and likely contains examples 29 | and usage of using your command. For example: 30 | 31 | Cobra is a CLI library for Go that empowers applications. 32 | This application is a tool to generate the needed files 33 | to quickly create a Cobra application.`, 34 | Run: func(cmd *cobra.Command, args []string) { 35 | fmt.Println("bye called") 36 | }, 37 | } 38 | 39 | func init() { 40 | rootCmd.AddCommand(byeCmd) 41 | 42 | // Here you will define your flags and configuration settings. 43 | 44 | // Cobra supports Persistent Flags which will work for this command 45 | // and all subcommands, e.g.: 46 | // byeCmd.PersistentFlags().String("foo", "", "A help for foo") 47 | 48 | // Cobra supports local flags which will only run when this command 49 | // is called directly, e.g.: 50 | // byeCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 51 | } 52 | -------------------------------------------------------------------------------- /Gorilla/context.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/gorilla/context" 6 | "github.com/gorilla/mux" 7 | "net/http" 8 | ) 9 | 10 | type Key string 11 | 12 | const GlobalRequestVariable Key = "" 13 | 14 | func SetGlobalHandler(w http.ResponseWriter, r *http.Request) { 15 | context.Set(r, GlobalRequestVariable, "test") 16 | 17 | // will WORK because within request lifetime 18 | get, ok := context.GetOk(r, GlobalRequestVariable) 19 | w.Write([]byte(fmt.Sprintf("GetOK : [%v] and get what :[%v] ", ok, get))) 20 | 21 | // global variable still accessible as long the request is still alive 22 | // and everything is cleared because router from gorilla/mux will 23 | // automatically call context.Clear(r) 24 | // and cause GetGlobalHandler to fail 25 | // WHEN you point the browser url to example.com:8080/get 26 | 27 | // to make it work, you have to pass r down to inside SetGlobalHandler 28 | // while the request is still alive to InternalGetGlobalHandler 29 | InternalGetGlobalHandler(w, r) 30 | 31 | } 32 | 33 | func InternalGetGlobalHandler(w http.ResponseWriter, r *http.Request) { 34 | 35 | // will WORK because still within request lifetime 36 | get, ok := context.GetOk(r, GlobalRequestVariable) 37 | w.Write([]byte(fmt.Sprintf("\nInternal GetOK : [%v] and get what :[%v] ", ok, get))) 38 | 39 | } 40 | 41 | func GetGlobalHandler(w http.ResponseWriter, r *http.Request) { 42 | 43 | // will FAIL because NOT within request lifetime 44 | get, ok := context.GetOk(r, GlobalRequestVariable) 45 | w.Write([]byte(fmt.Sprintf("GetOK : [%v] and get what :[%v] ", ok, get))) 46 | 47 | } 48 | 49 | func main() { 50 | mx := mux.NewRouter() 51 | 52 | mx.HandleFunc("/", SetGlobalHandler) 53 | mx.HandleFunc("/get", GetGlobalHandler) 54 | 55 | http.ListenAndServe(":8080", mx) 56 | } 57 | -------------------------------------------------------------------------------- /Server/simpleGoServer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "html/template" 5 | "log" 6 | "net/http" 7 | "time" 8 | 9 | "context" 10 | "github.com/julienschmidt/httprouter" 11 | "simpleGoServer/server/con" 12 | "simpleGoServer/server/controllers" 13 | ) 14 | 15 | func init() { 16 | con.DbConnection() 17 | } 18 | 19 | func indexHandler(w http.ResponseWriter, r *http.Request) { 20 | t, _ := template.ParseFiles("public/index.html") 21 | greet := map[string]string{"greetings": "Hello world"} 22 | t.Execute(w, greet) 23 | } 24 | 25 | func loggingHandler(next http.Handler) http.Handler { 26 | fn := func(w http.ResponseWriter, r *http.Request) { 27 | t1 := time.Now() 28 | next.ServeHTTP(w, r) 29 | t2 := time.Now() 30 | status := w.Header().Get("code") 31 | w.Header().Del("code") 32 | log.Printf("[%s] %q %v - %s\n", r.Method, r.URL.String(), t2.Sub(t1), status) 33 | } 34 | 35 | return http.HandlerFunc(fn) 36 | } 37 | 38 | // Put params in context for sharing them between handlers 39 | func wrapHandler(next http.Handler) httprouter.Handle { 40 | return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { 41 | ctx := context.WithValue(r.Context(), "params", ps) 42 | next.ServeHTTP(w, r.WithContext(ctx)) 43 | } 44 | } 45 | 46 | func main() { 47 | mux := httprouter.New() 48 | 49 | mux.POST("/user", wrapHandler(loggingHandler(http.HandlerFunc(controllers.SaveUser)))) 50 | mux.GET("/user/:id", wrapHandler(loggingHandler(http.HandlerFunc(controllers.GetUser)))) 51 | 52 | mux.ServeFiles("/public/*filepath", http.Dir("public")) 53 | mux.GET("/", wrapHandler(http.HandlerFunc(indexHandler))) 54 | 55 | log.Print("Listening on: 8080") 56 | err := http.ListenAndServe(":8080", mux) 57 | if err != nil { 58 | log.Print("Error in listening server: ", err) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Command/cmd/hello.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2019 NAME HERE 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package cmd 17 | 18 | import ( 19 | "fmt" 20 | 21 | "github.com/spf13/cobra" 22 | ) 23 | 24 | // helloCmd represents the hello command 25 | var helloCmd = &cobra.Command{ 26 | Use: "hello", 27 | Short: "A brief description of your command", 28 | Long: `A longer description that spans multiple lines and likely contains examples 29 | and usage of using your command. For example: 30 | 31 | Cobra is a CLI library for Go that empowers applications. 32 | This application is a tool to generate the needed files 33 | to quickly create a Cobra application.`, 34 | Run: func(cmd *cobra.Command, args []string) { 35 | fmt.Println("hello called") 36 | }, 37 | } 38 | 39 | func init() { 40 | rootCmd.AddCommand(helloCmd) 41 | 42 | // Here you will define your flags and configuration settings. 43 | 44 | // Cobra supports Persistent Flags which will work for this command 45 | // and all subcommands, e.g.: 46 | // helloCmd.PersistentFlags().String("foo", "", "A help for foo") 47 | 48 | // Cobra supports local flags which will only run when this command 49 | // is called directly, e.g.: 50 | // helloCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 51 | } 52 | -------------------------------------------------------------------------------- /ImageGrayScale/grayscale.go: -------------------------------------------------------------------------------- 1 | /* 2 | This file converts the image to gray scale image 3 | 4 | Source: https://riptutorial.com/go/example/31693/convert-color-image-to-grayscale 5 | */ 6 | 7 | package main 8 | 9 | import ( 10 | "image" 11 | "log" 12 | "net/http" 13 | "os" 14 | 15 | "image/jpeg" 16 | "image/png" 17 | ) 18 | 19 | func main() { 20 | // Load image from remote through http 21 | // The Go gopher was designed by Renee French. (http://reneefrench.blogspot.com/) 22 | // Images are available under the Creative Commons 3.0 Attributions license. 23 | resp, err := http.Get("http://golang.org/doc/gopher/fiveyears.jpg") 24 | if err != nil { 25 | // handle error 26 | log.Fatal(err) 27 | } 28 | defer resp.Body.Close() 29 | 30 | // Decode image to JPEG 31 | img, _, err := image.Decode(resp.Body) 32 | if err != nil { 33 | // handle error 34 | log.Fatal(err) 35 | } 36 | log.Printf("Image type: %T", img) 37 | 38 | file, err := os.Create("ImageGrayScale/fiveyears.jpg") 39 | defer file.Close() 40 | if err != nil { 41 | log.Fatal("Failed to create file, Error: ", err.Error()) 42 | } 43 | defer file.Close() 44 | 45 | if err := jpeg.Encode(file, img, &jpeg.Options{Quality: 100}); err != nil { 46 | log.Fatal(err) 47 | } 48 | 49 | // Converting image to grayscale 50 | grayImg := image.NewGray(img.Bounds()) 51 | for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ { 52 | for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ { 53 | grayImg.Set(x, y, img.At(x, y)) 54 | } 55 | } 56 | 57 | // Working with grayscale image, e.g. convert to png 58 | f, err := os.Create("ImageGrayScale/fiveyears_gray.png") 59 | if err != nil { 60 | // handle error 61 | log.Fatal(err) 62 | } 63 | defer f.Close() 64 | 65 | if err := png.Encode(f, grayImg); err != nil { 66 | log.Fatal(err) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /DesignPatterns/Structural/Decorator/dynamic-function.go: -------------------------------------------------------------------------------- 1 | // This file implements Decortor pattern which adds functionality to the existing function PI. 2 | // source: https://github.com/tensor-programming/pattern-tutorial/blob/master/decorator/main.go 3 | 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "log" 9 | "math" 10 | "os" 11 | "sync" 12 | "time" 13 | ) 14 | 15 | type piFunc func(int) float64 16 | 17 | // logger(cache(Pi(n))) 18 | func wraplogger(fun piFunc, logger *log.Logger) piFunc { 19 | return func(n int) float64 { 20 | fn := func(n int) (result float64) { 21 | defer func(t time.Time) { 22 | logger.Printf("took=%v, n=%v, result=%v", time.Since(t), n, result) 23 | }(time.Now()) 24 | 25 | return fun(n) 26 | } 27 | return fn(n) 28 | } 29 | } 30 | 31 | // cache(logger(Pi(n))) 32 | func wrapcache(fun piFunc, cache *sync.Map) piFunc { 33 | return func(n int) float64 { 34 | fn := func(n int) float64 { 35 | key := fmt.Sprintf("n=%d", n) 36 | val, ok := cache.Load(key) 37 | if ok { 38 | return val.(float64) 39 | } 40 | result := fun(n) 41 | cache.Store(key, result) 42 | return result 43 | } 44 | return fn(n) 45 | } 46 | } 47 | 48 | func Pi(n int) float64 { 49 | ch := make(chan float64) 50 | 51 | for k := 0; k <= n; k++ { 52 | go func(ch chan float64, k float64) { 53 | ch <- 4 * math.Pow(-1, k) / (2*k + 1) 54 | }(ch, float64(k)) 55 | } 56 | 57 | result := 0.0 58 | for k := 0; k <= n; k++ { 59 | result += <-ch 60 | } 61 | 62 | return result 63 | } 64 | 65 | func divide(n int) float64 { 66 | return float64(n / 2) 67 | } 68 | 69 | func main() { 70 | f := wrapcache(Pi, &sync.Map{}) 71 | g := wraplogger(f, log.New(os.Stdout, "Test ", 1)) 72 | 73 | g(100000) 74 | g(20000) 75 | g(100000) 76 | 77 | f = wrapcache(divide, &sync.Map{}) 78 | g = wraplogger(f, log.New(os.Stdout, "Divide ", 1)) 79 | 80 | g(10000) 81 | g(2000) 82 | g(10) 83 | g(10000) 84 | 85 | } 86 | -------------------------------------------------------------------------------- /Http/middleware.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/justinas/alice" 6 | "log" 7 | "net/http" 8 | ) 9 | 10 | type numberDumper int 11 | 12 | func hello(w http.ResponseWriter, r *http.Request) { 13 | fmt.Println("ServeHttp") 14 | fmt.Fprintf(w, "Here's your number: %d\n", n) 15 | a := "hello buddy" 16 | b := []byte(a) 17 | w.Write(b) 18 | } 19 | 20 | func logger(h http.Handler) http.Handler { 21 | fmt.Println("logger") 22 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 23 | log.Printf("%s requested %s", r.RemoteAddr, r.URL) 24 | hello(w, r) 25 | //a:=1 26 | //return a 27 | }) 28 | } 29 | 30 | type headerSetter struct { 31 | key, val string 32 | handler http.Handler 33 | } 34 | 35 | func (hs headerSetter) ServeHTTP(w http.ResponseWriter, r *http.Request) { 36 | fmt.Println("ServeHttp2") 37 | w.Header().Set(hs.key, hs.val) 38 | hs.handler.ServeHTTP(w, r) 39 | } 40 | 41 | // type constructor func(http.Handler) http.Handler 42 | 43 | func newHeaderSetter(key, val string) func(http.Handler) http.Handler { 44 | fmt.Println("newHeaderSetter") 45 | return func(h http.Handler) http.Handler { // it satisfies the constructor 46 | return headerSetter{key, val, h} 47 | } 48 | } 49 | 50 | func main() { 51 | h := http.NewServeMux() 52 | 53 | h.Handle("/one", numberDumper(1)) 54 | h.Handle("/two", numberDumper(2)) 55 | h.Handle("/three", numberDumper(3)) 56 | h.Handle("/four", numberDumper(4)) 57 | 58 | fiveHS := newHeaderSetter("X-FIVE", "the best number") 59 | h.Handle("/five", fiveHS(numberDumper(5))) 60 | 61 | h.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 62 | w.WriteHeader(404) 63 | fmt.Fprintln(w, "That's not a supported number!") 64 | }) 65 | 66 | chain := alice.New( 67 | newHeaderSetter("X-FOO", "BAR"), 68 | newHeaderSetter("X-BAZ", "BUZ"), 69 | logger, 70 | ).Then(h) 71 | 72 | err := http.ListenAndServe(":9999", chain) 73 | log.Fatal(err) 74 | } 75 | -------------------------------------------------------------------------------- /Server/simpleGoServer/server/controllers/UserController.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/julienschmidt/httprouter" 7 | "gopkg.in/mgo.v2/bson" 8 | "io/ioutil" 9 | "net/http" 10 | "simpleGoServer/server/con" 11 | "simpleGoServer/server/models" 12 | "time" 13 | ) 14 | 15 | func renderJson(w http.ResponseWriter, code int, res interface{}) { 16 | resBytes, _ := json.MarshalIndent(res, "", " ") 17 | w.Header().Set("Content-Type", "application/json") 18 | w.Header().Set("code", fmt.Sprint(code)) 19 | w.WriteHeader(code) 20 | w.Write(resBytes) 21 | } 22 | 23 | func SaveUser(w http.ResponseWriter, r *http.Request) { 24 | res := make(map[string]interface{}) 25 | user := models.User{} 26 | 27 | reqBytes, _ := ioutil.ReadAll(r.Body) 28 | err := json.Unmarshal(reqBytes, &user) 29 | if err != nil { 30 | res["message"] = "Error in parsing json" 31 | res["error"] = err.Error() 32 | renderJson(w, http.StatusBadRequest, res) 33 | return 34 | } 35 | 36 | user.DateCreated = time.Now().UTC() 37 | user.LastUpdated = time.Now().UTC() 38 | 39 | info, err := con.Db.C("user").Upsert(models.User{}, &user) 40 | if info != nil { 41 | user.ID = info.UpsertedId.(bson.ObjectId) 42 | } 43 | 44 | if err != nil { 45 | res["message"] = "Error in save user" 46 | res["error"] = err.Error() 47 | renderJson(w, http.StatusBadRequest, res) 48 | return 49 | } 50 | 51 | res["message"] = "User saved successfully" 52 | res["user"] = user 53 | renderJson(w, http.StatusOK, res) 54 | } 55 | 56 | func GetUser(w http.ResponseWriter, r *http.Request) { 57 | res := make(map[string]interface{}) 58 | user := models.User{} 59 | params := r.Context().Value("params").(httprouter.Params) 60 | id := params.ByName("id") 61 | 62 | if !bson.IsObjectIdHex(id) { 63 | res["message"] = "Invalid object ID" 64 | renderJson(w, http.StatusBadRequest, res) 65 | return 66 | } 67 | 68 | err := con.Db.C("user").FindId(bson.ObjectIdHex(id)).One(&user) 69 | if err != nil { 70 | res["message"] = "User not found" 71 | res["error"] = err.Error() 72 | renderJson(w, http.StatusNotFound, res) 73 | return 74 | } 75 | 76 | renderJson(w, http.StatusOK, user) 77 | } 78 | -------------------------------------------------------------------------------- /MongoDB/student-collection.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "gopkg.in/mgo.v2" 8 | "gopkg.in/mgo.v2/bson" 9 | ) 10 | 11 | type Student struct { 12 | Id int `bson:"id,o"` 13 | Name string `bson:"-"` 14 | } 15 | 16 | func main() { 17 | session, err := mgo.Dial("localhost:27017") 18 | if err != nil { 19 | panic("error in connecting Databases") 20 | } 21 | defer session.Close() 22 | c := session.DB("school").C("student") 23 | /// FOR INSERTION 24 | c.Insert(&Student{Id: 1, Name: "nagaraj"}, &Student{Id: 2, Name: "sathya"}) 25 | var result []Student 26 | // FOR RETRIVING 27 | c.Find(bson.M{}).All(&result) 28 | fmt.Println(result) 29 | //FOR REMOVING 30 | err = c.Remove(bson.M{"id": 1}) 31 | if err != nil { 32 | fmt.Printf("remove fail %v\n", err) 33 | os.Exit(1) 34 | } 35 | fmt.Println("----------------------------------------------------------") 36 | var result1 []Student 37 | c.Find(bson.M{}).All(&result1) 38 | fmt.Println(result1) 39 | fmt.Println("----------------------------------------------------------") 40 | data := Student{} 41 | ret := c.Find(nil).Iter() 42 | for ret.Next(&data) { 43 | fmt.Printf("\nid %d Name %s\n", data.Id, data.Name) 44 | } 45 | err = c.Remove(bson.M{"name": "sathya"}) 46 | if err != nil { 47 | fmt.Printf("remove fail %v\n", err) 48 | // os.Exit(1) 49 | } 50 | c.UpdateAll(bson.M{"name": "sathya"}, bson.M{"$set": bson.M{"name": "kevin", "id": 2}}) 51 | fmt.Println("----------------------------------------------------------") 52 | data1 := Student{} 53 | ret2 := c.Find(nil).Sort("name").Iter() 54 | for ret2.Next(&data1) { 55 | fmt.Printf("\nid %d Name %s\n", data1.Id, data1.Name) 56 | } 57 | fmt.Println("----------------------------------------------------------") 58 | counts, _ := c.Count() 59 | fmt.Println("total data is", counts) 60 | c.RemoveAll(nil) 61 | fmt.Println("----------------------------------------------------------") 62 | fmt.Println("total data is", counts) 63 | fmt.Println("----------------------------------------------------------") 64 | data2 := Student{} 65 | ret3 := c.Find(nil).Sort("name").Iter() 66 | for ret3.Next(&data2) { 67 | fmt.Printf("\nid %d Name %s\n", data2.Id, data2.Name) 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /Zap Logging/src/customencoder/README.md: -------------------------------------------------------------------------------- 1 | # Using custom encoders for standard fields 2 | 3 | You can use custom encoders for formatting time, level, caller, etc. One caveat 4 | is that you need these encoders to be as efficient as possible so as to not 5 | negate the memory/speed advantages of zap itself. After all, these functions 6 | are called for *every* line of log to be emitted! 7 | 8 | That said, the examples below are just a demonstration. I am not claiming at all 9 | that they are efficient replacements of standard functionality. :) 10 | 11 | ## Customizing timestamp formatting 12 | 13 | Here is an implementation which uses the syslog format often found in the wild. 14 | 15 | ```go 16 | func SyslogTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { 17 | enc.AppendString(t.Format("Jan 2 15:04:05")) 18 | } 19 | 20 | ... 21 | 22 | cfg.EncoderConfig.EncodeTime = SyslogTimeEncoder 23 | 24 | logger, _ = cfg.Build() 25 | logger.Info("This should have a syslog style timestamp") 26 | ``` 27 | 28 | Output: 29 | 30 | ``` 31 | May 2 18:54:55 INFO This should have a syslog style timestamp 32 | ``` 33 | 34 | If you noticed in the implementation that the encoder is supposed to append 35 | primitives to an array like object. zap uses this array to efficiently encode 36 | output with minimal memory allocations. 37 | 38 | ## Customizing level formatting 39 | 40 | ```go 41 | func CustomLevelEncoder(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) { 42 | enc.AppendString("[" + level.CapitalString() + "]") 43 | } 44 | ... 45 | cfg.EncoderConfig.EncodeLevel = CustomLevelEncoder 46 | 47 | logger, _ = cfg.Build() 48 | logger.Info("This should have a bracketed level name") 49 | ``` 50 | 51 | Output: 52 | 53 | ``` 54 | May 2 18:54:55 [INFO] This should have a bracketed level name 55 | ``` 56 | 57 | *NOTE*: I am creating a single string from multiple substrings and appending 58 | it to the array. For some reason, if I appended the substrings separately, zap 59 | is padding them with spaces. 60 | 61 | Similar customization can be done for other metadata fields as well. You can 62 | look [at the zap source](https://sourcegraph.com/github.com/uber-go/zap/-/blob/zapcore/encoder.go) 63 | to find the general pattern of these implementations. -------------------------------------------------------------------------------- /GoRoutines/buffered/main.go: -------------------------------------------------------------------------------- 1 | // This sample program demonstrates how to use a buffered 2 | // channel to work on multiple tasks with a predefined number 3 | // of goroutines. 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "log" 9 | "math/rand" 10 | "time" 11 | ) 12 | 13 | const ( 14 | numberGoroutines = 20 // Number of goroutines to use. 15 | taskLoad = 10 // Amount of work to process. 16 | ) 17 | 18 | 19 | // init is called to initialize the package by the 20 | // Go runtime prior to any other code being executed. 21 | func init() { 22 | // Seed the random number generator. 23 | rand.Seed(time.Now().Unix()) 24 | } 25 | 26 | // main is the entry point for all Go programs. 27 | func main() { 28 | // Create a buffered channel to manage the task load. 29 | tasks := make(chan string, taskLoad) 30 | // Launch goroutines to handle the work. 31 | wg.Add(numberGoroutines) 32 | for gr := 1; gr <= numberGoroutines; gr++ { 33 | go worker(tasks, gr) 34 | } 35 | // Add a bunch of work to get done. 36 | 37 | startTime := time.Now() 38 | for post := 1; post <= taskLoad; post++ { 39 | log.Printf("task: %+v", post) 40 | tasks <- fmt.Sprintf("Task : %d", post) 41 | } 42 | // Close the channel so the goroutines will quit 43 | // when all the work is done. 44 | close(tasks) 45 | // Wait for all the work to get done. 46 | wg.Wait() 47 | endTime := time.Now() 48 | 49 | log.Printf("time taken: %+v", endTime.Sub(startTime)) 50 | } 51 | 52 | // worker is launched as a goroutine to process work from 53 | // the buffered channel. 54 | func worker(tasks chan string, worker int) { 55 | // Report that we just returned. 56 | fmt.Printf("Worker: %d : Started \n", worker) 57 | defer wg.Done() 58 | for { 59 | // Wait for work to be assigned. 60 | task, ok := <-tasks 61 | if !ok { 62 | // This means the channel is empty and closed. 63 | fmt.Printf("Worker: %d : Shutting Down\n", worker) 64 | return 65 | } 66 | // Display we are starting the work. 67 | fmt.Printf("Worker: %d : Started %s\n", worker, task) 68 | // Randomly wait to simulate work time. 69 | sleep := rand.Int63n(100) 70 | time.Sleep(time.Duration(sleep) * time.Millisecond) 71 | // Display we finished the work. 72 | fmt.Printf("Worker: %d : Completed %s\n", worker, task) 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /MongoDB/person-collection.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // Crud operations with mongodb,restapi 4 | import ( 5 | "encoding/json" 6 | "fmt" 7 | "io/ioutil" 8 | 9 | // "log" 10 | "net/http" 11 | 12 | "gopkg.in/mgo.v2" 13 | "gopkg.in/mgo.v2/bson" 14 | ) 15 | 16 | type Person struct { 17 | ID bson.ObjectId `json:"id" bson:"_id,omitempty"` 18 | Ename string `json:"ename" bson: "ename"` 19 | Eid string `json:"eid" bson: "eid"` 20 | } 21 | 22 | func Insert(w http.ResponseWriter, r *http.Request) { 23 | session, _ := mgo.Dial("localhost:27017") 24 | person := Person{} 25 | 26 | reqBytes, _ := ioutil.ReadAll(r.Body) 27 | json.Unmarshal(reqBytes, &person) 28 | 29 | err := session.DB("employee").C("emp").Insert(&person) 30 | if err != nil { 31 | fmt.Println(err.Error()) 32 | } 33 | 34 | fmt.Println(person) 35 | fmt.Println("inserted") 36 | } 37 | 38 | func remove(res http.ResponseWriter, req *http.Request) { 39 | session, _ := mgo.Dial("localhost:27017") 40 | c := session.DB("employee").C("emp") 41 | 42 | _, err := c.RemoveAll(bson.M{}) 43 | if err != nil { 44 | panic(err) 45 | } else { 46 | fmt.Println("removed") 47 | } 48 | } 49 | 50 | func Update(res http.ResponseWriter, r *http.Request) { 51 | fmt.Println("entry") 52 | session, _ := mgo.Dial("localhost:27017") 53 | p1 := Person{} 54 | 55 | // params := context.Get(r, "params").(httprouter.Params) 56 | // id := params.ByName("5833e1a738eed2cc102e2f02") 57 | 58 | err := session.DB("employee").C("emp").Find(bson.M{"_id": bson.ObjectIdHex("5833e1a738eed2cc102e2f02")}).One(&p1) 59 | if err != nil { 60 | fmt.Println("id not fount", err.Error()) 61 | } 62 | 63 | bytes, _ := ioutil.ReadAll(r.Body) 64 | json.Unmarshal(bytes, &p1) 65 | 66 | err = session.DB("employee").C("emp").UpdateId(p1.ID, &p1) 67 | if err != nil { 68 | fmt.Println("cout't not update", err.Error()) 69 | } 70 | // err := c.Update(bson.M{"Eid": "A"}, bson.M{"$set": bson.M{"Ename": "avi"}}) 71 | // if err != nil { 72 | // fmt.Printf("err", err) 73 | // } else { 74 | fmt.Println("data's", p1) 75 | fmt.Printf("updated\n") 76 | } 77 | 78 | func main() { 79 | 80 | http.HandleFunc("/remove", remove) 81 | 82 | http.HandleFunc("/insert", Insert) 83 | http.HandleFunc("/update", Update) 84 | http.ListenAndServe(":8080", nil) 85 | 86 | } 87 | -------------------------------------------------------------------------------- /MongoDB/javascript.js: -------------------------------------------------------------------------------- 1 | db.getCollection('system.js').save( 2 | { 3 | _id: "makeSubcategoryName", 4 | value : function() { 5 | var totalAccounts = 0 6 | var totalStore = 0 7 | var totalSaleUpdate = 0 8 | var categoryMap = []; 9 | var totalCategory = 0 10 | 11 | db.account.find({}).forEach(function(account) { 12 | totalAccounts = totalAccounts + 1; 13 | db.store.find({"ownedBy":account._id}).forEach(function(store){ 14 | totalStore = totalStore + 1; 15 | db.category.find({ 16 | "ownedBy": account._id, 17 | "createdFor": store._id, 18 | "level": 1 19 | }).forEach(function(category){ 20 | categoryMap[category._id.toString()] = category.name 21 | totalCategory = totalCategory + 1 22 | }) 23 | 24 | db.sale.find({ 25 | "account": account._id, 26 | "store": store._id, 27 | "orders": { 28 | $elemMatch: { 29 | "subCategoryName": { 30 | $exists: false 31 | }, 32 | "categoryLevel": 2, 33 | } 34 | } 35 | }, { 36 | "_id": 1, 37 | "orders": 1 38 | }).forEach(function(sale){ 39 | for (var i in sale.orders) { 40 | sale.orders[i].subCategoryName = sale.orders[i].categoryName; 41 | catID = sale.orders[i].category; 42 | sale.orders[i].categoryName = categoryMap[catID]; 43 | db.sale.update(sale); 44 | totalSaleUpdate = totalSaleUpdate + 1 45 | } 46 | }) 47 | }) // store 48 | }) // account 49 | return { 50 | "totalAccounts":totalAccounts, 51 | "totalStore":totalStore, 52 | "totalCategory":totalCategory, 53 | "categoryMap":categoryMap, 54 | "totalSaleUpdate":totalSaleUpdate, 55 | } 56 | } 57 | }) -------------------------------------------------------------------------------- /gowiki/newwiki.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "html/template" 5 | "io/ioutil" 6 | "net/http" 7 | "regexp" 8 | ) 9 | 10 | type Page struct { 11 | Title string 12 | Body []byte 13 | } 14 | 15 | func (p *Page) save() error { 16 | filename := p.Title + ".txt" 17 | return ioutil.WriteFile(filename, p.Body, 0600) 18 | } 19 | 20 | func loadPage(title string) (*Page, error) { 21 | filename := title + ".txt" 22 | body, err := ioutil.ReadFile(filename) 23 | if err != nil { 24 | return nil, err 25 | } 26 | return &Page{Title: title, Body: body}, nil 27 | } 28 | 29 | func viewHandler(w http.ResponseWriter, r *http.Request, title string) { 30 | p, err := loadPage(title) 31 | if err != nil { 32 | http.Redirect(w, r, "/edit/"+title, http.StatusFound) 33 | return 34 | } 35 | renderTemplate(w, "view", p) 36 | } 37 | 38 | func editHandler(w http.ResponseWriter, r *http.Request, title string) { 39 | p, err := loadPage(title) 40 | if err != nil { 41 | p = &Page{Title: title} 42 | } 43 | renderTemplate(w, "edit", p) 44 | } 45 | 46 | func saveHandler(w http.ResponseWriter, r *http.Request, title string) { 47 | body := r.FormValue("body") 48 | p := &Page{Title: title, Body: []byte(body)} 49 | err := p.save() 50 | if err != nil { 51 | http.Error(w, err.Error(), http.StatusInternalServerError) 52 | return 53 | } 54 | http.Redirect(w, r, "/view/"+title, http.StatusFound) 55 | } 56 | 57 | var templates = template.Must(template.ParseFiles("edit.html", "view.html")) 58 | 59 | func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { 60 | err := templates.ExecuteTemplate(w, tmpl+".html", p) 61 | if err != nil { 62 | http.Error(w, err.Error(), http.StatusInternalServerError) 63 | } 64 | } 65 | 66 | var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$") 67 | 68 | func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc { 69 | return func(w http.ResponseWriter, r *http.Request) { 70 | m := validPath.FindStringSubmatch(r.URL.Path) 71 | if m == nil { 72 | http.NotFound(w, r) 73 | return 74 | } 75 | fn(w, r, m[2]) 76 | } 77 | } 78 | 79 | func main() { 80 | http.HandleFunc("/view/", makeHandler(viewHandler)) 81 | http.HandleFunc("/edit/", makeHandler(editHandler)) 82 | http.HandleFunc("/save/", makeHandler(saveHandler)) 83 | 84 | http.ListenAndServe(":8080", nil) 85 | } 86 | -------------------------------------------------------------------------------- /Proxy/reverseProxy.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/tls" 5 | "fmt" 6 | "log" 7 | "net/http" 8 | "net/http/httputil" 9 | "net/url" 10 | "runtime/debug" 11 | "strings" 12 | "time" 13 | ) 14 | 15 | func panicRecovery() { 16 | if err := recover(); err != nil { 17 | log.Printf("panic: %+v", err) 18 | debug.PrintStack() 19 | } 20 | } 21 | 22 | // RedirectToSubDomine redirects the request to sudomine server 23 | func RedirectToSubDomine(w http.ResponseWriter, r *http.Request) { 24 | defer panicRecovery() 25 | 26 | parts := strings.Split(r.Host, ".") 27 | if len(parts) != 3 { 28 | http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) 29 | return 30 | } 31 | 32 | targetURL := &url.URL{Scheme: "http", Host: "http:localhost:8080"} //cannonical name 33 | proxy := httputil.NewSingleHostReverseProxy(targetURL) 34 | proxy.ServeHTTP(w, r) 35 | } 36 | 37 | func redirectToSSLServer(w http.ResponseWriter, r *http.Request) { 38 | defer panicRecovery() 39 | 40 | parts := strings.Split(r.Host, ".") 41 | if len(parts) != 3 { 42 | http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) 43 | return 44 | } 45 | 46 | urlstr := fmt.Sprintf("https://%s%s", r.Host, r.URL.String()) 47 | http.Redirect(w, r, urlstr, http.StatusMovedPermanently) 48 | } 49 | 50 | func main() { 51 | mux := http.NewServeMux() 52 | mux.HandleFunc("/", redirectToSSLServer) 53 | server := http.Server{ 54 | Addr: ":9000", 55 | ReadTimeout: 200 * time.Second, 56 | WriteTimeout: 200 * time.Second, 57 | Handler: mux, 58 | } 59 | 60 | err := server.ListenAndServe() 61 | if err != nil { 62 | log.Printf("Error in proxy server: %+v", err.Error()) 63 | } 64 | 65 | defer server.Close() 66 | log.Printf("listerning on port : %s", server.Addr) 67 | go runSSlServer() 68 | } 69 | 70 | func runSSlServer() { 71 | sslmux := http.NewServeMux() 72 | sslmux.HandleFunc("/", RedirectToSubDomine) 73 | crtFile := "" 74 | keyFile := "" 75 | tlsconf := &tls.Config{ServerName: ""} 76 | sslServer := http.Server{ 77 | Addr: ":443", 78 | ReadTimeout: 200 * time.Second, 79 | WriteTimeout: 200 * time.Second, 80 | Handler: sslmux, 81 | TLSConfig: tlsconf, 82 | } 83 | 84 | log.Print("Listening on: 443") 85 | err := sslServer.ListenAndServeTLS(crtFile, keyFile) 86 | if err != nil { 87 | log.Printf("Error in running ssl proxy server: %s", err.Error()) 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Pool/main/pool_example.go: -------------------------------------------------------------------------------- 1 | // This sample program demonstrates how to use the pool package 2 | // to share a simulated set of database connections. 3 | package main 4 | 5 | import ( 6 | pool "golang-workspace/Pool" 7 | "io" 8 | "log" 9 | "math/rand" 10 | "sync" 11 | "sync/atomic" 12 | "time" 13 | ) 14 | 15 | const ( 16 | maxGoroutines = 5 // the number of routines to use. 17 | pooledResources = 2 // number of resources in the pool 18 | ) 19 | 20 | // dbConnection simulates a resource to share. 21 | type dbConnection struct { 22 | ID int32 23 | } 24 | 25 | // Close implements the io.Closer interface so dbConnection 26 | // can be managed by the pool. Close performs any resource 27 | // release management. 28 | func (dbConn *dbConnection) Close() error { 29 | log.Println("Close: Connection", dbConn.ID) 30 | return nil 31 | } 32 | 33 | // idCounter provides support for giving each connection a unique id. 34 | var idCounter int32 35 | 36 | // createConnection is a factory method that will be called by 37 | // the pool when a new connection is needed. 38 | func createConnection() (io.Closer, error) { 39 | id := atomic.AddInt32(&idCounter, 1) 40 | log.Println("Create: New Connection", id) 41 | return &dbConnection{id}, nil 42 | } 43 | 44 | // main is the entry point for all Go programs. 45 | func main() { 46 | var wg sync.WaitGroup 47 | wg.Add(maxGoroutines) 48 | 49 | // Create the pool to manage our connections. 50 | p, err := pool.New(createConnection, pooledResources) 51 | log.Println(p) 52 | if err != nil { 53 | log.Println(err) 54 | } 55 | 56 | // Perform queries using connections from the pool. 57 | for query := 0; query < maxGoroutines; query++ { 58 | 59 | // Each goroutine needs its own copy of the query 60 | // value else they will all be sharing the same query 61 | // variable. 62 | go func(q int) { 63 | performQueries(q, p) 64 | wg.Done() 65 | }(query) 66 | } 67 | 68 | // Wait for the goroutines to finish. 69 | wg.Wait() 70 | 71 | // Close the pool. 72 | log.Println("Shutdown Program.") 73 | p.Close() 74 | } 75 | 76 | // performQueries tests the resource pool of connections. 77 | func performQueries(query int, p *pool.Pool) { 78 | 79 | // Acquire a connection from the pool. 80 | conn, err := p.Acquire() 81 | if err != nil { 82 | log.Println(err) 83 | return 84 | } 85 | 86 | // Release the connection back to the pool. 87 | defer p.Release(conn) 88 | 89 | // Wait to simulate a query response. 90 | time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond) 91 | } 92 | -------------------------------------------------------------------------------- /DesignPatterns/Functional/Observer/main.go: -------------------------------------------------------------------------------- 1 | // This file provides an simple exmple of Observer pattern in Golang 2 | // source: https://github.com/tensor-programming/pattern-tutorial/blob/master/observer/main.go 3 | // This Logic is so worse. If you already no golang weel. dont look at this code. you will hate it. 4 | 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "sync" 10 | "time" 11 | ) 12 | 13 | type ( 14 | 15 | //Event that has to occur. 16 | Event struct { 17 | data int 18 | } 19 | 20 | // Observer observers an particular event 21 | Observer interface { 22 | NotifyCallback(Event) 23 | } 24 | 25 | // Subject can be any thing which has multiple events to occur. 26 | // example: a window which has events like 'open' and 'close' 27 | Subject interface { 28 | AddListener(Observer) 29 | RemoveListener(Observer) 30 | Notify(Event) 31 | } 32 | 33 | eventObserver struct { 34 | id int 35 | time time.Time 36 | } 37 | 38 | eventSubject struct { 39 | observers sync.Map 40 | } 41 | ) 42 | 43 | func (e *eventObserver) NotifyCallback(event Event) { 44 | fmt.Printf("Observer: %d Recieved: %d after %v\n", e.id, event.data, time.Since(e.time)) 45 | } 46 | 47 | func (s *eventSubject) AddListener(obs Observer) { 48 | s.observers.Store(obs, struct{}{}) 49 | } 50 | 51 | func (s *eventSubject) RemoveListener(obs Observer) { 52 | s.observers.Delete(obs) 53 | } 54 | 55 | func (s *eventSubject) Notify(event Event) { 56 | s.observers.Range(func(key interface{}, value interface{}) bool { 57 | if key == nil || value == nil { 58 | return false 59 | } 60 | 61 | key.(Observer).NotifyCallback(event) 62 | return true 63 | }) 64 | 65 | } 66 | 67 | func fib(n int) chan int { 68 | out := make(chan int) 69 | 70 | go func() { 71 | defer close(out) 72 | for i, j := 0, 1; i < n; i, j = i+j, i { 73 | out <- i 74 | } 75 | 76 | }() 77 | 78 | return out 79 | } 80 | 81 | // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... 82 | 83 | func main() { 84 | n := eventSubject{ 85 | observers: sync.Map{}, 86 | } 87 | 88 | t := time.Now() 89 | 90 | var obs1 = eventObserver{id: 1, time: t} 91 | var obs2 = eventObserver{id: 2, time: t} 92 | n.AddListener(&obs1) 93 | n.AddListener(&obs2) 94 | 95 | go func() { 96 | select { 97 | case <-time.After(time.Millisecond * 10): 98 | n.RemoveListener(&obs1) 99 | } 100 | }() 101 | 102 | for x := range fib(100000) { 103 | n.Notify(Event{data: x}) 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /Regex/gobrace.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // BUG(hariprasad): not working inside comments 4 | /* 5 | gobrace is a linting tool writern to format my go code. 6 | it will insert line break when it founds a brace followed by text in next line 7 | Example 8 | if all == "true" { 9 | baseQuery = allDimensionsQuery 10 | } 11 | res, err = d.DBr.Query(baseQuery, metricCode, accountID) 12 | 13 | 14 | the above code in the go file will be parsed and transformed into 15 | 16 | if all == "true" { 17 | baseQuery = allDimensionsQuery 18 | } 19 | 20 | res, err = d.DBr.Query(baseQuery, metricCode, accountID) 21 | */ 22 | import ( 23 | "flag" 24 | "fmt" 25 | "io/ioutil" 26 | "log" 27 | "os" 28 | "path/filepath" 29 | "regexp" 30 | "strings" 31 | ) 32 | 33 | func main() { 34 | var ( 35 | filename string 36 | dir string 37 | err error 38 | ) 39 | 40 | flag.StringVar(&filename, "f", "", "absolute file path which has to be linted") 41 | flag.StringVar(&dir, "d", "", "directory path where files has to be linted") 42 | flag.Parse() 43 | if flag.NFlag() != 1 { 44 | fmt.Fprintf(os.Stderr, "only one flag is allowed and must be set but got %v flags", flag.NFlag()) 45 | flag.Usage() 46 | os.Exit(1) 47 | } 48 | 49 | if dir != "" { 50 | err = filepath.Walk(dir, func(path string, file os.FileInfo, err error) error { 51 | if err != nil { 52 | return err 53 | } 54 | 55 | if !strings.Contains(path, "vendor") && strings.Contains(file.Name(), "go") { 56 | return updateFileWithRegex(path) 57 | } 58 | 59 | return nil 60 | }) 61 | } 62 | 63 | if filename != "" && strings.HasSuffix(filename, ".go") { 64 | err = updateFileWithRegex(filename) 65 | } 66 | 67 | if err != nil { 68 | log.Fatal(err) 69 | } 70 | } 71 | 72 | func updateFileWithRegex(filename string) error { 73 | exp, err := regexp.Compile("[^{]}\n.\\w+") 74 | if err != nil { 75 | return err 76 | } 77 | 78 | file, err := ioutil.ReadFile(filename) 79 | if err != nil { 80 | return err 81 | } 82 | 83 | data := exp.ReplaceAllFunc(file, func(line []byte) []byte { 84 | linestring := string(line) 85 | data := strings.SplitN(linestring, "}", 2) 86 | var newdata string 87 | for i, val := range data { 88 | newdata += val 89 | 90 | if i == 0 && strings.TrimSpace(val) != "" { 91 | newdata += "}" 92 | continue 93 | } 94 | 95 | if i == 0 { 96 | newdata += "}" + "\n" 97 | } 98 | } 99 | 100 | return []byte(newdata) 101 | }) 102 | 103 | ioutil.WriteFile(filename, data, os.ModePerm) 104 | return nil 105 | } 106 | -------------------------------------------------------------------------------- /DesignPatterns/Structural/Decorator/static-window.go: -------------------------------------------------------------------------------- 1 | package Design_Pattern 2 | 3 | import ( 4 | "errors" 5 | "log" 6 | ) 7 | 8 | type Window interface { 9 | // The interface defines the general window functionality 10 | paint() // client can make use of this functionality 11 | getInfo() 12 | } 13 | 14 | func (Win HorizontalScrollDecorator) paint() { 15 | log.Println(Win.Name + " has drawn") 16 | } 17 | 18 | func (Win HorizontalScrollDecorator) getInfo() { 19 | log.Println(Win.Name + " has description") 20 | } 21 | 22 | func (Win VerticalScrollDecorator) paint() { 23 | log.Println(Win.Name + " has drawn") 24 | } 25 | 26 | func (Win VerticalScrollDecorator) getInfo() { 27 | log.Println(Win.Name + " has description") 28 | } 29 | 30 | type HorizontalScrollDecorator struct { 31 | Name string 32 | Scrolling bool 33 | } 34 | 35 | type VerticalScrollDecorator struct { 36 | Name string 37 | Scrolling bool 38 | } 39 | 40 | type SimpleWindow struct { 41 | Name string 42 | } 43 | 44 | func (Win SimpleWindow) paint() { 45 | log.Println(Win.Name + " has drawn") 46 | } 47 | 48 | func (Win SimpleWindow) getInfo() { 49 | 50 | log.Println(Win.Name + " has description") 51 | } 52 | 53 | func (Vz VerticalScrollDecorator) Scroll() string { 54 | 55 | Vz.Scrolling = true 56 | return Vz.Name + " has vertical Scrolling" 57 | } 58 | 59 | func (Hz HorizontalScrollDecorator) Scroll() string { 60 | Hz.Scrolling = true 61 | return Hz.Name + " has horizontal Scrolling" 62 | } 63 | 64 | func CreateWindow(name string, scroll string) (Window Window, err error) { // returns an interface type window 65 | switch scroll { 66 | case "Horizontal": 67 | var Hz HorizontalScrollDecorator 68 | Hz.Name = name 69 | log.Println(Hz.Scroll()) // Dynamically adds functionality to the Horizontal window 70 | return Hz, err 71 | case "Vertical": 72 | var Vz VerticalScrollDecorator 73 | Vz.Name = name 74 | log.Println(Vz.Scroll()) // Dynamically adds functionality to Vertical window 75 | return Vz, err 76 | 77 | case "Simple": 78 | var simpleWindow SimpleWindow 79 | simpleWindow.Name = name 80 | return simpleWindow, err 81 | default: 82 | err = errors.New("Failed to Create Window :" + name) 83 | } 84 | return 85 | } 86 | 87 | func main() { 88 | window1, _ := CreateWindow("Window1", "Simple") 89 | window2, _ := CreateWindow("Horizontal", "Horizontal") 90 | window3, _ := CreateWindow("Vertical", "Vertical") 91 | 92 | window1.paint() 93 | window1.getInfo() 94 | 95 | window2.paint() 96 | window2.getInfo() 97 | 98 | window3.paint() 99 | window3.getInfo() 100 | 101 | } 102 | -------------------------------------------------------------------------------- /DesignPatterns/Structural/Decorator/dynamic-window.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "log" 4 | 5 | type Window interface { 6 | // The interface defines the general window functionality 7 | draw() // client can make use of this functionality 8 | getDescription() 9 | } 10 | 11 | type HorizontalScrollDecorator struct { 12 | Name string 13 | Scrolling bool 14 | Window *SimpleWindow 15 | } 16 | 17 | type VerticalScrollDecorator struct { 18 | Name string 19 | Scrolling bool 20 | Window *SimpleWindow 21 | } 22 | 23 | type SimpleWindow struct { 24 | Name string 25 | } 26 | 27 | func (Win SimpleWindow) draw() { 28 | log.Println(Win.Name + " has drawn") 29 | } 30 | 31 | func (Win SimpleWindow) getDescription() { 32 | 33 | log.Println(Win.Name + " has description") 34 | } 35 | 36 | func (Win HorizontalScrollDecorator) Scroll() string { 37 | Win.Scrolling = true 38 | return Win.Name + " has horizontal Scrolling" 39 | } 40 | 41 | func (Win VerticalScrollDecorator) Scroll() string { 42 | Win.Scrolling = true 43 | return Win.Name + " has vertical Scrolling" 44 | } 45 | 46 | func (Win HorizontalScrollDecorator) draw() { 47 | Win.Window.draw() 48 | log.Println(Win.Name + " has drawing") 49 | } 50 | 51 | func (Win VerticalScrollDecorator) draw() { 52 | Win.Window.draw() 53 | log.Println(Win.Name + " has drawing") 54 | } 55 | 56 | func (Win HorizontalScrollDecorator) getDescription() { 57 | Win.Window.getDescription() 58 | log.Println(Win.Name + " has description") 59 | } 60 | 61 | func (Win VerticalScrollDecorator) getDescription() { 62 | Win.Window.getDescription() 63 | log.Println(Win.Name + " has description") 64 | } 65 | 66 | func HorizontalScrollWindow(name string, window *SimpleWindow) Window { 67 | var horizontalWindow HorizontalScrollDecorator 68 | horizontalWindow.Name = "Horizontal Window" 69 | horizontalWindow.Scrolling = true 70 | horizontalWindow.Window = window 71 | log.Println(horizontalWindow.Scroll()) 72 | return horizontalWindow 73 | } 74 | 75 | func VerticalScrollWindow(name string, window *SimpleWindow) Window { 76 | var horizontalScrollWindow VerticalScrollDecorator 77 | horizontalScrollWindow.Name = "Vertical Window" 78 | horizontalScrollWindow.Scrolling = true 79 | horizontalScrollWindow.Window = window 80 | log.Println(horizontalScrollWindow.Scroll()) 81 | return horizontalScrollWindow 82 | } 83 | 84 | func main() { 85 | var simplewindow SimpleWindow 86 | simplewindow.Name = "Simple window" 87 | window1 := HorizontalScrollWindow("Window1", &simplewindow) 88 | window1.draw() 89 | window1.getDescription() 90 | 91 | window2 := VerticalScrollWindow("Window2", &simplewindow) 92 | window2.draw() 93 | window2.getDescription() 94 | } 95 | -------------------------------------------------------------------------------- /Cryptography/AES.go: -------------------------------------------------------------------------------- 1 | // Playbook - http://play.golang.org/p/3wFl4lacjX 2 | 3 | package main 4 | 5 | import ( 6 | "bytes" 7 | "crypto/aes" 8 | "crypto/cipher" 9 | "crypto/rand" 10 | "encoding/base64" 11 | "errors" 12 | "fmt" 13 | "io" 14 | "strings" 15 | ) 16 | 17 | func addBase64Padding(value string) string { 18 | m := len(value) % 4 19 | if m != 0 { 20 | value += strings.Repeat("=", 4-m) 21 | } 22 | 23 | return value 24 | } 25 | 26 | func removeBase64Padding(value string) string { 27 | return strings.Replace(value, "=", "", -1) 28 | } 29 | 30 | func Pad(src []byte) []byte { 31 | padding := aes.BlockSize - len(src)%aes.BlockSize 32 | padtext := bytes.Repeat([]byte{byte(padding)}, padding) 33 | return append(src, padtext...) 34 | } 35 | 36 | func Unpad(src []byte) ([]byte, error) { 37 | length := len(src) 38 | unpadding := int(src[length-1]) 39 | 40 | if unpadding > length { 41 | return nil, errors.New("unpad error. This could happen when incorrect encryption key is used") 42 | } 43 | 44 | return src[:(length - unpadding)], nil 45 | } 46 | 47 | func encryption(key []byte, text string) (string, error) { 48 | block, err := aes.NewCipher(key) 49 | if err != nil { 50 | return "", err 51 | } 52 | 53 | msg := Pad([]byte(text)) 54 | ciphertext := make([]byte, aes.BlockSize+len(msg)) 55 | iv := ciphertext[:aes.BlockSize] 56 | if _, err := io.ReadFull(rand.Reader, iv); err != nil { 57 | return "", err 58 | } 59 | 60 | cfb := cipher.NewCFBEncrypter(block, iv) 61 | cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(msg)) 62 | finalMsg := removeBase64Padding(base64.URLEncoding.EncodeToString(ciphertext)) 63 | return finalMsg, nil 64 | } 65 | 66 | func decryption(key []byte, text string) (string, error) { 67 | block, err := aes.NewCipher(key) 68 | if err != nil { 69 | return "", err 70 | } 71 | 72 | decodedMsg, err := base64.URLEncoding.DecodeString(addBase64Padding(text)) 73 | if err != nil { 74 | return "", err 75 | } 76 | 77 | if (len(decodedMsg) % aes.BlockSize) != 0 { 78 | return "", errors.New("blocksize must be multipe of decoded message length") 79 | } 80 | 81 | iv := decodedMsg[:aes.BlockSize] 82 | msg := decodedMsg[aes.BlockSize:] 83 | 84 | cfb := cipher.NewCFBDecrypter(block, iv) 85 | cfb.XORKeyStream(msg, msg) 86 | 87 | unpadMsg, err := Unpad(msg) 88 | if err != nil { 89 | return "", err 90 | } 91 | 92 | return string(unpadMsg), nil 93 | } 94 | 95 | func main() { 96 | key := []byte("LKHlhb899Y09olUi") 97 | encryptMsg, _ := encryption(key, "Hello World") 98 | msg, _ := decryption(key, encryptMsg) 99 | fmt.Println(msg) // Hello World 100 | } 101 | -------------------------------------------------------------------------------- /JWT/jwtSHA512.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/gorilla/securecookie" 8 | 9 | "github.com/dgrijalva/jwt-go" 10 | ) 11 | 12 | func main() { 13 | 14 | // ======== Sender =========== 15 | message := make(map[string]interface{}) 16 | message["World"] = "Hello" 17 | secretKey := securecookie.GenerateRandomKey(256) 18 | token := EncJWT256(message, secretKey) 19 | 20 | // ======== Reciver =========== 21 | claims, err := DecJWT256(token, secretKey) 22 | if err != nil { 23 | fmt.Printf("\n err :: %+v \n\n", err) 24 | } 25 | 26 | fmt.Printf("\n claims :: %+v \n\n", claims) 27 | 28 | } 29 | 30 | // EncJWT256 encrypts the message with the given secret key and returns the 'Json Web Token (JWT)' 31 | // secretkey lenght depends on the type of encryption algoritham. (i.e for HMAC512 the secret key length is 512 byte) 32 | // Example 33 | // message := make(map[string]interface{}) 34 | // message["World"] = "Hello" 35 | // secretKey := securecookie.GenerateRandomKey(256) 36 | // token := EncJWT256(message, secretKey) 37 | func EncJWT256(message map[string]interface{}, secretKey []byte) (JWTToken string) { 38 | 39 | // Token - JWT Header 40 | hmac512Algo := jwt.SigningMethodHS512.Alg() 41 | signingMethod := jwt.GetSigningMethod(hmac512Algo) 42 | token := jwt.New(signingMethod) 43 | 44 | // Claims - JWT Payload 45 | claims := make(jwt.MapClaims) 46 | for key, val := range message { 47 | claims[key] = val 48 | } 49 | 50 | token.Claims = claims 51 | 52 | // Signing and Serialization. 53 | tokenString, err := token.SignedString(secretKey) 54 | if err != nil { 55 | log.Print("Error: ", err) 56 | return 57 | } 58 | 59 | return tokenString 60 | } 61 | 62 | // DecJWT256 decrypts the Json Web Token using the secret key and returns the message 63 | // secretKey which given for encryption is must be given in params 64 | // Example 65 | // claims, err := DecJWT256(token, secretKey) 66 | // if err != nil { 67 | // fmt.Printf("\n err :: %+v \n\n", err) 68 | // } 69 | // 70 | // fmt.Printf("\n claims :: %+v \n\n", claims) 71 | func DecJWT256(tokenString string, secretKey []byte) (claims jwt.Claims, err error) { 72 | 73 | // Token received after Decrypting from token string and secret key. 74 | parsedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { 75 | if token.Method.Alg() != jwt.SigningMethodHS512.Alg() { 76 | return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) 77 | } 78 | 79 | return secretKey, nil 80 | }) 81 | 82 | if err != nil { 83 | return nil, err 84 | } 85 | 86 | if parsedToken.Valid { 87 | if claims, ok := parsedToken.Claims.(jwt.MapClaims); ok { 88 | return claims, nil 89 | } 90 | } 91 | 92 | return nil, fmt.Errorf("Error: %s \n", "failed to parse tokenString") 93 | } 94 | -------------------------------------------------------------------------------- /GoRoutines/runner/runner.go: -------------------------------------------------------------------------------- 1 | // Example provided with help from Gabriel Aszalos. 2 | // Package runner manages the running and lifetime of a process. 3 | package Runner 4 | 5 | import ( 6 | "errors" 7 | "os" 8 | "os/signal" 9 | "time" 10 | ) 11 | 12 | // Runner runs a set of tasks within a given timeout and can be 13 | // shut down on an operating system interrupt. 14 | type Runner struct { 15 | 16 | // interrupt channel reports a signal from the 17 | // operating system. 18 | interrupt chan os.Signal 19 | 20 | // complete channel reports that processing is done. 21 | complete chan error 22 | 23 | // timeout reports that time has run out. 24 | timeout <-chan time.Time 25 | 26 | // tasks holds a set of functions that are executed 27 | // synchronously in index order. 28 | tasks []func(int) 29 | } 30 | 31 | // ErrTimeout is returned when a value is received on the timeout. 32 | var ErrTimeout = errors.New("received timeout") 33 | 34 | // ErrInterrupt is returned when an event from the OS is received. 35 | var ErrInterrupt = errors.New("received interrupt") 36 | 37 | // New returns a new ready-to-use Runner. 38 | func New(d time.Duration) *Runner { 39 | return &Runner{ 40 | interrupt: make(chan os.Signal, 1), 41 | complete: make(chan error), 42 | timeout: time.After(d), 43 | } 44 | } 45 | 46 | // Add attaches tasks to the Runner. A task is a function that 47 | // takes an int ID. 48 | func (r *Runner) Add(tasks ...func(int)) { 49 | r.tasks = append(r.tasks, tasks...) 50 | } 51 | 52 | // Start runs all tasks and monitors channel events. 53 | func (r *Runner) Start() error { 54 | 55 | // We want to receive all interrupt based signals. 56 | signal.Notify(r.interrupt, os.Interrupt) 57 | 58 | // Run the different tasks on a different goroutine. 59 | go func() { 60 | r.complete <- r.run() 61 | }() 62 | 63 | select { 64 | 65 | // Signaled when processing is done. 66 | case err := <-r.complete: 67 | return err 68 | 69 | // Signaled when we run out of time. 70 | case <-r.timeout: 71 | return ErrTimeout 72 | } 73 | } 74 | 75 | // run executes each registered task. 76 | func (r *Runner) run() error { 77 | for id, task := range r.tasks { 78 | 79 | // Check for an interrupt signal from the OS. 80 | if r.gotInterrupt() { 81 | return ErrInterrupt 82 | } 83 | 84 | // Execute the registered task. 85 | go task(id) 86 | } 87 | return nil 88 | } 89 | 90 | // gotInterrupt verifies if the interrupt signal has been issued. 91 | func (r *Runner) gotInterrupt() bool { 92 | select { 93 | // Signaled when an interrupt event is sent. 94 | 95 | case <-r.interrupt: 96 | 97 | // Stop receiving any further signals. 98 | signal.Stop(r.interrupt) 99 | return true 100 | 101 | // Continue running as normal. 102 | default: 103 | return false 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /Pool/Pool.go: -------------------------------------------------------------------------------- 1 | package Pool 2 | 3 | import ( 4 | "errors" 5 | "io" 6 | "log" 7 | "sync" 8 | ) 9 | 10 | // Package pool manages a user defined set of resources. 11 | // Pool manages a set of resources that can be shared safely by 12 | // multiple goroutines. The resource being managed must implement 13 | // the io.Closer interface. 14 | type Pool struct { 15 | m sync.Mutex 16 | resources chan io.Closer 17 | factory func() (io.Closer, error) 18 | closed bool 19 | } 20 | 21 | // ErrPoolClosed is returned when an Acquire returns on a 22 | // closed pool. 23 | var ErrPoolClosed = errors.New("Pool has been closed.") 24 | 25 | // New creates a pool that manages resources. A pool requires a 26 | // function that can allocate a new resource and the size of 27 | // the pool. 28 | func New(fn func() (io.Closer, error), size uint) (*Pool, error) { 29 | if size <= 0 { 30 | return nil, errors.New("Size value too small.") 31 | } 32 | return &Pool{ 33 | factory: fn, 34 | resources: make(chan io.Closer, size), 35 | }, nil 36 | } 37 | 38 | // Acquire retrieves a resource from the pool. 39 | func (p *Pool) Acquire() (io.Closer, error) { 40 | select { 41 | 42 | // Check for a free resource. 43 | case r, ok := <-p.resources: 44 | log.Println("Acquire:", "Shared Resource") 45 | if !ok { 46 | return nil, ErrPoolClosed 47 | } 48 | return r, nil 49 | 50 | // Provide a new resource since there are none available. 51 | default: 52 | log.Println("Acquire:", "New Resource") 53 | return p.factory() 54 | } 55 | } 56 | 57 | // Release places a new resource onto the pool. 58 | func (p *Pool) Release(r io.Closer) { 59 | 60 | // Secure this operation with the Close operation. 61 | p.m.Lock() 62 | defer p.m.Unlock() 63 | 64 | // If the pool is closed, discard the resource. 65 | if p.closed { 66 | r.Close() 67 | return 68 | } 69 | select { 70 | 71 | // Attempt to place the new resource on the queue. 72 | case p.resources <- r: 73 | log.Println(<-p.resources) 74 | log.Println("Release:", "In Queue") 75 | 76 | // If the queue is already at capacity we close the resource. 77 | default: 78 | log.Println("Release:", "Closing") 79 | r.Close() 80 | } 81 | } 82 | 83 | // Close will shutdown the pool and close all existing resources. 84 | func (p *Pool) Close() { 85 | 86 | // Secure this operation with the Release operation. 87 | p.m.Lock() 88 | defer p.m.Unlock() 89 | 90 | // If the pool is already closed, don't do anything. 91 | if p.closed { 92 | return 93 | } 94 | 95 | // Set the pool as closed. 96 | p.closed = true 97 | 98 | // Close the channel before we drain the channel of its 99 | // resources. If we don't do this, we will have a deadlock. 100 | close(p.resources) 101 | 102 | // Close the resources 103 | for r := range p.resources { 104 | r.Close() 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /Protobuf/GoProtoServer/protoServer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/golang/protobuf/proto" 6 | "net" 7 | "os" 8 | 9 | "encoding/csv" 10 | "strconv" 11 | ) 12 | 13 | func main() { 14 | fmt.Printf("Started ProtoBuf Server") 15 | c := make(chan *ProtobufTest.TestMessage) 16 | go func() { 17 | for { 18 | message := <-c 19 | writeValuesTofile(message) 20 | 21 | } 22 | }() 23 | //Listen to the TCP port 24 | listener, err := net.Listen("tcp", "127.0.0.1:2110") 25 | checkError(err) 26 | for { 27 | if conn, err := listener.Accept(); err == nil { 28 | //If err is nil then that means that data is available for us so we take up this data and pass it to a new goroutine 29 | go handleProtoClient(conn, c) 30 | } else { 31 | continue 32 | } 33 | } 34 | } 35 | 36 | func handleProtoClient(conn net.Conn, c chan *ProtobufTest.TestMessage) { 37 | fmt.Println("Connection established") 38 | //Close the connection when the function exits 39 | defer conn.Close() 40 | //Create a data buffer of type byte slice with capacity of 4096 41 | data := make([]byte, 4096) 42 | //Read the data waiting on the connection and put it in the data buffer 43 | n, err := conn.Read(data) 44 | checkError(err) 45 | fmt.Println("Decoding Protobuf message") 46 | //Create an struct pointer of type ProtobufTest.TestMessage struct 47 | protodata := new(ProtobufTest.TestMessage) 48 | //Convert all the data retrieved into the ProtobufTest.TestMessage struct type 49 | err = proto.Unmarshal(data[0:n], protodata) 50 | checkError(err) 51 | //Push the protobuf message into a channel 52 | c <- protodata 53 | } 54 | 55 | func writeValuesTofile(datatowrite *ProtobufTest.TestMessage) { 56 | 57 | //Retreive client information from the protobuf message 58 | ClientName := datatowrite.GetClientName() 59 | ClientDescription := datatowrite.GetDescription() 60 | ClientID := strconv.Itoa(int(datatowrite.GetClientId())) 61 | 62 | // retrieve the message items list 63 | items := datatowrite.GetMessageitems() 64 | fmt.Println("Writing value to CSV file") 65 | //Open file for writes, if the file does not exist then create it 66 | file, err := os.OpenFile("CSVValues.csv", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) 67 | checkError(err) 68 | //make sure the file gets closed once the function exists 69 | defer file.Close() 70 | //Go through the list of message items, insert them into a string array then write them to the CSV file. 71 | writer := csv.NewWriter(file) 72 | for _, item := range items { 73 | record := []string{ClientID, ClientName, ClientDescription, strconv.Itoa(int(item.GetId())), item.GetItemName(), strconv.Itoa(int(item.GetItemValue())), strconv.Itoa(int(item.GetItemType()))} 74 | writer.Write(record) 75 | fmt.Println(record) 76 | } 77 | //flush data to the CSV file 78 | writer.Flush() 79 | fmt.Println("Finished Writing value to CSV file") 80 | } 81 | 82 | func checkError(err error) { 83 | if err != nil { 84 | fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) 85 | os.Exit(1) 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Zap Logging/src/customlogger/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "go.uber.org/zap/zapcore" 8 | 9 | "go.uber.org/zap" 10 | ) 11 | 12 | func main() { 13 | 14 | /* 15 | 16 | // This would cause a panic: "panic: no encoder name specified" 17 | 18 | cfg := zap.Config{} 19 | logger, err := cfg.Build() 20 | if err != nil { 21 | panic(err) 22 | } 23 | */ 24 | 25 | /* 26 | 27 | // causes a panic: "panic: runtime error: invalid memory address or nil pointer dereference" 28 | 29 | logger, err := zap.Config{Encoding: "json"}.Build() 30 | */ 31 | 32 | /* 33 | 34 | // No output 35 | 36 | logger, err := zap.Config{Encoding: "json", Level: zap.NewAtomicLevelAt(zapcore.InfoLevel)}.Build() 37 | 38 | */ 39 | 40 | fmt.Printf("\n*** Using a JSON encoder, at debug level, sending output to stdout, no key specified\n\n") 41 | 42 | logger, _ := zap.Config{ 43 | Encoding: "json", 44 | Level: zap.NewAtomicLevelAt(zapcore.DebugLevel), 45 | OutputPaths: []string{"stdout"}, 46 | }.Build() 47 | 48 | logger.Debug("This is a DEBUG message") 49 | logger.Info("This is an INFO message") 50 | logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) 51 | 52 | fmt.Printf("\n*** Using a JSON encoder, at debug level, sending output to stdout, message key only specified\n\n") 53 | 54 | logger, _ = zap.Config{ 55 | Encoding: "json", 56 | Level: zap.NewAtomicLevelAt(zapcore.DebugLevel), 57 | OutputPaths: []string{"stdout"}, 58 | EncoderConfig: zapcore.EncoderConfig{ 59 | MessageKey: "message", 60 | }, 61 | }.Build() 62 | 63 | logger.Debug("This is a DEBUG message") 64 | logger.Info("This is an INFO message") 65 | logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) 66 | 67 | fmt.Printf("\n*** Using a JSON encoder, at debug level, sending output to stdout, all possible keys specified\n\n") 68 | 69 | cfg := zap.Config{ 70 | Encoding: "json", 71 | Level: zap.NewAtomicLevelAt(zapcore.DebugLevel), 72 | OutputPaths: []string{"stderr"}, 73 | ErrorOutputPaths: []string{"stderr"}, 74 | EncoderConfig: zapcore.EncoderConfig{ 75 | MessageKey: "message", 76 | 77 | LevelKey: "level", 78 | EncodeLevel: zapcore.CapitalLevelEncoder, 79 | 80 | TimeKey: "time", 81 | EncodeTime: zapcore.ISO8601TimeEncoder, 82 | 83 | CallerKey: "caller", 84 | EncodeCaller: zapcore.ShortCallerEncoder, 85 | }, 86 | } 87 | logger, _ = cfg.Build() 88 | 89 | logger.Debug("This is a DEBUG message") 90 | logger.Info("This is an INFO message") 91 | logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) 92 | 93 | fmt.Printf("\n*** Same logger with console logging enabled instead\n\n") 94 | 95 | logger.WithOptions( 96 | zap.WrapCore( 97 | func(zapcore.Core) zapcore.Core { 98 | return zapcore.NewCore(zapcore.NewConsoleEncoder(cfg.EncoderConfig), zapcore.AddSync(os.Stderr), zapcore.DebugLevel) 99 | })).Info("This is an INFO message") 100 | } 101 | -------------------------------------------------------------------------------- /Money/money.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "math" 7 | "strconv" 8 | "strings" 9 | "unicode" 10 | ) 11 | 12 | type Options struct { 13 | DecimalDigits int8 `json:"decimalDigits"` 14 | ThousandSeparator string `json:"thousandSeparator"` 15 | DecimalSeparator string `json:"decimalSeparator"` 16 | CurrencySymbol string `json:"currencySymbol"` 17 | } 18 | 19 | //Money represents currency value as Integer 20 | type Money struct { 21 | value int 22 | options Options 23 | } 24 | 25 | func MakeFromString(s string, o Options) (Money, error) { 26 | isNegativeInt := strings.Contains(s, "-") 27 | m := Money{options: o} 28 | parts := strings.Split(s, o.DecimalSeparator) 29 | log.Println("parts", parts) 30 | var intstr, decstr string 31 | if len(parts) == 1 { 32 | } else if len(parts) == 2 { 33 | intstr = parts[0] 34 | decstr = parts[1] 35 | } else { 36 | return Money{}, fmt.Errorf("Cannot convert %s to money", s) 37 | } 38 | 39 | log.Println("intstr", intstr) 40 | log.Println("decstr", decstr) 41 | intstr = strings.Replace(intstr, o.ThousandSeparator, "", -1) 42 | intPart, err := strconv.Atoi(intstr) 43 | if err != nil { 44 | return Money{}, fmt.Errorf("Cannot convert %s to money", s) 45 | } 46 | 47 | if intPart < 0 { 48 | intPart = -1 * intPart 49 | } 50 | m.value = intPart * int(math.Pow10(int(o.DecimalDigits))) 51 | log.Println(int(math.Pow10(int(o.DecimalDigits)))) 52 | decval, err := makeDecPart(decstr, o.DecimalDigits) 53 | log.Println(" decval", decval) 54 | if err != nil { 55 | return Money{}, err 56 | } 57 | m.value += decval 58 | 59 | if isNegativeInt { 60 | m.value = -1 * m.value 61 | } 62 | return m, nil 63 | } 64 | func makeDecPart(s string, digits int8) (int, error) { 65 | 66 | var val int 67 | ds := strings.TrimSpace(s) 68 | log.Println("trim", ds) 69 | if len(ds) == 0 { 70 | return 0, nil 71 | } 72 | for i := 0; i < len(ds); i++ { 73 | if !unicode.IsDigit(rune(ds[i])) { 74 | return 0, fmt.Errorf("It is not unicode", ds) 75 | } 76 | log.Println("ds", i, ds[i]) 77 | digitstr := ds[i : i+1] 78 | dig, _ := strconv.Atoi(digitstr) 79 | log.Println("dig", dig) 80 | log.Println(int(digits - 1 - int8(i))) 81 | val += dig * int(math.Pow10(int(digits-1-int8(i)))) 82 | log.Println("val", val) 83 | if digits-1-int8(i) == 0 { 84 | //if next digit available then round and return else return val 85 | if i < len(ds)-1 { 86 | nextDig, err := strconv.Atoi(ds[i+1 : i+2]) 87 | if err != nil { 88 | return 0, fmt.Errorf("Cannot convert %s to decimal part of money", ds) 89 | } 90 | if nextDig >= 5 { 91 | val++ 92 | } 93 | } 94 | return val, nil 95 | } 96 | } 97 | return val, nil 98 | } 99 | 100 | func main() { 101 | money := "100,000.5555" 102 | a := 10 103 | log.Println(rune(a)) 104 | options := Options{DecimalDigits: 2, ThousandSeparator: ",", DecimalSeparator: ".", CurrencySymbol: "$"} 105 | data, err := MakeFromString(money, options) 106 | 107 | log.Println(data.value) 108 | //log.Println(data) 109 | log.Println(data) 110 | log.Println(err) 111 | } 112 | -------------------------------------------------------------------------------- /Protobuf/GoProtoClient/protoClient.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "Golang/Protobuf/ProtobufTest" 5 | "encoding/csv" 6 | "flag" 7 | "fmt" 8 | "io" 9 | "net" 10 | "os" 11 | "strconv" 12 | 13 | "github.com/golang/protobuf/proto" 14 | ) 15 | 16 | type Headers []string 17 | 18 | const CLIENT_NAME = "GoClient" 19 | const CLIENT_ID = 2 20 | const CLIENT_DESCRIPTION = "This is a Go Protobuf client!!" 21 | 22 | func main() { 23 | filename := flag.String("f", "/Users/hariprasad/go/src/Golang/Protobuf/GoProtoClient/CSVV.csv", "Enter the filename to read from") 24 | dest := flag.String("d", "127.0.0.1:2110", "Enter the destnation socket address") 25 | flag.Parse() 26 | data, err := retrieveDataFromFile(filename) 27 | checkError(err) 28 | sendDataToDest(data, dest) 29 | } 30 | 31 | func retrieveDataFromFile(fname *string) ([]byte, error) { 32 | file, err := os.Open(*fname) 33 | checkError(err) 34 | defer file.Close() 35 | 36 | csvreader := csv.NewReader(file) 37 | var hdrs Headers 38 | hdrs, err = csvreader.Read() 39 | checkError(err) 40 | ITEMIDINDEX := hdrs.getHeaderIndex("itemid") 41 | ITEMNAMEINDEX := hdrs.getHeaderIndex("itemname") 42 | ITEMVALUEINDEX := hdrs.getHeaderIndex("itemvalue") 43 | ITEMTYPEINDEX := hdrs.getHeaderIndex("itemType") 44 | 45 | ProtoMessage := new(ProtobufTest.TestMessage) 46 | ProtoMessage.ClientName = proto.String(CLIENT_NAME) 47 | ProtoMessage.ClientId = proto.Int32(CLIENT_ID) 48 | ProtoMessage.Description = proto.String(CLIENT_DESCRIPTION) 49 | 50 | //loop through the records 51 | for { 52 | record, err := csvreader.Read() 53 | if err != io.EOF { 54 | checkError(err) 55 | } else { 56 | 57 | break 58 | } 59 | //Populate items 60 | testMessageItem := new(ProtobufTest.TestMessage_MsgItem) 61 | itemid, err := strconv.Atoi(record[ITEMIDINDEX]) 62 | checkError(err) 63 | testMessageItem.Id = proto.Int32(int32(itemid)) 64 | testMessageItem.ItemName = &record[ITEMNAMEINDEX] 65 | itemvalue, err := strconv.Atoi(record[ITEMVALUEINDEX]) 66 | checkError(err) 67 | testMessageItem.ItemValue = proto.Int32(int32(itemvalue)) 68 | itemtype, err := strconv.Atoi(record[ITEMTYPEINDEX]) 69 | checkError(err) 70 | iType := ProtobufTest.TestMessage_ItemType(itemtype) 71 | testMessageItem.ItemType = &iType 72 | 73 | ProtoMessage.Messageitems = append(ProtoMessage.Messageitems, testMessageItem) 74 | 75 | fmt.Println(record) 76 | } 77 | 78 | //fmt.Println(ProtoMessage.Messageitems) 79 | return proto.Marshal(ProtoMessage) 80 | } 81 | 82 | func sendDataToDest(data []byte, dst *string) { 83 | conn, err := net.Dial("tcp", *dst) 84 | checkError(err) 85 | n, err := conn.Write(data) 86 | checkError(err) 87 | fmt.Println("Sent " + strconv.Itoa(n) + " bytes") 88 | } 89 | 90 | func checkError(err error) { 91 | if err != nil { 92 | fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) 93 | os.Exit(1) 94 | } 95 | } 96 | 97 | func (h Headers) getHeaderIndex(headername string) int { 98 | if len(headername) >= 2 { 99 | for index, s := range h { 100 | if s == headername { 101 | return index 102 | } 103 | } 104 | } 105 | return -1 106 | } 107 | -------------------------------------------------------------------------------- /Command/cmd/root.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2019 NAME HERE 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package cmd 17 | 18 | import ( 19 | "fmt" 20 | "os" 21 | "github.com/spf13/cobra" 22 | 23 | homedir "github.com/mitchellh/go-homedir" 24 | "github.com/spf13/viper" 25 | 26 | ) 27 | 28 | 29 | var cfgFile string 30 | 31 | 32 | // rootCmd represents the base command when called without any subcommands 33 | var rootCmd = &cobra.Command{ 34 | Use: "cobra-example", 35 | Short: "A brief description of your application", 36 | Long: `A longer description that spans multiple lines and likely contains 37 | examples and usage of using your application. For example: 38 | 39 | Cobra is a CLI library for Go that empowers applications. 40 | This application is a tool to generate the needed files 41 | to quickly create a Cobra application.`, 42 | // Uncomment the following line if your bare application 43 | // has an action associated with it: 44 | // Run: func(cmd *cobra.Command, args []string) { }, 45 | } 46 | 47 | // Execute adds all child commands to the root command and sets flags appropriately. 48 | // This is called by main.main(). It only needs to happen once to the rootCmd. 49 | func Execute() { 50 | if err := rootCmd.Execute(); err != nil { 51 | fmt.Println(err) 52 | os.Exit(1) 53 | } 54 | } 55 | 56 | func init() { 57 | cobra.OnInitialize(initConfig) 58 | 59 | // Here you will define your flags and configuration settings. 60 | // Cobra supports persistent flags, which, if defined here, 61 | // will be global for your application. 62 | 63 | rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra-example.yaml)") 64 | 65 | 66 | // Cobra also supports local flags, which will only run 67 | // when this action is called directly. 68 | rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 69 | } 70 | 71 | 72 | // initConfig reads in config file and ENV variables if set. 73 | func initConfig() { 74 | if cfgFile != "" { 75 | // Use config file from the flag. 76 | viper.SetConfigFile(cfgFile) 77 | } else { 78 | // Find home directory. 79 | home, err := homedir.Dir() 80 | if err != nil { 81 | fmt.Println(err) 82 | os.Exit(1) 83 | } 84 | 85 | // Search config in home directory with name ".cobra-example" (without extension). 86 | viper.AddConfigPath(home) 87 | viper.SetConfigName(".cobra-example") 88 | } 89 | 90 | viper.AutomaticEnv() // read in environment variables that match 91 | 92 | // If a config file is found, read it in. 93 | if err := viper.ReadInConfig(); err == nil { 94 | fmt.Println("Using config file:", viper.ConfigFileUsed()) 95 | } 96 | } 97 | 98 | -------------------------------------------------------------------------------- /MongoDB/crud.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "gopkg.in/mgo.v2" 6 | "gopkg.in/mgo.v2/bson" 7 | "os" 8 | ) 9 | 10 | /* Handling with Struct */ 11 | /* It will create a new document Collection*/ 12 | func Create(book interface{}, c *mgo.Collection) { 13 | fmt.Println("Create a book") 14 | c.Insert(book) 15 | 16 | } 17 | 18 | func Retrive(book interface{}, c *mgo.Collection) { 19 | // for Retriving all the elements 20 | fmt.Println("inside the Retrive method") 21 | var output interface{} 22 | // for Retriving only one element 23 | c.Find(bson.M{}).One(&output) 24 | fmt.Println(output) 25 | } 26 | func Update(book interface{}, c *mgo.Collection) { 27 | fmt.Println("Inside the update method") 28 | c.Update(bson.M{"description": "Building Scallable web apps with Restfull services"}, 29 | bson.M{"$set": bson.M{"description": "It is updated"}}) 30 | c.Find(bson.M{}).One(book) 31 | 32 | fmt.Println(book) 33 | } 34 | func Delete(book interface{}, c *mgo.Collection) { 35 | fmt.Println("Inside the delete") 36 | err := c.Remove(bson.M{"isbn": 7894651}) 37 | if err != nil { 38 | fmt.Printf("Error occurs", err) 39 | os.Exit(1) 40 | // we can use panic instead of os.Exit(1) 41 | fmt.Printf("Collection is deleted") 42 | } 43 | } 44 | func Retriveall(book interface{}, c *mgo.Collection) { 45 | var output []interface{} 46 | fmt.Println("Retrive all") 47 | c.Find(bson.M{}).All(&output) 48 | fmt.Println(output) 49 | } 50 | func Updateall(book interface{}, c *mgo.Collection) { 51 | fmt.Println("update all") 52 | c.UpdateAll(bson.M{"description": "Building Scallable web apps with Restfull services"}, 53 | bson.M{"$set": bson.M{"description": "It is updated"}}) 54 | 55 | } 56 | func Deleteall(book interface{}, c *mgo.Collection) { 57 | fmt.Println("Inside the remove all") 58 | c.RemoveAll(bson.M{}) 59 | fmt.Println("all docments are removed") 60 | } 61 | 62 | func Retriveonbyone(book interface{}, c *mgo.Collection) { 63 | fmt.Println("Inside the Retriveonbyone") 64 | var output interface{} 65 | iter := c.Find(bson.M{}).Iter() 66 | for iter.Next(&output) { 67 | fmt.Println("Document ---", output) 68 | 69 | } 70 | 71 | } 72 | 73 | /*---------------------------------------*/ 74 | /* Handling map functions*/ 75 | 76 | type Book struct { 77 | Title string 78 | Description string 79 | } 80 | 81 | func main() { 82 | session, error := mgo.Dial("localhost:27017") 83 | defer session.Close() 84 | if error != nil { 85 | panic("Error has been occured") 86 | } 87 | 88 | // to create an Collection 89 | 90 | bookstruct := &Book{Title: "Webdevelopment with go", 91 | Description: "Building Scallable web apps with Restfull services", 92 | Author: "Shiju Varghese", 93 | ISBN: 7894651} 94 | collection := session.DB("Library").C("Technology") 95 | fmt.Println(bookstruct) 96 | fmt.Println(collection) 97 | Create(bookstruct, collection) 98 | Retrive(bookstruct, collection) 99 | Update(bookstruct, collection) 100 | // Delete(bookstruct,collection) 101 | Retriveall(bookstruct, collection) 102 | Updateall(bookstruct, collection) 103 | // Deleteall(bookstruct,collection) 104 | Retriveonbyone(bookstruct, collection) 105 | bookmap := map[string]interface{}{"title": "Web development with go", 106 | "description": "Building Scallable web apps with Restfull services", 107 | "author": "Shiju Vargese", 108 | "isbn": 7894651} 109 | fmt.Println("Handling with maps") 110 | Create(bookmap, collection) 111 | Retrive(bookmap, collection) 112 | Update(bookmap, collection) 113 | // Delete(bookmap,collection) 114 | Retriveall(bookmap, collection) 115 | Updateall(bookmap, collection) 116 | // Deleteall(bookmap,collection) 117 | Retriveonbyone(bookmap, collection) 118 | 119 | } 120 | -------------------------------------------------------------------------------- /GoRoutines/unbuffered/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "sync" 7 | "time" 8 | ) 9 | 10 | // wg is used to wait for the program to finish. 11 | var wg sync.WaitGroup 12 | 13 | func init() { 14 | rand.Seed(time.Now().UnixNano()) 15 | } 16 | 17 | func main() { 18 | Tennis() 19 | // RunningRace() 20 | } 21 | 22 | //======================================================================================== 23 | /* * 24 | * RUNNING RACE * 25 | * */ 26 | //======================================================================================== 27 | 28 | func RunningRace() { 29 | 30 | // Create an unbuffered channel. 31 | baton := make(chan int) 32 | 33 | // Three palyers are running hence three go routines 34 | wg.Add(3) 35 | 36 | // First runner to his mark. 37 | go Runner(baton) 38 | 39 | // Start the race. 40 | baton <- 1 41 | 42 | // Wait for the race to finish. 43 | wg.Wait() 44 | } 45 | 46 | // Runner simulates a person running in the relay race. 47 | func Runner(baton chan int) { 48 | var newRunner int 49 | 50 | // Wait to receive the baton. 51 | runner := <-baton 52 | 53 | // Start running around the track. 54 | fmt.Printf("Runner %d Running With Baton\n", runner) 55 | 56 | // New runner to the line. 57 | if runner != 4 { 58 | newRunner = runner + 1 59 | fmt.Printf("Runner %d To The Line\n", newRunner) 60 | go Runner(baton) 61 | } 62 | 63 | // Running around the track. 64 | time.Sleep(100 * time.Millisecond) 65 | 66 | // Is the race over. 67 | if runner == 4 { 68 | fmt.Printf("Runner %d Finished, Race Over\n", runner) 69 | wg.Done() 70 | return 71 | } 72 | 73 | // Exchange the baton for the next runner. 74 | fmt.Printf( 75 | "Runner %d Exchange With Runner %d\n", 76 | runner, 77 | newRunner, 78 | ) 79 | 80 | baton <- newRunner 81 | wg.Done() 82 | } 83 | 84 | //======================================================================================== 85 | /* * 86 | * TENNIS GAME * 87 | * */ 88 | //======================================================================================== 89 | 90 | func Tennis() { 91 | 92 | // Create an unbuffered channel. 93 | court := make(chan int) 94 | 95 | // Add a count of two, one for each goroutine. 96 | wg.Add(2) 97 | 98 | // Launch two players. 99 | go player("Nadal", court) 100 | go player("Djokovic", court) 101 | 102 | // Start the set. 103 | court <- 1 104 | 105 | // Wait for the game to finish. 106 | wg.Wait() 107 | } 108 | 109 | // player simulates a person playing the game of tennis. 110 | func player(name string, court chan int) { 111 | defer wg.Done() 112 | for { 113 | 114 | // Wait for the ball to be hit back to us. 115 | ball, ok := <-court 116 | if !ok { 117 | 118 | // If the channel was closed we won. 119 | fmt.Printf("Player %s Won\n", name) 120 | return 121 | } 122 | 123 | // Pick a random number and see if we miss the ball. 124 | n := rand.Intn(100) 125 | if n%13 == 0 { 126 | fmt.Printf("Player %s Missed\n", name) 127 | close(court) 128 | return 129 | } 130 | 131 | // Display and then increment the hit count by one. 132 | fmt.Printf("Player %s Hit %d\n", name, ball) 133 | ball++ 134 | 135 | // Hit the ball back to the opposing player. 136 | court <- ball 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /gowiki/json.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "encoding/json" 4 | import "fmt" 5 | import "os" 6 | 7 | // We'll use these two structs to demonstrate encoding and 8 | // decoding of custom types below. 9 | type Response1 struct { 10 | Page int 11 | Fruits []string 12 | } 13 | type Response2 struct { 14 | Page int `json:"page"` 15 | Fruits []string `json:"fruits"` 16 | } 17 | 18 | func main() { 19 | 20 | // First we'll look at encoding basic data types to 21 | // JSON strings. Here are some examples for atomic 22 | // values. 23 | bolB, _ := json.Marshal(true) 24 | fmt.Println(string(bolB)) 25 | 26 | //testing boolean values 27 | 28 | a := false 29 | botot, _ := json.Marshal(a) 30 | fmt.Println(string(botot)) 31 | 32 | intB, _ := json.Marshal(1) 33 | fmt.Println(string(intB)) 34 | 35 | fltB, _ := json.Marshal(2.34) 36 | fmt.Println(string(fltB)) 37 | 38 | strB, _ := json.Marshal("gopher") 39 | fmt.Println(string(strB)) 40 | 41 | // And here are some for slices and maps, which encode 42 | // to JSON arrays and objects as you'd expect. 43 | slcD := []string{"apple", "peach", "pear"} 44 | slcB, _ := json.Marshal(slcD) 45 | fmt.Println(string(slcB)) 46 | 47 | mapD := map[string]int{"apple": 5, "lettuce": 7} 48 | mapB, _ := json.Marshal(mapD) 49 | fmt.Println(string(mapB)) 50 | 51 | // The JSON package can automatically encode your 52 | // custom data types. It will only include exported 53 | // fields in the encoded output and will by default 54 | // use those names as the JSON keys. 55 | res1D := &Response1{ 56 | Page: 1, 57 | Fruits: []string{"apple", "peach", "pear"}} 58 | res1B, _ := json.Marshal(res1D) 59 | fmt.Println(string(res1B)) 60 | 61 | // You can use tags on struct field declarations 62 | // to customize the encoded JSON key names. Check the 63 | // definition of `Response2` above to see an example 64 | // of such tags. 65 | res2D := &Response2{ 66 | Page: 1, 67 | Fruits: []string{"apple", "peach", "pear"}} 68 | res2B, _ := json.Marshal(res2D) 69 | fmt.Println(string(res2B)) 70 | 71 | // Now let's look at decoding JSON data into Go 72 | // values. Here's an example for a generic data 73 | // structure. 74 | byt := []byte(`{"num":6.13,"strs":["a","b"]}`) 75 | 76 | // We need to provide a variable where the JSON 77 | // package can put the decoded data. This 78 | // `map[string]interface{}` will hold a map of strings 79 | // to arbitrary data types. 80 | var dat map[string]interface{} 81 | 82 | // Here's the actual decoding, and a check for 83 | // associated errors. 84 | if err := json.Unmarshal(byt, &dat); err != nil { 85 | panic(err) 86 | } 87 | fmt.Println(dat) 88 | 89 | // In order to use the values in the decoded map, 90 | // we'll need to cast them to their appropriate type. 91 | // For example here we cast the value in `num` to 92 | // the expected `float64` type. 93 | num := dat["num"].(float64) 94 | fmt.Println(num) 95 | 96 | // Accessing nested data requires a series of 97 | // casts. 98 | strs := dat["strs"].([]interface{}) 99 | str1 := strs[0].(string) 100 | fmt.Println(str1) 101 | 102 | // We can also decode JSON into custom data types. 103 | // This has the advantages of adding additional 104 | // type-safety to our programs and eliminating the 105 | // need for type assertions when accessing the decoded 106 | // data. 107 | str := `{"page": 1, "fruits": ["apple", "peach"]}` 108 | res := Response2{} 109 | json.Unmarshal([]byte(str), &res) 110 | fmt.Println(res) 111 | fmt.Println(res.Fruits[0]) 112 | 113 | // In the examples above we always used bytes and 114 | // strings as intermediates between the data and 115 | // JSON representation on standard out. We can also 116 | // stream JSON encodings directly to `os.Writer`s like 117 | // `os.Stdout` or even HTTP response bodies. 118 | enc := json.NewEncoder(os.Stdout) 119 | d := map[string]int{"apple": 5, "lettuce": 7} 120 | enc.Encode(d) 121 | } 122 | -------------------------------------------------------------------------------- /gowiki/wiki.go: -------------------------------------------------------------------------------- 1 | package main 2 | import ( 3 | //"fmt" 4 | "io/ioutil" 5 | "net/http" 6 | "html/template" 7 | "fmt" 8 | "log" 9 | "regexp" 10 | 11 | "github.com/stretchr/testify/http" 12 | ) 13 | 14 | /* Creating a file ,updating and displaying text inside the file */ 15 | func init() { 16 | log.SetFlags(log.LstdFlags|log.Lshortfile) 17 | } 18 | type Page struct { 19 | 20 | Title string 21 | Body []byte 22 | } 23 | 24 | func (p *Page) save() error { 25 | 26 | filename:= p.Title + ".txt" 27 | return ioutil.WriteFile(filename,p.Body,0600) 28 | 29 | } 30 | 31 | func loadPage(title string) (*Page,error){ 32 | filename := title + ".txt" 33 | body,err := ioutil.ReadFile(filename) 34 | if err != nil { 35 | return nil,err 36 | } 37 | return &Page{Title: title, Body: body},nil 38 | } 39 | 40 | func main() { 41 | // p1:= &Page{Title: "TestPage",Body: []byte("This is the sample page")} 42 | // p1.save() 43 | // p2,_ := loadPage("TestPage") 44 | // fmt.Println(string(p2.Body)) 45 | // http.HandleFunc("/",handler) 46 | // http.ListenAndServe(":8080",nil) 47 | var template = template.Must(template.ParseFiles("edit.html","view.html")) 48 | var validpath = regexp.MustCompile("^/(edit|save|view)/([a-ZA-Z0-9]+)$") 49 | http.HandleFunc("/view/", makeHandler(viewHandler)) 50 | http.HandleFunc("/edit/", makeHandler(editHandler)) 51 | http.HandleFunc("/save/" ,makeHandler(saveHandler)) 52 | error:=http.ListenAndServe(":8080",nil) 53 | log.Println(error) 54 | } 55 | func handler(w http.ResponseWriter, r *http.Request) { 56 | fmt.Fprintf(w,"Hi, there, I love %s!", r.URL.Path[1:]) 57 | fmt.Println("Inside the println") 58 | } 59 | func viewHandler(w http.ResponseWriter, r *http.Request, title string) { 60 | title:= r.URL.Path[len("/view/"):] 61 | p,err := loadPage(title) 62 | if err != nil { 63 | http.Redirect(w, r, "/edit/"+title, http.StatusFound) 64 | return 65 | } 66 | 67 | renderTemplate(w,"view",p) 68 | 69 | } 70 | 71 | // fmt.Fprintf(w,"

%s

%s
", p.Title,p.Body) 72 | // } 73 | func editHandler(w http.ResponseWriter, r *http.Request, title string) { 74 | // title := r.URL.Path[len("/edit/"):] 75 | title,err := getTitle(w,r) 76 | if err != nil { 77 | return 78 | } 79 | p, err := loadPage(title) 80 | if err != nil { 81 | p = &Page{Title: title,} 82 | } 83 | // t, _ := template.ParseFiles("edit.html") 84 | // t.Execute(w, p) 85 | renderTemplate(w,"edit",p) 86 | } 87 | 88 | func renderTemplate(w http.ResponseWriter, tmpl string,p *Page) { 89 | t,err:= template.ExceuteTemplate(w,tmpl+".html",p) 90 | if err != nil { 91 | http.Error(w, err.Error(), http.StatusInternalServerError) 92 | return 93 | } 94 | err = t.Execute(w,p) 95 | if err != nil { 96 | http.Error(w.err.Error(), http.StatusInternalServerError) 97 | } 98 | 99 | 100 | } 101 | func saveHandler(w http.ResponseWriter,r *http.Request, title string) { 102 | title,err := getTitle(w,r) 103 | if err!=nil { 104 | return 105 | } 106 | body := r.FormValue("body") 107 | p := &Page{Title: title, Body: []byte(body)} 108 | err :=p.save() 109 | if err != nil { 110 | http.Error(w,err.Error().http.StatusInternalServerError) 111 | return 112 | } 113 | http.Redirect(w,r,"/view/"+ title,http.StatusFound) 114 | } 115 | func getTitle(w http.ResponseWriter,r *http.Request) (string,error){ 116 | m := validPath.FindStringSubmatch(r.URL.Path) 117 | if m == nil { 118 | http.NotFound(w,r) 119 | retrun "", errors.New("Invalid Page Title") 120 | } 121 | retrun m[2],nil 122 | } 123 | 124 | fun makeHandler(fn func(http.ResponseWriter,*http.Request, title string)) http.HandleFunc { 125 | return func(w http.ResponseWriter,r *http.Request) { 126 | m := validPath.FindStringSubmatch(r.url.Path) 127 | if m == nil { 128 | http.NotFound(w,r) 129 | return 130 | } 131 | fn(w,r,m[2]) 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /File/fileCache.go: -------------------------------------------------------------------------------- 1 | // file system cache implementation in Golang 2 | package main 3 | 4 | import ( 5 | "encoding/json" 6 | "errors" 7 | "io" 8 | "log" 9 | "os" 10 | "path/filepath" 11 | "regexp" 12 | "strconv" 13 | "strings" 14 | "sync" 15 | "time" 16 | ) 17 | 18 | var currentDir, _ = os.Getwd() 19 | 20 | const ( 21 | cache_dir = "/tmp" // Cache directory 22 | expire = 8 * time.Hour // Hours to keep the cache 23 | ) 24 | 25 | func Set(k *Key, data interface{}) error { 26 | t1 := time.Now() 27 | err := k.validate() 28 | if err != nil { 29 | return err 30 | } 31 | 32 | val, err := json.Marshal(&data) 33 | if err != nil { 34 | return err 35 | } 36 | 37 | key := regexp.MustCompile("[^a-zA-Z0-9_-]").ReplaceAllLiteralString(k.String(), "") 38 | clean(key) 39 | 40 | file := "filecache." + key + "." + strconv.FormatInt(time.Now().Add(expire).Unix(), 10) 41 | fpath := filepath.Join(currentDir+cache_dir, file) 42 | 43 | var fmutex sync.RWMutex 44 | fmutex.Lock() 45 | fp, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600) 46 | if err != nil { 47 | return err 48 | 49 | } 50 | 51 | defer fp.Close() 52 | if _, err = fp.Write(val); err != nil { 53 | return err 54 | } 55 | 56 | defer fmutex.Unlock() 57 | t2 := time.Now() 58 | log.Println("Set filecache: ", key, " : ", t2.Sub(t1)) 59 | 60 | return nil 61 | } 62 | 63 | func Get(k *Key, dst interface{}) error { 64 | t := time.Now() 65 | key := regexp.MustCompile("[^a-zA-Z0-9_-]").ReplaceAllLiteralString(k.String(), "") 66 | pattern := filepath.Join(currentDir+cache_dir, "filecache."+key+".*") 67 | files, err := filepath.Glob(pattern) 68 | if len(files) < 1 || err != nil { 69 | return errors.New("filecache: no cache file found") 70 | } 71 | 72 | if _, err = os.Stat(files[0]); err != nil { 73 | return err 74 | } 75 | 76 | fp, err := os.OpenFile(files[0], os.O_RDONLY, 0400) 77 | if err != nil { 78 | return err 79 | } 80 | defer fp.Close() 81 | 82 | var serialized []byte 83 | buf := make([]byte, 1024) 84 | for { 85 | var n int 86 | n, err = fp.Read(buf) 87 | serialized = append(serialized, buf[0:n]...) 88 | if err != nil || err == io.EOF { 89 | break 90 | } 91 | } 92 | if err = json.Unmarshal(serialized, &dst); err != nil { 93 | return err 94 | } 95 | 96 | for _, file := range files { 97 | exptime, err := strconv.ParseInt(strings.Split(file, ".")[2], 10, 64) 98 | if err != nil { 99 | return err 100 | } 101 | 102 | if exptime < time.Now().Unix() { 103 | if _, err = os.Stat(file); err == nil { 104 | os.Remove(file) 105 | } 106 | } 107 | } 108 | 109 | log.Println("Get filecache: ", key, " : ", time.Since(t)) 110 | return nil 111 | } 112 | 113 | func clean(key string) { 114 | pattern := filepath.Join(currentDir+cache_dir, "filecache."+key+".*") 115 | log.Print(pattern) 116 | files, _ := filepath.Glob(pattern) 117 | for _, file := range files { 118 | if _, err := os.Stat(file); err == nil { 119 | os.Remove(file) 120 | } 121 | } 122 | } 123 | 124 | type Key struct { 125 | Collection string 126 | Id string 127 | } 128 | 129 | // Stringify the Key 130 | func (k *Key) String() string { 131 | data = k.Collection + "_" + k.Id.Hex() + data 132 | return data 133 | } 134 | 135 | func (k *Key) validate() error { 136 | return nil 137 | } 138 | 139 | func main() { 140 | var customer = map[string]interface{}{ 141 | "name": "customer 1", 142 | "firstName": "", 143 | "lastName": "", 144 | "gender": "", 145 | "imageAvailable": false, 146 | "imageVersion": 0, 147 | "gateCode": "" 148 | } 149 | 150 | key := Key{ 151 | Collection: "customer", // Set DB collection name 152 | Id: "5936895978362e42ac5e02ca", 153 | } 154 | 155 | err := Set(&key, &customer) 156 | if err != nil { 157 | log.Print("error:", err) 158 | } 159 | 160 | var data interface{} 161 | err = Get(&key, &data) 162 | if err != nil { 163 | log.Print("Error", err) 164 | } 165 | 166 | log.Print(data) 167 | 168 | } 169 | -------------------------------------------------------------------------------- /Interpreter/interpreter.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | /* file : interpreter.go 5 | /* author : hariprasad 6 | /* date : 3 June 2018 7 | /* last : 3 June 2018 8 | /* this file contains the goalng implementation of Interpreter. 9 | It is writtern based on the example provided. in the site: https://ruslanspivak.com/lsbasi-part1/ 10 | */ 11 | 12 | import ( 13 | "fmt" 14 | "strconv" 15 | ) 16 | 17 | // TokenType defines the Tokens 18 | type TokenType string 19 | 20 | const ( 21 | // INTEGER Data type 22 | INTEGER TokenType = "INTEGER" 23 | 24 | // PLUS operator 25 | PLUS TokenType = "PLUS" 26 | 27 | // EOF (end-of-file) token is used to indicate that 28 | // there is no more input left for lexical analysis 29 | EOF TokenType = "EOF" 30 | ) 31 | 32 | // Token is a lexical values 33 | type Token struct { 34 | Type TokenType 35 | Value string 36 | } 37 | 38 | //Interpreter does Interpretation for the text. 39 | type Interpreter struct { 40 | text string 41 | position int 42 | currentToken *Token 43 | } 44 | 45 | // expr -> INTEGER PLUS INTEGER 46 | func (i *Interpreter) expr() string { 47 | 48 | // set current token to the first token taken from the input 49 | i.currentToken = i.getNextToken() 50 | 51 | // we expect the current token to be a single-digit integer 52 | left := i.currentToken 53 | i.eat(INTEGER) 54 | 55 | // we expect the current token to be a '+' token 56 | op := i.currentToken 57 | i.eat(PLUS) 58 | 59 | // we expect the current token to be a single-digit integer 60 | right := i.currentToken 61 | i.eat(INTEGER) 62 | 63 | // after the above call the self.current_token is set to 64 | // EOF token 65 | // at this point INTEGER PLUS INTEGER sequence of tokens 66 | // has been successfully found and the method can just 67 | // return the result of adding two integers, thus 68 | // effectively interpreting client input 69 | var lValue, rValue, result int 70 | if left.Type == INTEGER { 71 | lValue, _ = strconv.Atoi(left.Value) 72 | } 73 | 74 | if left.Type == INTEGER { 75 | rValue, _ = strconv.Atoi(right.Value) 76 | } 77 | 78 | if op.Value == "+" { 79 | result = lValue + rValue 80 | } 81 | 82 | return strconv.Itoa(result) 83 | } 84 | 85 | // Lexical analyzer (also known as scanner or tokenizer) 86 | // This method is responsible for breaking a sentence 87 | // apart into tokens. One token at a time. 88 | func (i *Interpreter) getNextToken() *Token { 89 | text := i.text 90 | 91 | // is self.pos index past the end of the self.text ? 92 | // if so, then return EOF token because there is no more 93 | // input left to convert into tokens 94 | if i.position > (len(text) - 1) { 95 | return &Token{Type: "EOF", Value: ""} 96 | } 97 | 98 | // get a character at the position self.pos and decide 99 | // what token to create based on the single character 100 | currentChar := text[i.position] 101 | if currentChar == '+' { 102 | token := &Token{Type: "PLUS", Value: string(currentChar)} 103 | i.position++ 104 | return token 105 | } 106 | 107 | // if the character is a digit then convert it to 108 | // integer, create an INTEGER token, increment self.pos 109 | // index to point to the next character after the digit, 110 | // and return the INTEGER token 111 | if string(currentChar) != "" { 112 | token := &Token{Type: "INTEGER", Value: string(currentChar)} 113 | i.position++ 114 | return token 115 | } 116 | 117 | return nil 118 | } 119 | 120 | func (i *Interpreter) eat(tokenType TokenType) { 121 | // compare the current token type with the passed token 122 | // type and if they match then "eat" the current token 123 | // and assign the next token to the self.current_token, 124 | // otherwise raise an exception. 125 | if i.currentToken.Type == tokenType { 126 | i.currentToken = i.getNextToken() 127 | } 128 | } 129 | 130 | func main() { 131 | 132 | text := "3+4" 133 | fmt.Print("Enter the expression ,eg: 3+4\n") 134 | fmt.Scan(&text) 135 | 136 | interpreter := &Interpreter{ 137 | text: text, 138 | } 139 | 140 | result := interpreter.expr() 141 | fmt.Print("Result: ", result, "\n") 142 | } 143 | -------------------------------------------------------------------------------- /Zap Logging/src/simple1/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "time" 7 | 8 | "go.uber.org/zap" 9 | ) 10 | 11 | func main() { 12 | fmt.Printf("\n*** Using the Example logger\n\n") 13 | 14 | logger := zap.NewExample() 15 | logger.Debug("This is a DEBUG message") 16 | logger.Info("This is an INFO message") 17 | logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) 18 | logger.Warn("This is a WARN message") 19 | logger.Error("This is an ERROR message") 20 | // logger.Fatal("This is a FATAL message") // would exit if uncommented 21 | logger.DPanic("This is a DPANIC message") 22 | //logger.Panic("This is a PANIC message") // would exit if uncommented 23 | 24 | fmt.Println() 25 | 26 | fmt.Printf("*** Using the Development logger\n\n") 27 | 28 | logger, _ = zap.NewDevelopment() 29 | logger.Debug("This is a DEBUG message") 30 | logger.Info("This is an INFO message") 31 | logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) 32 | logger.Warn("This is a WARN message") 33 | logger.Error("This is an ERROR message") 34 | // logger.Fatal("This is a FATAL message") // would exit if uncommented 35 | // logger.DPanic("This is a DPANIC message") // would exit if uncommented 36 | //logger.Panic("This is a PANIC message") // would exit if uncommented 37 | 38 | fmt.Println() 39 | 40 | fmt.Printf("*** Using the Production logger\n\n") 41 | 42 | logger, _ = zap.NewProduction() 43 | logger.Debug("This is a DEBUG message") 44 | logger.Info("This is an INFO message") 45 | logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) 46 | logger.Warn("This is a WARN message") 47 | logger.Error("This is an ERROR message") 48 | // logger.Fatal("This is a FATAL message") // would exit if uncommented 49 | logger.DPanic("This is a DPANIC message") 50 | // logger.Panic("This is a PANIC message") // would exit if uncommented 51 | 52 | fmt.Println() 53 | 54 | fmt.Printf("*** Using the Sugar logger\n\n") 55 | 56 | logger, _ = zap.NewDevelopment() 57 | slogger := logger.Sugar() 58 | slogger.Info("Info() uses sprint") 59 | slogger.Infof("Infof() uses %s", "sprintf") 60 | slogger.Infow("Infow() allows tags", "name", "Legolas", "type", 1) 61 | 62 | fmt.Println("*** Build a logger from a json ****") 63 | 64 | rawJSONConfig := []byte(`{ 65 | "level": "info", 66 | "encoding": "console", 67 | "outputPaths": ["stdout", "/tmp/logs"], 68 | "errorOutputPaths": ["/tmp/errorlogs"], 69 | "initialFields": {"initFieldKey": "fieldValue"}, 70 | "encoderConfig": { 71 | "messageKey": "message", 72 | "levelKey": "level", 73 | "nameKey": "logger", 74 | "timeKey": "time", 75 | "callerKey": "logger", 76 | "stacktraceKey": "stacktrace", 77 | "callstackKey": "callstack", 78 | "errorKey": "error", 79 | "timeEncoder": "iso8601", 80 | "fileKey": "file", 81 | "levelEncoder": "capitalColor", 82 | "durationEncoder": "second", 83 | "callerEncoder": "full", 84 | "nameEncoder": "full", 85 | "sampling": { 86 | "initial": "3", 87 | "thereafter": "10" 88 | } 89 | } 90 | }`) 91 | 92 | config := zap.Config{} 93 | if err := json.Unmarshal(rawJSONConfig, &config); err != nil { 94 | panic(err) 95 | } 96 | logger, err := config.Build() 97 | if err != nil { 98 | panic(err) 99 | } 100 | 101 | logger.Debug("This is a DEBUG message") 102 | logger.Info("This should have an ISO8601 based time stamp") 103 | logger.Warn("This is a WARN message") 104 | logger.Error("This is an ERROR message") 105 | //logger.Fatal("This is a FATAL message") // would exit if uncommented 106 | //logger.DPanic("This is a DPANIC message") // would exit if uncommented 107 | 108 | const url = "http://example.com" 109 | logger.Info("Failed to fetch URL.", 110 | // Structured context as strongly typed fields. 111 | zap.String("url", url), 112 | zap.Int("attempt", 3), 113 | zap.Duration("backoff", time.Second)) 114 | // {"level":"info","msg":"Failed to fetch URL.","url":"http://example.com","attempt":3,"backoff":"1"} 115 | 116 | } 117 | -------------------------------------------------------------------------------- /Protobuf/ProtobufTest/ProtoTest.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. 2 | // source: ProtobufTest.proto 3 | // DO NOT EDIT! 4 | 5 | /* 6 | Package ProtobufTest is a generated protocol buffer package. 7 | 8 | It is generated from these files: 9 | ProtobufTest.proto 10 | 11 | It has these top-level messages: 12 | TestMessage 13 | */ 14 | package ProtobufTest 15 | 16 | import proto "github.com/golang/protobuf/proto" 17 | import math "math" 18 | 19 | // Reference imports to suppress errors if they are not otherwise used. 20 | var _ = proto.Marshal 21 | var _ = math.Inf 22 | 23 | type TestMessage_ItemType int32 24 | 25 | const ( 26 | TestMessage_TypeX TestMessage_ItemType = 0 27 | TestMessage_TypeY TestMessage_ItemType = 1 28 | TestMessage_TypeZ TestMessage_ItemType = 2 29 | ) 30 | 31 | var TestMessage_ItemType_name = map[int32]string{ 32 | 0: "TypeX", 33 | 1: "TypeY", 34 | 2: "TypeZ", 35 | } 36 | var TestMessage_ItemType_value = map[string]int32{ 37 | "TypeX": 0, 38 | "TypeY": 1, 39 | "TypeZ": 2, 40 | } 41 | 42 | func (x TestMessage_ItemType) Enum() *TestMessage_ItemType { 43 | p := new(TestMessage_ItemType) 44 | *p = x 45 | return p 46 | } 47 | func (x TestMessage_ItemType) String() string { 48 | return proto.EnumName(TestMessage_ItemType_name, int32(x)) 49 | } 50 | func (x *TestMessage_ItemType) UnmarshalJSON(data []byte) error { 51 | value, err := proto.UnmarshalJSONEnum(TestMessage_ItemType_value, data, "TestMessage_ItemType") 52 | if err != nil { 53 | return err 54 | } 55 | *x = TestMessage_ItemType(value) 56 | return nil 57 | } 58 | 59 | type TestMessage struct { 60 | ClientName *string `protobuf:"bytes,1,req,name=clientName" json:"clientName,omitempty"` 61 | ClientId *int32 `protobuf:"varint,2,req,name=clientId" json:"clientId,omitempty"` 62 | Description *string `protobuf:"bytes,3,opt,name=description,def=NONE" json:"description,omitempty"` 63 | Messageitems []*TestMessage_MsgItem `protobuf:"bytes,4,rep,name=messageitems" json:"messageitems,omitempty"` 64 | XXX_unrecognized []byte `json:"-"` 65 | } 66 | 67 | func (m *TestMessage) Reset() { *m = TestMessage{} } 68 | func (m *TestMessage) String() string { return proto.CompactTextString(m) } 69 | func (*TestMessage) ProtoMessage() {} 70 | 71 | const Default_TestMessage_Description string = "NONE" 72 | 73 | func (m *TestMessage) GetClientName() string { 74 | if m != nil && m.ClientName != nil { 75 | return *m.ClientName 76 | } 77 | return "" 78 | } 79 | 80 | func (m *TestMessage) GetClientId() int32 { 81 | if m != nil && m.ClientId != nil { 82 | return *m.ClientId 83 | } 84 | return 0 85 | } 86 | 87 | func (m *TestMessage) GetDescription() string { 88 | if m != nil && m.Description != nil { 89 | return *m.Description 90 | } 91 | return Default_TestMessage_Description 92 | } 93 | 94 | func (m *TestMessage) GetMessageitems() []*TestMessage_MsgItem { 95 | if m != nil { 96 | return m.Messageitems 97 | } 98 | return nil 99 | } 100 | 101 | type TestMessage_MsgItem struct { 102 | Id *int32 `protobuf:"varint,1,req,name=id" json:"id,omitempty"` 103 | ItemName *string `protobuf:"bytes,2,opt,name=itemName" json:"itemName,omitempty"` 104 | ItemValue *int32 `protobuf:"varint,3,opt,name=itemValue" json:"itemValue,omitempty"` 105 | ItemType *TestMessage_ItemType `protobuf:"varint,4,opt,name=itemType,enum=ProtobufTest.TestMessage_ItemType" json:"itemType,omitempty"` 106 | XXX_unrecognized []byte `json:"-"` 107 | } 108 | 109 | func (m *TestMessage_MsgItem) Reset() { *m = TestMessage_MsgItem{} } 110 | func (m *TestMessage_MsgItem) String() string { return proto.CompactTextString(m) } 111 | func (*TestMessage_MsgItem) ProtoMessage() {} 112 | 113 | func (m *TestMessage_MsgItem) GetId() int32 { 114 | if m != nil && m.Id != nil { 115 | return *m.Id 116 | } 117 | return 0 118 | } 119 | 120 | func (m *TestMessage_MsgItem) GetItemName() string { 121 | if m != nil && m.ItemName != nil { 122 | return *m.ItemName 123 | } 124 | return "" 125 | } 126 | 127 | func (m *TestMessage_MsgItem) GetItemValue() int32 { 128 | if m != nil && m.ItemValue != nil { 129 | return *m.ItemValue 130 | } 131 | return 0 132 | } 133 | 134 | func (m *TestMessage_MsgItem) GetItemType() TestMessage_ItemType { 135 | if m != nil && m.ItemType != nil { 136 | return *m.ItemType 137 | } 138 | return TestMessage_TypeX 139 | } 140 | 141 | func init() { 142 | proto.RegisterEnum("ProtobufTest.TestMessage_ItemType", TestMessage_ItemType_name, TestMessage_ItemType_value) 143 | } 144 | -------------------------------------------------------------------------------- /Zap Logging/src/simple1/README.md: -------------------------------------------------------------------------------- 1 | # Using presets 2 | 3 | Zap recommends using presets for the simplest of cases. 4 | 5 | It makes three presets available: 6 | 7 | - Example 8 | - Development 9 | - Production 10 | 11 | I try out their presets in this piece of code. Here is the output. 12 | 13 | ```console 14 | $ go run src/simple1/main.go 15 | 16 | *** Using the Example logger 17 | 18 | {"level":"debug","msg":"This is a DEBUG message"} 19 | {"level":"info","msg":"This is an INFO message"} 20 | {"level":"info","msg":"This is an INFO message with fields","region":"us-west","id":2} 21 | {"level":"warn","msg":"This is a WARN message"} 22 | {"level":"error","msg":"This is an ERROR message"} 23 | {"level":"dpanic","msg":"This is a DPANIC message"} 24 | 25 | *** Using the Development logger 26 | 27 | 2018-05-02T13:52:44.332-0700 DEBUG simple1/main.go:28 This is a DEBUG message 28 | 2018-05-02T13:52:44.332-0700 INFO simple1/main.go:29 This is an INFO message 29 | 2018-05-02T13:52:44.332-0700 INFO simple1/main.go:30 This is an INFO message with fields {"region": "us-west", "id": 2} 30 | 2018-05-02T13:52:44.332-0700 WARN simple1/main.go:31 This is a WARN messagemain.main 31 | /Users/snbhatta/dev/zap-examples/src/simple1/main.go:31 32 | runtime.main 33 | /Users/snbhatta/.gradle/language/golang/1.9.2/go/src/runtime/proc.go:195 34 | 2018-05-02T13:52:44.332-0700 ERROR simple1/main.go:32 This is an ERROR message 35 | main.main 36 | /Users/snbhatta/dev/zap-examples/src/simple1/main.go:32 37 | runtime.main 38 | /Users/snbhatta/.gradle/language/golang/1.9.2/go/src/runtime/proc.go:195 39 | 40 | *** Using the Production logger 41 | 42 | {"level":"info","ts":1525294364.332839,"caller":"simple1/main.go:43","msg":"This is an INFO message"} 43 | {"level":"info","ts":1525294364.332864,"caller":"simple1/main.go:44","msg":"This is an INFO message with fields","region":"us-west","id":2} 44 | {"level":"warn","ts":1525294364.3328729,"caller":"simple1/main.go:45","msg":"This is a WARN message"} 45 | {"level":"error","ts":1525294364.332882,"caller":"simple1/main.go:46","msg":"This is an ERROR message","stacktrace":"main.main\n\t/Users/snbhatta/dev/zap-examples/src/simple1/main.go:46\nruntime.main\n\ 46 | t/Users/snbhatta/.gradle/language/golang/1.9.2/go/src/runtime/proc.go:195"} 47 | {"level":"dpanic","ts":1525294364.332895,"caller":"simple1/main.go:48","msg":"This is a DPANIC message","stacktrace":"main.main\n\t/Users/snbhatta/dev/zap-examples/src/simple1/main.go:48\nruntime.main\n 48 | \t/Users/snbhatta/.gradle/language/golang/1.9.2/go/src/runtime/proc.go:195"} 49 | 50 | 51 | *** Using the Sugar logger 52 | 53 | 2018-05-02T18:13:22.376-0700 INFO simple1/main.go:56 Info() uses sprint 54 | 2018-05-02T18:13:22.376-0700 INFO simple1/main.go:57 Infof() uses sprintf 55 | 2018-05-02T18:13:22.376-0700 INFO simple1/main.go:58 Infow() allows tags {"name": "Legolas", "type": 1} 56 | ``` 57 | 58 | # Observations 59 | 60 | - Both `Example` and `Production` loggers use the [JSON encoder](https://godoc.org/go.uber.org/zap/zapcore#NewJSONEncoder). `Development` uses the [Console](https://godoc.org/go.uber.org/zap/zapcore#NewConsoleEncoder) encoder. 61 | - The `logger.DPanic()` function causes a panic in `Development` logger but not in `Example` or `Production`. 62 | - The `Development` logger: 63 | * Adds a stack trace from Warn level and up. 64 | * Always prints the package/file/line number 65 | * Tacks extra fields as a json string at the end of the line 66 | * level names are uppercase 67 | * timestamp is in ISO8601 with seconds 68 | - The `Production` logger: 69 | * Doesn't log messages at debug level 70 | * Adds stack trace as a json field for Error, DPanic levels, but not for Warn. 71 | * Always adds the caller as a json field 72 | * timestamp is in epoch format 73 | * level is in lower case 74 | 75 | # Using the "sugar" logger 76 | 77 | The default logger expects structured tags. 78 | 79 | ```go 80 | logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) 81 | ``` 82 | 83 | This is the fastest option for an application where performance is key. 84 | 85 | However, for a just [a small additional penalty](https://github.com/uber-go/zap#performance), 86 | which actually is still slightly better than the standard library, you can use 87 | the _sugar_ logger, which uses a reflection based type detection to give you 88 | a simpler syntax to add tags of mixed types. 89 | 90 | ```go 91 | slogger := logger.Sugar() 92 | slogger.Info("Info() uses sprint") 93 | slogger.Infof("Infof() uses %s", "sprintf") 94 | slogger.Infow("Infow() allows tags", "name", "Legolas", "type", 1) 95 | ``` 96 | 97 | Output: 98 | 99 | ``` 100 | 2018-05-02T18:13:22.376-0700 INFO simple1/main.go:56 Info() uses sprint 101 | 2018-05-02T18:13:22.376-0700 INFO simple1/main.go:57 Infof() uses sprintf 102 | 2018-05-02T18:13:22.376-0700 INFO simple1/main.go:58 Infow() allows tags {"name": "Legolas", "type": 1} 103 | ``` 104 | 105 | You can switch from a sugar logger to a standard logger any time using the 106 | `.Desugar()` method on the logger. -------------------------------------------------------------------------------- /Protobuf/Addressbook/addressbook.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: addressbook.proto 3 | 4 | /* 5 | Package tutorial is a generated protocol buffer package. 6 | 7 | It is generated from these files: 8 | addressbook.proto 9 | 10 | It has these top-level messages: 11 | Person 12 | AddressBook 13 | */ 14 | package main 15 | 16 | import proto "github.com/golang/protobuf/proto" 17 | import fmt "fmt" 18 | import math "math" 19 | 20 | // Reference imports to suppress errors if they are not otherwise used. 21 | var _ = proto.Marshal 22 | var _ = fmt.Errorf 23 | var _ = math.Inf 24 | 25 | // This is a compile-time assertion to ensure that this generated file 26 | // is compatible with the proto package it is being compiled against. 27 | // A compilation error at this line likely means your copy of the 28 | // proto package needs to be updated. 29 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 30 | 31 | type Person_PhoneType int32 32 | 33 | const ( 34 | Person_MOBILE Person_PhoneType = 0 35 | Person_HOME Person_PhoneType = 1 36 | Person_WORK Person_PhoneType = 2 37 | ) 38 | 39 | var Person_PhoneType_name = map[int32]string{ 40 | 0: "MOBILE", 41 | 1: "HOME", 42 | 2: "WORK", 43 | } 44 | var Person_PhoneType_value = map[string]int32{ 45 | "MOBILE": 0, 46 | "HOME": 1, 47 | "WORK": 2, 48 | } 49 | 50 | func (x Person_PhoneType) String() string { 51 | return proto.EnumName(Person_PhoneType_name, int32(x)) 52 | } 53 | func (Person_PhoneType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} } 54 | 55 | type Person struct { 56 | Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` 57 | Id int32 `protobuf:"varint,2,opt,name=id" json:"id,omitempty"` 58 | Email string `protobuf:"bytes,3,opt,name=email" json:"email,omitempty"` 59 | Phones []*Person_PhoneNumber `protobuf:"bytes,4,rep,name=phones" json:"phones,omitempty"` 60 | } 61 | 62 | func (m *Person) Reset() { *m = Person{} } 63 | func (m *Person) String() string { return proto.CompactTextString(m) } 64 | func (*Person) ProtoMessage() {} 65 | func (*Person) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } 66 | 67 | func (m *Person) GetName() string { 68 | if m != nil { 69 | return m.Name 70 | } 71 | return "" 72 | } 73 | 74 | func (m *Person) GetId() int32 { 75 | if m != nil { 76 | return m.Id 77 | } 78 | return 0 79 | } 80 | 81 | func (m *Person) GetEmail() string { 82 | if m != nil { 83 | return m.Email 84 | } 85 | return "" 86 | } 87 | 88 | func (m *Person) GetPhones() []*Person_PhoneNumber { 89 | if m != nil { 90 | return m.Phones 91 | } 92 | return nil 93 | } 94 | 95 | type Person_PhoneNumber struct { 96 | Number string `protobuf:"bytes,1,opt,name=number" json:"number,omitempty"` 97 | Type Person_PhoneType `protobuf:"varint,2,opt,name=type,enum=tutorial.Person_PhoneType" json:"type,omitempty"` 98 | } 99 | 100 | func (m *Person_PhoneNumber) Reset() { *m = Person_PhoneNumber{} } 101 | func (m *Person_PhoneNumber) String() string { return proto.CompactTextString(m) } 102 | func (*Person_PhoneNumber) ProtoMessage() {} 103 | func (*Person_PhoneNumber) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} } 104 | 105 | func (m *Person_PhoneNumber) GetNumber() string { 106 | if m != nil { 107 | return m.Number 108 | } 109 | return "" 110 | } 111 | 112 | func (m *Person_PhoneNumber) GetType() Person_PhoneType { 113 | if m != nil { 114 | return m.Type 115 | } 116 | return Person_MOBILE 117 | } 118 | 119 | // Our address book file is just one of these. 120 | type AddressBook struct { 121 | People []*Person `protobuf:"bytes,1,rep,name=people" json:"people,omitempty"` 122 | } 123 | 124 | func (m *AddressBook) Reset() { *m = AddressBook{} } 125 | func (m *AddressBook) String() string { return proto.CompactTextString(m) } 126 | func (*AddressBook) ProtoMessage() {} 127 | func (*AddressBook) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } 128 | 129 | func (m *AddressBook) GetPeople() []*Person { 130 | if m != nil { 131 | return m.People 132 | } 133 | return nil 134 | } 135 | 136 | func init() { 137 | proto.RegisterType((*Person)(nil), "tutorial.Person") 138 | proto.RegisterType((*Person_PhoneNumber)(nil), "tutorial.Person.PhoneNumber") 139 | proto.RegisterType((*AddressBook)(nil), "tutorial.AddressBook") 140 | proto.RegisterEnum("tutorial.Person_PhoneType", Person_PhoneType_name, Person_PhoneType_value) 141 | } 142 | 143 | func init() { proto.RegisterFile("addressbook.proto", fileDescriptor0) } 144 | 145 | var fileDescriptor0 = []byte{ 146 | // 254 bytes of a gzipped FileDescriptorProto 147 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x50, 0xc1, 0x4a, 0xc3, 0x40, 148 | 0x14, 0x74, 0xd3, 0x74, 0x69, 0x5f, 0xa1, 0xc4, 0x87, 0x48, 0x28, 0x1e, 0x42, 0x4e, 0x01, 0x61, 149 | 0x0f, 0x55, 0xf0, 0x6c, 0xa1, 0xa0, 0x68, 0x4d, 0x59, 0x14, 0xcf, 0x09, 0x79, 0x60, 0x68, 0x92, 150 | 0xb7, 0x6c, 0xd2, 0x43, 0xff, 0xdd, 0x83, 0x64, 0x13, 0x45, 0xc4, 0xdb, 0xbc, 0x99, 0x61, 0x76, 151 | 0x76, 0xe0, 0x3c, 0x2b, 0x0a, 0x4b, 0x6d, 0x9b, 0x33, 0x1f, 0x94, 0xb1, 0xdc, 0x31, 0xce, 0xba, 152 | 0x63, 0xc7, 0xb6, 0xcc, 0xaa, 0xf8, 0x53, 0x80, 0xdc, 0x93, 0x6d, 0xb9, 0x41, 0x04, 0xbf, 0xc9, 153 | 0x6a, 0x0a, 0x45, 0x24, 0x92, 0xb9, 0x76, 0x18, 0x97, 0xe0, 0x95, 0x45, 0xe8, 0x45, 0x22, 0x99, 154 | 0x6a, 0xaf, 0x2c, 0xf0, 0x02, 0xa6, 0x54, 0x67, 0x65, 0x15, 0x4e, 0x9c, 0x69, 0x38, 0xf0, 0x16, 155 | 0xa4, 0xf9, 0xe0, 0x86, 0xda, 0xd0, 0x8f, 0x26, 0xc9, 0x62, 0x7d, 0xa5, 0xbe, 0xf3, 0xd5, 0x90, 156 | 0xad, 0xf6, 0xbd, 0xfc, 0x72, 0xac, 0x73, 0xb2, 0x7a, 0xf4, 0xae, 0xde, 0x60, 0xf1, 0x8b, 0xc6, 157 | 0x4b, 0x90, 0x8d, 0x43, 0x63, 0x81, 0xf1, 0x42, 0x05, 0x7e, 0x77, 0x32, 0xe4, 0x4a, 0x2c, 0xd7, 158 | 0xab, 0xff, 0xa3, 0x5f, 0x4f, 0x86, 0xb4, 0xf3, 0xc5, 0xd7, 0x30, 0xff, 0xa1, 0x10, 0x40, 0xee, 159 | 0xd2, 0xcd, 0xe3, 0xf3, 0x36, 0x38, 0xc3, 0x19, 0xf8, 0x0f, 0xe9, 0x6e, 0x1b, 0x88, 0x1e, 0xbd, 160 | 0xa7, 0xfa, 0x29, 0xf0, 0xe2, 0x3b, 0x58, 0xdc, 0x0f, 0xeb, 0x6c, 0x98, 0x0f, 0x98, 0x80, 0x34, 161 | 0xc4, 0xa6, 0xea, 0x47, 0xe8, 0x3f, 0x12, 0xfc, 0x7d, 0x4d, 0x8f, 0x7a, 0x2e, 0xdd, 0x90, 0x37, 162 | 0x5f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x08, 0xe9, 0x13, 0xff, 0x5d, 0x01, 0x00, 0x00, 163 | } 164 | -------------------------------------------------------------------------------- /Zap Logging/src/customlogger/README.md: -------------------------------------------------------------------------------- 1 | # Creating custom loggers 2 | 3 | Instead of using the presets, you can create custom loggers with the exact 4 | combinations of features that you want. 5 | 6 | # Using the zap config struct to create a logger 7 | 8 | Loggers can be created using a configuration struct `zap.Config`. You are expected 9 | to fill in the struct with require values, and then call the `.Build()` method 10 | on the struct to get your logger. 11 | 12 | ```go 13 | cfg := zap.Config{...} 14 | logger, err := cfg.Build() 15 | ``` 16 | 17 | There are no sane defaults for the struct. You have to at the minimum provide 18 | values for the three classes of settings that zap needs. 19 | 20 | * _encoder_: Just adding a `Encoding: "xxx"` field is a minimum. Using `json` 21 | here as the value will create a default JSON encoder. You can customize the 22 | encoder (which almost certainly you have to, because the defaults aren't very 23 | useful), by adding a `zapcore.EncoderConfig` struct to the `EncoderConfig` 24 | field. 25 | * _level enabler_: This is a data type which allows zap to determine whether a 26 | message at a particular level should be displayed. In the zap config struct, 27 | you provide such a type using the `AtomicLevel` wrapper in the `Level` field. 28 | * _sink_: This is the destination of the log messages. You can specify multiple 29 | output paths using the `OutputPaths` field which accepts a list of path names. 30 | Magic values like `"stderr"` and `"stdout"` can be used for the usual 31 | purposes. 32 | 33 | # Customizing the encoder 34 | 35 | Just mentioning an encoder type in the struct is not enough. By default the 36 | JSON encoder only outputs fields specifically provided in the log messages. 37 | 38 | ```go 39 | logger, _ = zap.Config{ 40 | Encoding: "json", 41 | Level: zap.NewAtomicLevelAt(zapcore.DebugLevel), 42 | OutputPaths: []string{"stdout"}, 43 | }.Build() 44 | 45 | logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) 46 | ``` 47 | 48 | Will output: 49 | 50 | ``` 51 | {"region":"us-west","id":2} 52 | ``` 53 | 54 | Even the message is not printed! 55 | 56 | To add the message in the JSON encoder, you need to specify the JSON key name 57 | which will display this value in the output. 58 | 59 | ```go 60 | logger, _ = zap.Config{ 61 | Encoding: "json", 62 | Level: zap.NewAtomicLevelAt(zapcore.DebugLevel), 63 | OutputPaths: []string{"stdout"}, 64 | EncoderConfig: zapcore.EncoderConfig{ 65 | MessageKey: "message", 66 | }, 67 | }.Build() 68 | 69 | logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) 70 | ``` 71 | 72 | Will output: 73 | 74 | ``` 75 | {"message":"This is an INFO message with fields","region":"us-west","id":2} 76 | ``` 77 | 78 | zap can add more metadata to the message like level name, timestamp, caller, 79 | stacktrace, etc. Unless you specifically mention the JSON key in the output 80 | corresponding to these metadata, it is not added. 81 | 82 | Some of these field names *have* to be paired with an _encoder_ else zap just 83 | burns and dies (!!). 84 | 85 | For example: 86 | 87 | ```go 88 | cfg := zap.Config{ 89 | Encoding: "json", 90 | Level: zap.NewAtomicLevelAt(zapcore.DebugLevel), 91 | OutputPaths: []string{"stderr"}, 92 | ErrorOutputPaths: []string{"stderr"}, 93 | EncoderConfig: zapcore.EncoderConfig{ 94 | MessageKey: "message", 95 | 96 | LevelKey: "level", 97 | EncodeLevel: zapcore.CapitalLevelEncoder, 98 | 99 | TimeKey: "time", 100 | EncodeTime: zapcore.ISO8601TimeEncoder, 101 | 102 | CallerKey: "caller", 103 | EncodeCaller: zapcore.ShortCallerEncoder, 104 | }, 105 | } 106 | logger, _ = cfg.Build() 107 | logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) 108 | ``` 109 | 110 | Will output: 111 | 112 | ``` 113 | {"level":"INFO","time":"2018-05-02T16:37:54.998-0700","caller":"customlogger/main.go:91","message":"This is an INFO message with fields","region":"us-west","id":2} 114 | ``` 115 | 116 | Each of the encoder can be customized to fit your requirements, and some have 117 | different implementations provided by zap. 118 | 119 | - timestamp can be output in either ISO 8601 format, or as an epoch timestamp. 120 | - level can be capital or lowercase or even colored (even though it is probably 121 | only visible in the console output). Weirdly, the colors escape codes are 122 | not stripped in the JSON output. 123 | - caller can be shown in short and full formats. 124 | 125 | # Changing logger behavior on the fly 126 | 127 | loggers can be cloned from an existing logger with certain modification to their 128 | behavior. This can often be useful for example, when you want to reduce code 129 | duplication by fixing a standard set of fields the logger will always output. 130 | 131 | * `logger.AddCaller()` adds caller annotation 132 | * `logger.AddStacktrace()` adds stacktraces for messages at and above a given 133 | level 134 | * `logger.Fields()` adds specified fields to all messages output by the new logger 135 | * `logger.WrapCore()` allows you to modify or even completely replace the 136 | underlying _core_ in the logger which combines the encoder, level and sink. 137 | 138 | ```go 139 | fmt.Printf("\n*** Using a JSON encoder, at debug level, sending output to stdout, all possible keys specified\n\n") 140 | 141 | cfg := zap.Config{ 142 | Encoding: "json", 143 | Level: zap.NewAtomicLevelAt(zapcore.DebugLevel), 144 | OutputPaths: []string{"stderr"}, 145 | ErrorOutputPaths: []string{"stderr"}, 146 | EncoderConfig: zapcore.EncoderConfig{ 147 | MessageKey: "message", 148 | 149 | LevelKey: "level", 150 | EncodeLevel: zapcore.CapitalLevelEncoder, 151 | 152 | TimeKey: "time", 153 | EncodeTime: zapcore.ISO8601TimeEncoder, 154 | 155 | CallerKey: "caller", 156 | EncodeCaller: zapcore.ShortCallerEncoder, 157 | }, 158 | } 159 | logger, _ = cfg.Build() 160 | 161 | logger.Info("This is an INFO message") 162 | 163 | fmt.Printf("\n*** Same logger with console logging enabled instead\n\n") 164 | 165 | logger.WithOptions( 166 | zap.WrapCore( 167 | func(zapcore.Core) zapcore.Core { 168 | return zapcore.NewCore(zapcore.NewConsoleEncoder(cfg.EncoderConfig), zapcore.AddSync(os.Stderr), zapcore.DebugLevel) 169 | })).Info("This is an INFO message") 170 | 171 | ``` 172 | 173 | Output: 174 | 175 | ``` 176 | *** Using a JSON encoder, at debug level, sending output to stdout, all possible keys specified 177 | 178 | {"level":"INFO","time":"2018-05-02T16:37:54.998-0700","caller":"customlogger/main.go:90","message":"This is an INFO message"} 179 | 180 | *** Same logger with console logging enabled instead 181 | 182 | 2018-05-02T16:37:54.998-0700 INFO customlogger/main.go:99 This is an INFO message 183 | 184 | ``` -------------------------------------------------------------------------------- /Command/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------