Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Node.js -> Go: Writing RESTful Web Services

Node.js -> Go: Writing RESTful Web Services

A super impromptu talk I gave during Gainesville Barcamp 2016 comparing writing a web service in golang to Node.js

Avatar for Jacob Jenkins

Jacob Jenkins

March 12, 2016

Other Decks in Programming

Transcript

  1. let Post = require('./post'); app.route('/posts/:postID').get((req, res) => { let postID

    = req.params.postID; Post .findById(postID) .exec((err, post) => { if (err) { res.status(500).send('Something went wrong!'); } else if (post) { res.jsonp(post); } else { res.status(404).send('The post does not exist.'); } }); });
  2. func handleSongs(rw http.ResponseWriter, rq *http.Request) { id := rq.URL.String()[len("/users/")] if

    id == "" { http.Error(rw, "Bad request", 400) } switch rq.Method { case "GET": result := Post{} err := dbs.posts().FindId(bson.ObjectIdHex(id)).One(&result) if err != nil { http.Error(w, "Something went wrong!", 500) } if result != nil { post, _ := json.Marshal(result) w.Write(post) } else { http.Error(w, "The requested post does not exist.", 404) } default: http.Error(rw, "Method not allowed", 405) } }
  3. func handleSongs(rw http.ResponseWriter, rq *http.Request) { id := rq.URL.String()[len("/users/")] if

    id == "" { http.Error(rw, "Bad request", 400) } // More code below... } GOLANG
  4. func handleSongs(rw http.ResponseWriter, rq *http.Request) { // More code above…

    switch rq.Method { case “GET”: // Handle GET default: http.Error(rw, "Method not allowed", 405) } } GOLANG
  5. Post .findById(postID) .exec((err, post) => { if (err) { res.status(500).send('Something

    went wrong!'); } else if (post) { res.jsonp(post); } else { res.status(404).send('The post does not exist.'); } NODE.JS
  6. case "GET": result := Post{} err := dbs.posts().FindId(bson.ObjectIdHex(id)).One(&result) if err

    != nil { http.Error(w, "Something went wrong!", 500) } if result != nil { post, _ := json.Marshal(result) w.Write(post) } else { http.Error(w, "The requested post does not exist.", 404) } GOLANG
  7. FIN