-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
64 lines (51 loc) · 1.16 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"fmt"
"log"
"net/http"
"encoding/json"
"strconv"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"goapi-demo/config"
)
var cfg config.Config
var db *sql.DB
var jokeDb *JokeDb
func showJoke(c web.C, w http.ResponseWriter, r *http.Request) {
jokeId, err := strconv.Atoi(c.URLParams["jokeId"])
if err != nil {
log.Fatal(err)
}
joke, err := jokeDb.FetchJoke(jokeId)
switch {
case err == sql.ErrNoRows:
log.Printf("No joke with that ID.")
fmt.Fprint(w, "404")
case err != nil:
log.Fatal(err)
default:
sjson, _ := json.Marshal(joke)
fmt.Fprintf(w, string(sjson))
}
}
func init() {
var err error
cfg, err = config.NewFromFile("config.json")
if err != nil {
log.Fatal(err)
}
db, err = sql.Open("mysql", cfg.MySqlDsn)
if err != nil {
log.Fatal(err)
}
jokeDb = &JokeDb{db}
}
func main() {
goji.Use(ContentTypeJson)
goji.Get("/jokes/:jokeId", showJoke)
goji.Serve()
db.Close()
}