{"id":16710687,"url":"https://github.com/debck/learning-go","last_synced_at":"2025-03-21T20:33:10.633Z","repository":{"id":124400757,"uuid":"259642082","full_name":"debck/Learning-Go","owner":"debck","description":"List of concepts and code snippets that would help in learning Golang and apply in Web Development 🎉","archived":false,"fork":false,"pushed_at":"2020-05-31T06:36:33.000Z","size":70,"stargazers_count":48,"open_issues_count":0,"forks_count":4,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-18T04:52:02.543Z","etag":null,"topics":["concepts","database","forms","golang","learning-golang","middleware","middlware","parsing-xml-data","routes","snippets","study","unit-testing","webdevelopment"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/debck.png","metadata":{"files":{"readme":"Readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-04-28T13:17:26.000Z","updated_at":"2024-10-22T23:35:07.000Z","dependencies_parsed_at":null,"dependency_job_id":"3f62f696-c56b-425d-ba93-f6608ce310de","html_url":"https://github.com/debck/Learning-Go","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/debck%2FLearning-Go","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/debck%2FLearning-Go/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/debck%2FLearning-Go/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/debck%2FLearning-Go/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/debck","download_url":"https://codeload.github.com/debck/Learning-Go/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244866191,"owners_count":20523477,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["concepts","database","forms","golang","learning-golang","middleware","middlware","parsing-xml-data","routes","snippets","study","unit-testing","webdevelopment"],"created_at":"2024-10-12T20:09:19.171Z","updated_at":"2025-03-21T20:33:10.592Z","avatar_url":"https://github.com/debck.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg  src=\"https://user-images.githubusercontent.com/33368759/80697133-2a085b00-8af6-11ea-9506-903486db94c1.png\"\u003e\n\u003c/p\u003e\nA simple list of concepts and code snippets that would help in learning Golang and apply in Web Development :tada:. I tried to jot down when I was learning. It might be helpful for beginners who want to learn Go for web development.\n\u003cbr /\u003e\n\u003cbr /\u003e\n\n[![Open Source](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://opensource.org/)\n[![GitHub license](https://img.shields.io/github/license/debck/Learning-Go?style=flat-square)](https://github.com/debck/Learning-Go/blob/master/LICENSE)  ![Maintenance](https://img.shields.io/maintenance/yes/2020?style=flat-square) ![GitHub last commit](https://img.shields.io/github/last-commit/debck/Learning-Go?style=flat-square)\n[![HitCount](http://hits.dwyl.com/debck/Learning-Go.svg)](http://hits.dwyl.com/debck/Learning-Go)\n\n\n\u003e ✌️ Hope you find something useful. If you like it please give it a 🌟.\n\n## Contents\n* [Installation](#Installation)\n* [Concepts to learn before diving into Web](#Initial-Concepts-to-Study-before-diving-deep)\n* [Basic Hello World](#Basic-Hello-World)\n* [Adding static assets](#Adding-static-asset)\n* [Creating Routes](#Adding-Routes)\n* [Adding Forms](#Adding-Forms)\n* [Adding MiddleWare](#Adding-MiddleWare)\n* [Sessions Management](#Sessions-Management)\n* [Adding Database](#Adding-Database)\n\t* [MongoDB](#MongoDB)\n* [Writing Unit Test](#Writing-Unit-Test)\n* [Parsing XML Data](#Parsing-XML-Data)\n* [File Uploading](#File-Uploading)\n\n## Installation\n\n\u003e Follow the [official doc](https://golang.org/doc/install) and setup Go depending on your OS (ie. Windows , Linux, OS X)\n\n## Initial Concepts to Study before diving deep\n\n* Basic Understanding of\n    * Variables\n    * Constants\n    * Packages and import/export\n    * Functions\n    * Pointers\n    * Mutability\n * Types\n    * Type Conversion \n    * Type assertion**\n    * Structs\n    * Composition\n * Collection Types\n    * Arrays\n    * Slicing\n    * Range \u0026 Maps\n * Control Flow\n    * If, For, Switch statement\n * Methods\n * Interfaces\n * Concurrency\n    * Goroutines\n    * Channels\n\n\n\n\n\n## Basic Hello World\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"net/http\"\n)\n\nfunc main() {\n    http.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n        fmt.Fprintf(w, \"Hello, World !\")\n    })\n\n    http.ListenAndServe(\":8000\", nil)\n}\n```\n[Go back to top \u0026#8593;](#Contents)\n\n## Adding static asset\n\nWhen we want to serve static files like CSS, JavaScript or images to Web.\n\n```go\nfunc main() {\n    http.HandleFunc(\"/\", func (w http.ResponseWriter, r *http.Request) {\n        fmt.Fprintf(w, \"Hello World!\")\n    })\n   \n    fs := http.FileServer(http.Dir(\"./static\"))\n    http.Handle(\"/static/\", http.StripPrefix(\"/static/\", fs))\n\n    http.ListenAndServe(\":8000\", nil)\n}\n```\n[Go back to top \u0026#8593;](#Contents)\n\n## Adding Routes\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"encoding/json\"\n    \"net/http\"\n    \"github.com/gorilla/mux\"\n)\n\n\ntype Tasks struct {\n    ID \t\tstring  \t`json:\"id,omitempty\"`\n    TASKNAME \tstring \t\t`json:\"task,omitempty\"`\n}\n\nvar task []Tasks\n\nfunc getAllTask(w http.ResponseWriter, r *http.Request) {\n\tjson.NewEncoder(w).Encode(task)\n}\n\n\nfunc getTask(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tfor _,item := range task {\n\t\tif item.ID == params[\"id\"] {\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(\u0026Tasks{})\n}\n\n\nfunc main() {\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"/task\", getAllTask).Methods(\"GET\")\n\trouter.HandleFunc(\"/task/{id}\", getTask).Methods(\"GET\")\n\t\n\thttp.ListenAndServe(\":8000\", router)\n}\n\n```\n\n[Go back to top \u0026#8593;](#Contents)\n\n## Adding Forms\n\nConsidering the form has 2 fields `Email` and `Message`.\n\n```go\n\npackage main\n\nimport (\n\t\"log\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\ntype Details struct {\n    Email   string\n    Message string\n}\n\nfunc messageHandle(w http.ResponseWriter, r *http.Request) {\n\tif err := r.ParseForm(); err != nil {\n\t\tfmt.Fprintf(w, \"ParseForm() err: %v\", err)\n\t\treturn\n\t}\n\t\n\tdata := Details{\n\t\tEmail:   r.FormValue(\"email\"),\n\t\tMessage: r.FormValue(\"message\"),\n        }\n\n        // do something with the data\n}\n\nfunc main() {\n    http.HandleFunc(\"/\", messageHandle)\n    \n    if err := http.ListenAndServe(\":8080\", nil); err != nil {\n        log.Fatal(err)\n    }\n}\n\n\n```\n\n[Go back to top \u0026#8593;](#Contents)\n\n## Adding MiddleWare\n\nHere, the `Middleware` function allows adding more than one layer of middleware and handle them appropriately.\n`SomeMiddleware` is the middleware function which gets called before the route handler function `getAllTask`\n\n```go\n\npackage main\n\nimport (\n    \"encoding/json\"\n    \"log\"\n    \"net/http\"\n    \"github.com/gorilla/mux\"\n)\n\nfunc getAllTask(w http.ResponseWriter, r *http.Request) {\n\t// ... do something inside this route\n}\n\n\n// Function allows adding more than one layer of middleware and handle them appropriately\n\nfunc Middleware(h http.Handler, middleware ...func(http.Handler) http.Handler) http.Handler {\n    for _, mw := range middleware {\n        h = mw(h)\n    }\n    return h\n}\n\n// Middlware function\n\nfunc SomeMiddleware(next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\n\t\t // ... do middleware things\n\n        next.ServeHTTP(w, r)\n    })\n}\n\nfunc main() {\n\n\trouter := mux.NewRouter()\n\trouter.Handle(\"/task\", Middleware(\n        http.HandlerFunc(getAllTask),\n        SomeMiddleware,\n    ))\n    log.Fatal(http.ListenAndServe(\":8000\", router))\n}\n\n\n```\n\n[Go back to top \u0026#8593;](#Contents)\n\n## Sessions Management\n\n```go\n\nimport (\n    \"os\"\n    \"log\"\n    \"net/http\"\n    \"github.com/gorilla/sessions\"\n)\n\nvar store = sessions.NewCookieStore([]byte(os.Getenv(\"SESSION_KEY\")))\n\nfunc Handlerfunction(w http.ResponseWriter, r *http.Request) {\n\tsession, err := store.Get(r, \"session-name\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\t\n\t// Set some session values.\n    \tsession.Values[\"hello\"] = \"world\"\n    \t// Save it \n    \tsession.Save(r, w)\n}\n\n\nfunc main() {\n    http.HandleFunc(\"/\", Handlerfunction)\n    \n    if err := http.ListenAndServe(\":8080\", nil); err != nil {\n        log.Fatal(err)\n    }\n}\n\n```\n\n[Go back to top \u0026#8593;](#Contents)\n\n\n## Adding Database\n\n### MongoDB\n\nHere in this example we have connected MongoDB with our application and saved sample data into the collection \n\n```go\n\npackage main\n\nimport (\n\"context\"\n\"fmt\"\n\"os\"\n\"time\"\n\"go.mongodb.org/mongo-driver/mongo\"\n\"go.mongodb.org/mongo-driver/mongo/options\"\n)\n\ntype Data struct {\n\tID  int `json:\"Field Int\"`\n\tTask string `json:\"Field Str\"`\n}\n\nfunc main() {\n\t\n\tclientOptions := options.Client().ApplyURI(\"\u003cMONGO_URI\u003e\") \n\n\t// Connect to the MongoDB\n\tclient, err := mongo.Connect(context.TODO(), clientOptions)\n\t\n\tif err != nil {\n\t\tfmt.Println(\"mongo.Connect() ERROR:\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// To manage multiple API requests\n\tctx, _ := context.WithTimeout(context.Background(), 15*time.Second)\n\n\t// Access a MongoDB collection through a database\n\tcol := client.Database(\"DATABASE_NAME\").Collection(\"COLLECTION_NAME\")\n\n\t// Declare a MongoDB struct instance for the document's fields and data\n\tnewData := Data{\n\t\tID: 12,\n\t\tTask: \"Learn Go\",\n\t}\n\n\tresult, err := col.InsertOne(ctx, newData)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR:\", err)\n\t\tos.Exit(1)\n\n\t} else {\n\tfmt.Println(\"Result:\", result)\n\t}\n}\n\n```\n\n[Go back to top \u0026#8593;](#Contents)\n\n\n## Writing Unit Test\n\nConsider the [Adding Routes](#Adding-Routes) section for testing. The below test case is for the `/task` route which returns an array of tasks created by users.\n\n```go\n\npackage main\n\nimport (\n\t\"net/http\"\n\t\"testing\"\n\t\"net/http/httptest\"\n\t\"strings\"\n)\n\nfunc TestGetAllTask(t *testing.T) {\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:8000/task\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tres := httptest.NewRecorder()\n\thandler := http.HandlerFunc(getAllTask)\n\thandler.ServeHTTP(res, req)\n\t\n\tif status := res.Code; status != http.StatusOK {\n\t\tt.Errorf(\"Wrong Status Code: got %v want %v\",\n\t\t\tstatus, http.StatusOK)\n\t}\n\n\t// Check the response body is what we expect.\n\texpected := `[{\"id\":\"1\",\"task\":\"Hello\"},{\"id\":\"2\",\"task\":\"World\"},{\"id\":\"3\",\"task\":\"yeah\"}]`\n\n\tif strings.TrimRight(res.Body.String(),\"\\n\") != expected {\n\t\tt.Errorf(\"ERROR: got %v want %v\",\n\t\t\tres.Body.String(), expected)\n\t}\n}\n\n```\nRemember Test file should be name of original file + test like: `base.go` - `base_test.go`.(good practice)\n\nAfter running the above test case by `go test -v` command, the following output will appear\n\n```bash\nF:\\Go\\src\\Rest_API\u003ego test -v\n=== RUN   TestGetAllTask\n--- PASS: TestGetAllTask (0.00s)\nPASS\nok      Rest_API        0.454s\n```\n\n[Go back to top \u0026#8593;](#Contents)\n\n\n## Parsing XML Data\n\nFor example we have taken [this](https://github.com/debck/Learning-Go/blob/master/assets/foods.xml) XML file for parsing. \n\n```go\npackage main\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\n// struct which contains the array of all Foods in the file.\ntype Foods struct {\n\tFoods []Food `xml:\"food\"`\n}\n\n// struct which contains the details of one food.\ntype Food struct {\n\tName     string `xml:\"name\"`\n\tPrice    string `xml:\"price\"`\n\tCalories string `xml:\"calories\"`\n}\n\nfunc main() {\n\t// Open xml file\n\txmlFile, err := os.Open(\"foods.xml\")\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\t// defer the closing of our xmlfile so that we can parse later\n\tdefer xmlFile.Close()\n\n\t// read the xml file as a byte array.\n\tbyteValue, _ := ioutil.ReadAll(xmlFile)\n\n\tvar f Foods\n\n\txml.Unmarshal(byteValue, \u0026f)\n\n\t// Do something with the info.....\n\n\t// Here, we print out the Foods as just an example\n\n\tfmt.Println(\"______MENU______\")\n\tfor i := 0; i \u003c len(f.Foods); i++ {\n\t\tfmt.Println(f.Foods[i].Name + \" \" + f.Foods[i].Price + \" \" + f.Foods[i].Calories)\n\t}\n\n}\n\n```\nAfter running the above program, the following output will appear\n\n```bash\nF:\\Go\\src\\Code\u003ego run parsexml.go\n______MENU______\nBelgian Waffles $5.95 650\nFrench Toast $4.50 600\n```\n\n[Go back to top \u0026#8593;](#Contents)\n\n## File Uploading\n\n\u003e Todo\n\n## Contribute\n\nContributions are always welcome! Please open an [issue](https://github.com/debck/Learning-Go/issues/new) if you think something should be added to the list.\n\n## Licence\n\nMIT © [Debasish Sahoo](https://github.com/debck/Learning-Go/blob/master/LICENSE)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdebck%2Flearning-go","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdebck%2Flearning-go","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdebck%2Flearning-go/lists"}