This repository was archived by the owner on Oct 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
90 lines (75 loc) · 1.84 KB
/
server.go
File metadata and controls
90 lines (75 loc) · 1.84 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
// standard library packages
"encoding/json"
"fmt"
"log"
"net/http"
"time"
// third party packages
"github.com/Pepeye/raion/api/user"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/render"
mgo "gopkg.in/mgo.v2"
)
const appname string = "raion"
const host string = "localhost"
const port string = ":3333"
// Message struct
type Message struct {
ID string `json:"id"`
Message string `json:"message"`
Server `json:"server,omitempty"`
CreatedAt time.Time `json:"createdat"`
}
// Server struct
type Server struct {
App string `json:"app"`
Host string `json:"host"`
Port string `json:"port"`
}
func main() {
// new router
app := chi.NewRouter()
// middleware
app.Use(middleware.RequestID)
app.Use(middleware.RealIP)
app.Use(middleware.Logger)
app.Use(middleware.Recoverer)
app.Use(middleware.URLFormat)
app.Use(render.SetContentType(render.ContentTypeJSON))
// get resources and set data session
users := user.Resource{Session: getSession()}
// public routes
app.Get("/", handlerFn)
app.Mount("/users", users.Routes())
// start server
// defer http.ListenAndServe(":3001", app)
fmt.Printf("[%s]: Server running...", appname)
err := http.ListenAndServe(host+port, app)
if err != nil {
log.Fatal("Serving: ", err)
}
}
// connect to mongodb
func getSession() *mgo.Session {
s, err := mgo.Dial("mongodb://localhost")
if err != nil {
panic(err)
}
s.SetMode(mgo.Monotonic, true)
return s
}
func handlerFn(res http.ResponseWriter, req *http.Request) {
// create a new message
msg := Message{
ID: "f80b342c-f90c-4804-9df1-faeb244ab9b8",
Message: "raion api",
Server: Server{appname, host, port},
CreatedAt: time.Now(),
}
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
json.NewEncoder(res).Encode(msg)
}