{"id":659,"date":"2020-05-15T11:42:46","date_gmt":"2020-05-15T11:42:46","guid":{"rendered":"https:\/\/blog.samarthya.me\/wps\/?p=659"},"modified":"2020-05-16T13:14:11","modified_gmt":"2020-05-16T13:14:11","slug":"webservice-in-golang","status":"publish","type":"post","link":"https:\/\/blog.samarthya.me\/wps\/2020\/05\/15\/webservice-in-golang\/","title":{"rendered":"WebService: In golang"},"content":{"rendered":"<p>Having practiced creating loads of <code>Console based<\/code> programs of <code>golang<\/code>, it is now time to try something new &#8211; A Web Service.<\/p>\n<p>In this blog, I will try and create a Web Service (RESTful) that will be built entirely on Go.<\/p>\n<h2>Weapons of choice<\/h2>\n\n\n<ul class=\"wp-block-list\"><li>Visual studio code (I like it)<\/li><li>GO &#8211; 1.14<\/li><\/ul>\n\n\n\n<p>As I write the code I will touch upon the various building blocks that are used. If I miss something, please do comment and let me know.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Source Code<\/h3>\n\n\n\n<p>Source code is available <a href=\"https:\/\/github.com\/samarthya\/gws\">here<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Remember<\/h2>\n\n\n\n<p>You might come across an empty interface <code>type interface{}<\/code> and just to give you a heads up.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is Empty interface?<\/h3>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>The <code>interface{}<\/code> (empty interface) type describes an interface with zero methods. Every Go type implements at least zero methods and therefore satisfies the empty interface.<\/p><\/blockquote>\n\n\n\n<p>Some examples are as under<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var i interface{}\ni = \"a string\"\ni = 3.14<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>var f interface{}\nerr := json.Unmarshal(b, &amp;f)<\/code><\/pre>\n\n\n\n<p>With interface explained time to get started with the cod. First thing first I will create a workspace and initialize a module.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img fetchpriority=\"high\" decoding=\"async\" width=\"548\" height=\"890\" src=\"https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2020\/05\/Screenshot-2020-05-16-at-4.21.47-PM.png\" alt=\"\" class=\"wp-image-677\" srcset=\"https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2020\/05\/Screenshot-2020-05-16-at-4.21.47-PM.png 548w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2020\/05\/Screenshot-2020-05-16-at-4.21.47-PM-185x300.png 185w\" sizes=\"(max-width: 548px) 100vw, 548px\" \/><figcaption>Folder structure<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Module: init<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>Samarthya:ws> go mod init github.com\/samarthya\/gws<\/code><\/pre>\n\n\n\n<p>It creates a file go.mod as under<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">File [go. mod]<\/h3>\n\n\n\n<p>Creating package<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>module github.com\/samarthya\/gws\n\ngo 1.14<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">main.go<\/h2>\n\n\n\n<p>Now workspace defined, I will quickly stub my dummy code in the file to check it compiles ok.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tfmt.Printf(\" Webservice.\\n\")\n}\n<\/code><\/pre>\n\n\n\n<p>The <code>go lang<\/code> package that we will be using is <code>net\/http<\/code> (details available <a href=\"https:\/\/golang.org\/pkg\/net\/http\/\">here<\/a>).<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>HTTP package provide client server implementation that we will be using to write a sample code and expose it as an rest end point.<\/p><\/blockquote>\n\n\n\n<p>The primary functions that people use are<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/golang.org\/pkg\/net\/http\/#Handle\">Handle<\/a> : (From official documentation) <strong>Handle<\/strong> registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.<\/li><li><a href=\"https:\/\/golang.org\/pkg\/net\/http\/#HandleFunc\">HandleFunc<\/a> : <strong>HandleFunc<\/strong> registers the handler function for the given pattern in the DefaultServeMux.<\/li><li><a href=\"https:\/\/golang.org\/pkg\/net\/http\/#ServeMux\">ServeMux<\/a>: <strong>ServeMux<\/strong> is an HTTP request multiplexer. It matches the URL of each incoming request <code>against a list of registered patterns<\/code> and calls the handler for the pattern that most closely matches the URL.<\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Adding the HTTP-request handlers<\/h4>\n\n\n\n<p>Now, instead of simple defining a Hello World messge, I thought of using a counter. In my version the counter is incremented each time an endpoint is hit and incremented value is displayed back.<\/p>\n\n\n\n<p>Added some <strong>handler<\/strong> code for <code>\/count<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"sync\"\n)\n\n\/\/ CountHandler Handles the count\ntype CountHandler struct {\n\tsync.Mutex \/\/ guards n\n\tn  int\n}\n\nfunc (h *CountHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\th.Lock()\n\tdefer h.Unlock()\n\th.n++\n\tfmt.Fprintf(w, \"count is %d\\n\", h.n)\n}\n\nfunc main() {\n\tfmt.Printf(\" Webservice.\\n\")\n\thttp.Handle(\"\/count\", new(CountHandler))\n\tlog.Fatal(http.ListenAndServe(\":8090\", nil))\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">CountHandler<\/h3>\n\n\n\n<p>A struct type which has a numeric variable to store the number of times the request was made and a mutex (<code>sync.mutex<\/code>) to ensure parallel requests processing.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">http.Handle<\/h3>\n\n\n\n<p>Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>func (mux *<a href=\"https:\/\/golang.org\/pkg\/net\/http\/#ServeMux\">ServeMux<\/a>) Handle(pattern <a href=\"https:\/\/golang.org\/pkg\/builtin\/#string\">string<\/a>, handler <a href=\"https:\/\/golang.org\/pkg\/net\/http\/#Handler\">Handler<\/a>)<\/p><\/blockquote>\n\n\n\n<ul class=\"wp-block-list\"><li>In our example we are listening on <code>\"\/count\"<\/code> that is the pattern<\/li><li><a href=\"https:\/\/golang.org\/pkg\/net\/http\/#Handler\">Handler<\/a>: It is an interface (the second argument), that responds to the HTTP request.<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>type Handler interface {\n    ServeHTTP(ResponseWriter, *Request)\n}<\/code><\/pre>\n\n\n\n<p>In our case we are using CountHandler as an argument which implements the function <code>ServeHTTP<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func (h *CountHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\th.Lock()\n\tdefer h.Unlock()\n\th.n++\n\tfmt.Fprintf(w, \"count is %d\\n\", h.n)\n}<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/golang.org\/pkg\/net\/http\/#ResponseWriter\">ResponseWriter<\/a> <ul><li>It is an interface, used to create HTTP response.<\/li><\/ul><\/li><li><a href=\"https:\/\/golang.org\/pkg\/net\/http\/#Request\">Request<\/a><ul><li>A Request represents an HTTP request received by a server or to be sent by a client.<\/li><\/ul><\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">ServeHTTP<\/h3>\n\n\n\n<h3 class=\"wp-block-heading\">main()<\/h3>\n\n\n\n<p>The entry point to the code<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>ListenAndServe<\/strong> starts an HTTP server with a given address and handler.<ul><li>In our sample we are listening on 8090 &amp; localhost.<\/li><li>The handler is usually <code>nil<\/code>, which means to use DefaultServeMux.<\/li><li><strong>Handle<\/strong> and <strong>HandleFunc<\/strong> add handlers to <strong><a href=\"https:\/\/golang.org\/pkg\/net\/http\/#ServeMux\">DefaultServeMux<\/a><\/strong><\/li><\/ul><\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">JSON<\/h3>\n\n\n\n<p>One of the crucial pieces of building is JSON, which can be an input to a web-request and an output from a web-request. <\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>JSON is an data interchange format.<\/p><\/blockquote>\n\n\n\n<p>To allow easier handling of Web-Requests go provides a package<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import \"encoding\/json\"<\/code><\/pre>\n\n\n\n<p>Official documentation can be found <a href=\"https:\/\/golang.org\/pkg\/encoding\/json\/#pkg-overview\">here<\/a> &amp; another helpful link is available <a href=\"https:\/\/blog.golang.org\/json\">here<\/a>.<\/p>\n\n\n\n<p>Package <code>json<\/code> implements encoding and decoding of JSON.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/golang.org\/pkg\/encoding\/json\/#Marshal\">Marshal<\/a> : Marshal returns the JSON encoding of an object<ul><li><code>Marshal traverses the values in the object recursively &amp; if an encountered value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to produce JSON.<\/code><\/li><\/ul><\/li><li><a href=\"https:\/\/golang.org\/pkg\/encoding\/json\/#Unmarshal\">Unmarshal<\/a> : Unmarshal parses the JSON-encoded data and stores the result in the argument passed.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<p>Let&#8217;s define a type that we can use to validate.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type User struct {\n\tName string `json:\"firstName\"`\n\tMiddlename string `json:\"middleName\"`\n\tSurname string `json:\"lastName\"`\n\tEmail string `json:\"userName\"`\n\tAddress string `json:\"address\"`\n}<\/code><\/pre>\n\n\n\n<p>The encoding of each struct field <code>can be customized by the format string stored under the \"json\" key<\/code> in the struct field&#8217;s tag. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>`json:\"middleName\"`<\/code><\/pre>\n\n\n\n<p>The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.<\/p>\n\n\n\n<p>The &#8220;omitempty&#8221; option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>`json:\"middleName,omitempty\"`<\/code><\/pre>\n\n\n\n<p>If I try and invoke <code>Marshal<\/code> on it, the output looks like below.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var user User = User{ \n\t\tName: \"Saurabh\", \n\t\tMiddlename: \"\",\n\t\tSurname: \"Sharma\", \n\t\tEmail: \"saurabh@samarthya.me\", \n\t\tAddress: \"Auzzieland\",\n\t}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>u, err := json.Marshal(user)\n\tif err != nil {\n\t\tlog.Println(err)\n\t} else {\n\t\tfmt.Println(\" User: \", string(u))\n\t}<\/code><\/pre>\n\n\n\n<p>The <code>Marshal<\/code> returns <code>[] byte &amp; error<\/code> which we assign to <code>u<\/code> and <code>err<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func Marshal(v interface{}) (&#91;]byte, error)<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Output <\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>User: {\"firstName\":\"Saurabh\",\"middleName\":\"\",\"lastName\":\"Sharma\",\"userName\":\"saurabh@samarthya.me\",\"address\":\"Auzzieland\"}<\/code><\/pre>\n\n\n\n<p>Let me add some some more attributes like the <code>omitempty<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/User Stores the information about a user\ntype User struct {\n\tName string `json:\"firstName\"`\n\tMiddlename string `json:\"middleName,omitempty\"`\n\tSurname string `json:\"lastName\"`\n\tEmail string `json:\"userName\"`\n\tAddress string `json:\"address\"`\n}<\/code><\/pre>\n\n\n\n<p>Running the same code will return<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>User:  {\"firstName\":\"Saurabh\",\"lastName\":\"Sharma\",\"userName\":\"saurabh@samarthya.me\",\"address\":\"Auzzieland\"}<\/code><\/pre>\n\n\n\n<p>You can see the empty <code>Middlename<\/code> has been ignored.<\/p>\n\n\n\n<p>Unmarshalling, is a way you can use a <code>byte []<\/code> and create an object from it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>unc Unmarshal(data &#91;]byte, v interface{}) error<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>var newUser User\n\ne := json.Unmarshal(u, &amp;newUser)\n\nif e == nil {\n\tfmt.Println(\" Name : \", newUser.Name, \" \", newUser.Surname)\n}<\/code><\/pre>\n\n\n\n<p>Output looks like<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>User:  {\"firstName\":\"Saurabh\",\"lastName\":\"Sharma\",\"userName\":\"saurabh@samarthya.me\",\"address\":\"Auzzieland\"}\n Name :  Saurabh   Sharma<\/code><\/pre>\n\n\n\n<p>Having understood the Handlers and <code>Marshaling<\/code> let&#8217;s add some actual code.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>Helpful <a href=\"https:\/\/golang.org\/doc\/effective_go.html#initialization\">link<\/a><\/p><\/blockquote>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ userList Slice of users that will be returned for the GET Rest call.\nvar userList &#91;]User\n\n\/\/ init Initialized\nfunc init() {\n\tuserList = &#91;]User{\n\t\t{\n\t\t\tName:       \"Saurabh\",\n\t\t\tMiddlename: \"\",\n\t\t\tSurname:    \"Sharma\",\n\t\t\tEmail:      \"saurabh@samarthya.me\",\n\t\t\tAddress:    \"Auzzieland\",\n\t\t},\n\t\t{\n\t\t\tName:       \"Gaurav\",\n\t\t\tMiddlename: \"M\",\n\t\t\tSurname:    \"Sharma\",\n\t\t\tEmail:      \"iam@gaurav.me\",\n\t\t\tAddress:    \"Swaziland\",\n\t\t},\n\t\t{\n\t\t\tName:       \"Bhanuni\",\n\t\t\tMiddlename: \"\",\n\t\t\tSurname:    \"Sharma\",\n\t\t\tEmail:      \"bhanuni@bhanuni.in\",\n\t\t\tAddress:    \"Papaland\",\n\t\t},\n\t}\n}<\/code><\/pre>\n\n\n\n<p>Each source file can define its own niladic <code>init<\/code> function to set up whatever state is required. (Actually each file can have multiple <code>init<\/code> functions.) And finally <code>init<\/code> is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized.<\/p>\n\n\n\n<p>I will now define a Handler that will process the HTTP methods (GET and POST) for a defined pattern.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ handleUsers Will expose this API to handle user commands\nfunc handleUsers(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Handlers can handle request with multiple request methods.\n\n\t\/\/ Every request has a method a simple string\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\tlog.Println(\" GET: called\")\n\t\tb, err := json.Marshal(userList)\n\t\tif err != nil {\n\t\t\t\/\/ Error while unmarshaling\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n                w.WriteHeader(http.StatusOK)\n\t\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\t\tw.Write(b)\n\t\t\n\t\treturn\n\n\tcase http.MethodPost:\n\t\tlog.Println(\" POST: called\")\n\tdefault:\n\t\tlog.Println(\" Not supported\")\n\t}\n\n}<\/code><\/pre>\n\n\n\n<p>From the source code <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Request struct {\n    \/\/ Method specifies the HTTP method (GET, POST, PUT, etc.).\n    \/\/ For client requests, an empty string means GET.\n    \/\/\n    \/\/ Go's HTTP client does not support sending a request with\n    \/\/ the CONNECT method. See the documentation on Transport for\n    \/\/ details.\n    Method string<\/code><\/pre>\n\n\n\n<p>I am reading the <code>METHOD<\/code> in the switch and if it GET I will return the <code>userList<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>b, err := json.Marshal(userList)\nif err != nil {\n\t\/\/ Error while unmarshaling\n\tw.WriteHeader(http.StatusInternalServerError)\n\treturn\n}<\/code><\/pre>\n\n\n\n<p>As shown above we simply <code>Marshal<\/code> the userList that we have initialized and in case of any error we will return the <code>StatusInternalServerError<\/code> otherwise<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>w.WriteHeader(http.StatusOK)\nw.Header().Add(\"Content-Type\", \"application\/json\")\nw.Write(b)\nreturn<\/code><\/pre>\n\n\n\n<p>We define the Header &amp; write the <code>byte []<\/code> and return.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>HTTP\/1.1 200 OK\nContent-Type: application\/json\nDate: Sat, 16 May 2020 11:06:44 GMT\nContent-Length: 308<\/code><\/pre>\n\n\n\n<p>the Response body<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;\n\n    {\n        \"firstName\": \"Saurabh\",\n        \"lastName\": \"Sharma\",\n        \"userName\": \"saurabh@samarthya.me\",\n        \"address\": \"Auzzieland\"\n    },\n    {\n        \"firstName\": \"Gaurav\",\n        \"middleName\": \"M\",\n        \"lastName\": \"Sharma\",\n        \"userName\": \"iam@gaurav.me\",\n        \"address\": \"Swaziland\"\n    },\n    {\n        \"firstName\": \"Bhanuni\",\n        \"lastName\": \"Sharma\",\n        \"userName\": \"bhanuni@bhanuni.in\",\n        \"address\": \"Papaland\"\n    }\n\n]<\/code><\/pre>\n\n\n\n<p>Let&#8217;s modify some code and handle other methods.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func handleUsers(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Handlers can handle request with multiple request methods.\n\n\t\/\/ Every request has a method a simple string\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\tlog.Println(\" GET: called\")\n\t\tb, err := json.Marshal(userList)\n\t\tif err != nil {\n\t\t\t\/\/ Error while unmarshaling\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\t\tw.Write(b)\n\n\tcase http.MethodPost:\n\t\tlog.Println(\" POST: called\")\n\t\tw.WriteHeader(http.StatusCreated)\n\t\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\t\tw.Write(&#91;]byte(\"User added\"))\n\n\tdefault:\n\t\tlog.Printf(\" Method: %s\\n\", r.Method)\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\t\tw.Write(&#91;]byte(\"method not supported\"))\n\t\tlog.Println(\" Not supported\")\n\t}\n\n}<\/code><\/pre>\n\n\n\n<p>Let&#8217;s try sending a <code>PUT<\/code> request<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>> PUT \/users HTTP\/1.1\n> Host: localhost:8090\n> User-Agent: insomnia\/7.1.1\n> Accept: *\/*\n> Content-Length: 0\n\n&lt; HTTP\/1.1 405 Method Not Allowed\n&lt; Date: Sat, 16 May 2020 11:21:40 GMT\n&lt; Content-Length: 20\n&lt; Content-Type: text\/plain; charset=utf-8<\/code><\/pre>\n\n\n\n<p>Sending a POST request<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>> POST \/users HTTP\/1.1\n> Host: localhost:8090\n> User-Agent: insomnia\/7.1.1\n> Accept: *\/*\n> Content-Length: 0\n\n&lt; HTTP\/1.1 201 Created\n&lt; Date: Sat, 16 May 2020 11:27:13 GMT\n&lt; Content-Length: 10\n&lt; Content-Type: text\/plain; charset=utf-8<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"1024\" height=\"106\" src=\"https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2020\/05\/Screenshot-2020-05-16-at-4.57.56-PM-1024x106.png\" alt=\"\" class=\"wp-image-679\" srcset=\"https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2020\/05\/Screenshot-2020-05-16-at-4.57.56-PM-1024x106.png 1024w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2020\/05\/Screenshot-2020-05-16-at-4.57.56-PM-300x31.png 300w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2020\/05\/Screenshot-2020-05-16-at-4.57.56-PM-768x80.png 768w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2020\/05\/Screenshot-2020-05-16-at-4.57.56-PM-1536x159.png 1536w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2020\/05\/Screenshot-2020-05-16-at-4.57.56-PM-2048x213.png 2048w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption>POST<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Post: To add <\/h3>\n\n\n\n<p>I have added on the structure and Post handler to add a user passed along with the request.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type User struct {\n\tId         int    `json:\"id\"`\n\tName       string `json:\"firstName\"`\n\tMiddlename string `json:\"middleName,omitempty\"`\n\tSurname    string `json:\"lastName\"`\n\tEmail      string `json:\"userName\"`\n\tAddress    string `json:\"address\"`\n}<\/code><\/pre>\n\n\n\n<p>You can see I have added a new field <code>Id<\/code>, and also have modified the <code>POST<\/code> handler.<\/p>\n\n\n\n<p>Added a JSON converter utility function as under<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ JSON representation of a user.\nfunc jsonUser(user User) &#91;]byte {\n\tb, err := json.Marshal(user)\n\tif err != nil {\n\t\t\/\/ Error while unmarshaling\n\t\treturn &#91;]byte(\"\")\n\t}\n\treturn b\n}<\/code><\/pre>\n\n\n\n<p>Now modifying for post in the <code>switch<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>case http.MethodPost:\n\t\tlog.Println(\" POST: called\")\n\t\tvar newUser User\n\t\te, er := ioutil.ReadAll(r.Body)\n\t\tif er != nil {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\ter = json.Unmarshal(e, &amp;newUser)\n\t\tif er != nil {\n\t\t\t\/\/ Error unmarsheling the data\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t}\n\n\t\tfmt.Printf(\" User : %s\", newUser.Email)\n\n\t\tuserList = append(userList, newUser)\n\t\tw.WriteHeader(http.StatusCreated)\n\t\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\t\tw.Write(jsonUser(newUser))<\/code><\/pre>\n\n\n\n<p>Few additions<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>I am using <code>ioutil.ReadAll<\/code> to read the request body<ul><li>In case of error I return a <code>Bad Request<\/code> error.<\/li><\/ul><\/li><li>Unmarshal the <code>byte []<\/code> to a new user<\/li><li>This <code>newUser<\/code> is added to the slice.<\/li><li>I return the <code>newUser<\/code> along with the <code>Status Created<\/code> code.<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>> POST \/users HTTP\/1.1\n> Host: localhost:8090\n> User-Agent: insomnia\/7.1.1\n> Content-Type: application\/json\n> Accept: *\/*\n> Content-Length: 159\n\n| { \n| \t\"id\" : 6,\n| \t\"firstName\": \"Samarthya\",\n| \t\"middlename\": \"Saurabh\",\n| \t\"lastName\":    \"Sharma\",\n| \t\"userName\":      \"sam@samarthya.me\",\n| \t\"address\":    \"Anglet\u00e9re\"\n| }\n\n* upload completely sent off: 159 out of 159 bytes\n\n&lt; HTTP\/1.1 201 Created\n&lt; Date: Sat, 16 May 2020 13:12:48 GMT\n&lt; Content-Length: 127\n&lt; Content-Type: text\/plain; charset=utf-8<\/code><\/pre>\n\n\n\n<h4 class=\"has-text-align-center wp-block-heading\">&#8212; THE &#8211; END &#8212;<\/h4>\n","protected":false},"excerpt":{"rendered":"<p>Having practiced creating loads of Console based programs of golang, it is now time to try something new &#8211; A Web Service. In this blog, I will try and create a Web Service (RESTful) that will be built entirely on Go. Weapons of choice Visual studio code (I like it) GO &#8211; 1.14 As I [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":665,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"image","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"footnotes":""},"categories":[34],"tags":[23,70,69],"class_list":["post-659","post","type-post","status-publish","format-image","has-post-thumbnail","hentry","category-technical","tag-golang","tag-rest","tag-ws","post_format-post-format-image"],"_links":{"self":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/659","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/comments?post=659"}],"version-history":[{"count":0,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/659\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media\/665"}],"wp:attachment":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media?parent=659"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/categories?post=659"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/tags?post=659"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}