-
Notifications
You must be signed in to change notification settings - Fork 0
/
components.go
80 lines (63 loc) · 1.76 KB
/
components.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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
r *mux.Router
username string
password string
hostname string
dbname string
sidecarUrl string
)
func connectToCollection(w http.ResponseWriter) (context.Context, context.CancelFunc, *mongo.Client, *mongo.Collection, bool) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://"+username+":"+
password+"@"+hostname+":27017/"+dbname))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Could not connect to database")
return ctx, cancel, client, nil, false
}
return ctx, cancel, client, client.Database(dbname).Collection("components"), true
}
func main() {
log.SetFlags(0)
var exists bool
username = os.Getenv("DB_USER")
password = os.Getenv("DB_PASSWORD")
hostname = os.Getenv("DB_HOST")
dbname = os.Getenv("DB_NAME")
sidecarUrl, exists = os.LookupEnv("SIDECAR_URL")
if !exists {
log.Fatalln("No sidecar URL set")
}
r = mux.NewRouter()
r.HandleFunc("/api/", handleAPIRequest)
r.HandleFunc("/nr/{nr}", handleComponentsRequest)
r.HandleFunc("/edit/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
content, err := os.ReadFile("static/edit.html")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
msg := "Can not serve file"
fmt.Fprintf(w, msg)
log.Println(msg, err)
return
}
fmt.Fprintf(w, string(content))
})
log.Println("Components is listening on port 8080")
err := http.ListenAndServe(":8080", r)
if err != nil {
log.Fatalln("Components failed:", err)
}
}