I am trying to learn Backend development by building a vary basic REST API using gorilla mux library in Go (following this tutorial)
Here's the code that I have built so far:
package main
import (
"encoding/json"
"net/http"
"github.com/gorilla/mux"
)
// Post represents single post by user
type Post struct {
Title string `json:"title"`
Body string `json:"body"`
Author User `json:"author"`
}
// User is struct that represnets a user
type User struct {
FullName string `json:"fullName"`
Username string `json:"username"`
Email string `json:"email"`
}
var posts []Post = []Post{}
func main() {
router := mux.NewRouter()
router.HandleFunc("/posts", addItem).Methods("POST")
http.ListenAndServe(":5000", router)
}
func addItem(w http.ResponseWriter, req *http.Request) {
var newPost Post
json.NewDecoder(req.Body).Decode(&newPost)
posts = append(posts, newPost)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(posts)
}
However, I'm really confused about what exactly is happening in json.NewDecoder
and json.NewEncoder
part.
As far as I understand, ultimately data transfer over internet in a REST API will happen in form of bytes/binary format (encoded in UTF-8 i guess?). So json.NewEncoder
is converting Go data strcuture to JSON string and json.NewDecoder
is doing the opposite (correct me if i'm wrong).
- So who is responsible here for converting this JSON string to UTF-8
encoding for data transfer? Is that also part of what
json.NewDecoder
andjson.NewEncoder
do? - Also, if these 2 functions are only serializing/de-serializing
to/from JSON, why the name encoder and decoder (isn't encoding
always related to binary data conversion?). Honestly i'm pretty confused with the terms
encoding
,serialization
,marshaling
and the difference between them
Can someone just explain how exactly is data transfer happening here at each conversion level (json, binary, in-memory data structure)?
json.NewEncoder
is also converting the JSON string to its UTF-8 encoding? Because this is a JSON string :"{'name': 'John'}"
and this is it's UTF-8 encoding:\x20\x22\x7b\x27\x6e\x61\x6d\x65\x27\x3a\x20\x27\x4a\x6f\x68\x6e\x27\x7d\x22
They aren't the same obviously. – D_S_X"{'name': 'John'}"
is its UTF-8 encoding. Bytes up to127
are the same in ASCII and UTF-8. – Adrianencoding/json
documentation states that it follows the JSON spec (RFC 7195). – AdrianGET
request:Golang Data structure -> JSON -> UTF-8 -> Binary ------- data transfer over wire -------- Binary -> UTF-8 -> JSON -> JSON.parse in broswer
Now this question might be far-fetched but who exactly is responsible for converting to/from binary data here. Also can you elaborate more on what you mean by every data is bytes? – D_S_X