forked from signalfx/tracing-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
104 lines (86 loc) · 2.23 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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
echotrace "github.com/signalfx/signalfx-go-tracing/contrib/labstack/echo"
"github.com/signalfx/signalfx-go-tracing/tracing"
"net/http"
"os"
"strconv"
"github.com/labstack/echo"
)
const (
// ServiceName contains name of this service. This will show up on traces
DefaultServiceName = "simple-crud-api"
// TracingEndpoint contains a url to send traces
DefaultTracingEndpoint = "http://localhost:9080/v1/trace"
)
type (
entry struct {
ID int `json:"id"`
Record interface{} `json:"record"`
}
)
var (
records = map[int]*entry{}
seq = 1
)
// Creates a new record
func createRecord(c echo.Context) error {
u := &entry{
ID: seq,
}
err := c.Bind(u)
if err != nil {
return c.JSON(http.StatusBadRequest, "Invalid input")
}
records[u.ID] = u
seq++
return c.JSON(http.StatusCreated, u)
}
// Gets a record corresponding to the id
func getRecord(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if records[id] == nil {
return c.JSON(http.StatusNotFound, "Record not found")
}
return c.JSON(http.StatusOK, records[id])
}
// Updates the record corresponding to the id
func updateRecord(c echo.Context) error {
u := new(entry)
if err := c.Bind(u); err != nil {
return err
}
id, _ := strconv.Atoi(c.Param("id"))
if records[id] == nil {
return c.JSON(http.StatusNotFound, "Record not found")
}
records[id].Record = u.Record
return c.JSON(http.StatusOK, records[id])
}
// Deletes the record corresponding to the id
func deleteRecord(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
delete(records, id)
return c.NoContent(http.StatusNoContent)
}
func main() {
tracingEndpoint := os.Getenv("ECHO_TRACING_ENDPOINT")
if tracingEndpoint == "" {
tracingEndpoint = DefaultTracingEndpoint
}
serviceName := os.Getenv("ECHO_SERVICE_NAME")
if serviceName == "" {
serviceName = DefaultServiceName
}
tracing.Start(tracing.WithEndpointURL(tracingEndpoint), tracing.WithServiceName(serviceName))
defer tracing.Stop()
e := echo.New()
e.Use(echotrace.Middleware())
// Routes
e.POST("/records", createRecord)
e.GET("/records/:id", getRecord)
e.PUT("/records/:id", updateRecord)
e.DELETE("/records/:id", deleteRecord)
// Start server
e.Logger.Fatal(e.Start(":1323"))
}