Skip to content

Commit

Permalink
better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
atomotic committed Mar 11, 2019
1 parent 82da188 commit ad66ed8
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 29 deletions.
5 changes: 3 additions & 2 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package main

import (
"database/sql"
"log"

"github.com/rs/zerolog/log"
)

// InitDB create the database table and indexes
func InitDB(dsn string) *sql.DB {
db, err := sql.Open("sqlite3", dsn)
if err != nil {
log.Fatal("error db")
log.Fatal().Msg("database init error")
}
statement, _ := db.Prepare(`CREATE TABLE IF NOT EXISTS annotations (
id INTEGER PRIMARY KEY,
Expand Down
68 changes: 45 additions & 23 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,19 @@ func List(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {

rows, err := db.Query("SELECT body FROM annotations where target=?", canvas[0])
if err != nil {
log.Fatal().Err(err)
log.Error().Err(err).Str("action", "list").Msg("db error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500"))
return
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&body)
if err != nil {
log.Fatal().Err(err)
log.Error().Err(err).Str("action", "list").Msg("db error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500"))
return
}
list.Resources = append(list.Resources, body)
}
Expand All @@ -56,30 +62,31 @@ func List(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
if err := enc.Encode(list); err != nil {
fmt.Println(err)
log.Error().Err(err).Str("action", "list").Str("canvas", canvas[0]).Msg("annotation list error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500"))
return
}

}

// Get retrieve a single annotation with database id
// TODO: retrieve with annotation id
// NOTE: just for test, not used by mirador
func Get(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
w.Header().Set("Content-Type", "application/json")

var body string
rows, err := db.Query("SELECT body FROM annotations where id=?", ps.ByName("id"))
err := db.QueryRow("SELECT body FROM annotations where id=?", ps.ByName("id")).Scan(&body)

if err != nil {
log.Fatal().Err(err)
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&body)
if err != nil {
log.Fatal().Err(err)
}
fmt.Fprintf(w, body)
log.Error().Err(err).Str("action", "get").Msg("db error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500"))
return
}

w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, body)
}

// Delete an annotation
Expand All @@ -89,14 +96,20 @@ func Delete(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
var anno string
err := db.QueryRow("SELECT body FROM annotations where annoid = ?", ps.ByName("id")).Scan(&anno)
if err != nil {
log.Fatal().Err(err)
log.Error().Err(err).Str("action", "delete").Msg("db error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500"))
return
}

_, err = db.Exec("DELETE FROM annotations where annoid=?", ps.ByName("id"))
if err != nil {
log.Fatal().Err(err)
log.Error().Err(err).Str("action", "delete").Msg("db error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500"))
return
}
log.Info().Str("annotation-id", ps.ByName("id")).Msg("deleted")
log.Info().Str("annotation_id", ps.ByName("id")).Str("action", "delete").Msg("")
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, anno)
}
Expand All @@ -106,14 +119,18 @@ func Create(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), 500)
log.Error().Err(err).Str("action", "create").Msg("")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500"))
return
}

var annotation Annotation
err = json.Unmarshal(body, &annotation)
if err != nil {
http.Error(w, err.Error(), 500)
log.Error().Err(err).Str("action", "create").Msg("")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500"))
return
}

Expand All @@ -122,7 +139,7 @@ func Create(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
AnnotationWithID, _ := json.Marshal(annotation)
statement, _ := db.Prepare("INSERT INTO annotations (annoid, created_at, target, manifest, body) VALUES (?, ?, ?, ?, ?)")
statement.Exec(annoid, time.Now(), annotation.Canvas(), annotation.Manifest(), AnnotationWithID)
log.Info().Str("annotation-id", annoid).Msg("create")
log.Info().Str("annotation_id", annoid).Str("action", "create").Msg("")

fmt.Fprintf(w, string(AnnotationWithID))
}
Expand All @@ -135,16 +152,21 @@ func Update(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), 500)
log.Error().Err(err).Str("action", "update").Msg("db error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500"))
return
}

_, err = db.Exec("UPDATE annotations SET body=? WHERE annoid=?", body, annoid)
if err != nil {
log.Fatal().Err(err)
log.Error().Err(err).Str("action", "update").Msg("db error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500"))
return
}

log.Info().Str("annotation-id", annoid).Msg("update")
log.Info().Str("annotation_id", annoid).Str("action", "update").Msg("")

fmt.Fprintf(w, string(body))
}
9 changes: 5 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/julienschmidt/httprouter"
_ "github.com/mattn/go-sqlite3"
"github.com/mitchellh/go-homedir"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/zserge/webview"
)
Expand All @@ -26,13 +27,13 @@ func init() {
}

func main() {
log.Logger = log.Output(os.Stdout)
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
db = InitDB(annotationsDB)
router := httprouter.New()

ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Error().Msg("server err")
log.Fatal().Err(err).Msg("server failed to start")
}
defer ln.Close()
go func() {
Expand All @@ -49,9 +50,9 @@ func main() {
fileServer.ServeHTTP(w, r)
})

log.Info().Msg("# listening on " + ln.Addr().String())
log.Info().Str("address", "http://"+ln.Addr().String()).Msg("server started")
if err := http.Serve(ln, router); err != nil {
log.Fatal().Err(err).Msg("Startup failed")
log.Fatal().Err(err).Msg("server failed to start")
}

}()
Expand Down

0 comments on commit ad66ed8

Please sign in to comment.