File tree Expand file tree Collapse file tree 3 files changed +79
-0
lines changed Expand file tree Collapse file tree 3 files changed +79
-0
lines changed Original file line number Diff line number Diff line change
1
+ module github.com/icabp-coderdojo-projects/go-rest-api
2
+
3
+ go 1.13
4
+
5
+ require github.com/go-chi/chi v4.0.3+incompatible
Original file line number Diff line number Diff line change
1
+ github.com/go-chi/chi v4.0.3+incompatible h1:gakN3pDJnzZN5jqFV2TEdF66rTfKeITyR8qu6ekICEY =
2
+ github.com/go-chi/chi v4.0.3+incompatible /go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ =
Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "encoding/json"
5
+ "fmt"
6
+ "net/http"
7
+ "strconv"
8
+ "time"
9
+
10
+ "github.com/go-chi/chi"
11
+ "github.com/go-chi/chi/middleware"
12
+ )
13
+
14
+ type Post struct {
15
+ Name string `json:"name"`
16
+ Body string `json:"body"`
17
+ }
18
+
19
+ type DB = map [int ]Post
20
+
21
+ var db DB
22
+
23
+ func (post * Post ) ToJSON () []byte {
24
+ js , _ := json .Marshal (post )
25
+ return js
26
+ }
27
+
28
+ func init () {
29
+ db = make (DB )
30
+ db [1 ] = Post {
31
+ Name : "Init" ,
32
+ Body : "body" ,
33
+ }
34
+ db [2000 ] = Post {
35
+ Name : "Init 2" ,
36
+ Body : "body 2" ,
37
+ }
38
+ }
39
+
40
+ func main () {
41
+ router := chi .NewRouter ()
42
+ router .Use (
43
+ middleware .Logger ,
44
+ middleware .RealIP ,
45
+ middleware .Timeout (60 * time .Second ),
46
+ )
47
+
48
+ router .Get ("/post/{id}" , GetPost )
49
+
50
+ http .ListenAndServe (":3000" , router )
51
+ }
52
+
53
+ func GetPost (w http.ResponseWriter , r * http.Request ) {
54
+ id_str := chi .URLParam (r , "id" )
55
+ var (
56
+ id int
57
+ err error
58
+ )
59
+ if id , err = strconv .Atoi (id_str ); err != nil {
60
+ http .Error (w , http .StatusText (500 ), 500 )
61
+ return
62
+ }
63
+ if post , ok := db [id ]; ok {
64
+ w .Header ().Add ("Content-Type" , "application/json" )
65
+ js := post .ToJSON ()
66
+ code , _ := w .Write (js )
67
+ fmt .Println (code )
68
+ return
69
+ } else {
70
+ http .Error (w , http .StatusText (404 ), 404 )
71
+ }
72
+ }
You can’t perform that action at this time.
0 commit comments