I have been programming Go for 3 days now, I am a complete beginner when it comes to this. But I really like the language, and seems a lot easier than C to learn. I love the neatness and everything about it.
My question is, I am building a API to upload files to a database, and also a endpoint which you see below that searches the database.
I am wondering if this is the correct way in Go to serve a JSON response code for a error. Or is there a more advanced way to set up my if else statements if a error occurs. I am trying to build this the correct way. But this is my code, 100%. So I am open for ideas thanks.
I am wondering if there is a way to do what I am doing more efficiently.
package main
import (
"net/http"
"log"
"http://ift.tt/J9WoXt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"encoding/json"
)
type Result struct {
ID string
URL string
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/view", View).Methods("GET")
log.Fatal(http.ListenAndServe(":4000", router))
}
func View(w http.ResponseWriter, r *http.Request) {
id := r.FormValue("id")
if len(id) > 1 {
session, err := mgo.Dial("mongodb://")
if err != nil {
// Server Error
status := map[string]int{"Error": 500}
js, _ := json.Marshal(status)
w.WriteHeader(500)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
return
} else {
defer session.Close()
session.SetMode(mgo.Monotonic, true)
collection := session.DB("api").C("uploads")
item := Result{}
err = collection.Find(bson.M{"id": id}).One(&item)
if err != nil {
// Database Empty
status := map[string]int{"Error": 204}
js, _ := json.Marshal(status)
w.WriteHeader(204)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
return
} else {
js, err := json.Marshal(&item)
if err != nil {
// Server Error
status := map[string]int{"Error": 500}
js, _ := json.Marshal(status)
w.WriteHeader(500)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
return
} else {
// Success
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
}
}
} else {
// Bad Request
status := map[string]int{"Error": 400}
js, _ := json.Marshal(status)
w.WriteHeader(400)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
return
}
}
Aucun commentaire:
Enregistrer un commentaire