forked from mbach04/meeseeks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
meeseeks.go
80 lines (68 loc) · 1.96 KB
/
meeseeks.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 (
"log"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/spf13/viper"
"github.com/mbach04/meeseeks/handlers"
"github.com/kabukky/httpscerts"
)
func main() {
log.SetFlags(log.LstdFlags)
router := mux.NewRouter().StrictSlash(true)
v1, err := readConfig("meeseeks", map[string]interface{}{
"api_port": 8080,
"debug": true,
"tls_cert": "cert.pem",
"tls_key": "key.pem",
})
if err != nil {
log.Println("Error reading config file:", err)
}
// Store CONFIG info
debug := v1.GetBool("debug")
apiPort := v1.GetString("API_PORT")
cert := v1.GetString("tls_cert")
key := v1.GetString("tls_key")
// Dump CONFIG info to Log
log.Println("DEBUG:", debug)
log.Println("API_PORT:", apiPort)
log.Println("CERT", cert)
log.Println("KEY", key)
// Check if the cert files are available.
err = httpscerts.Check(cert, key)
// If they are not available, generate new ones.
if err != nil {
err = httpscerts.Generate(cert, key, "localhost:" + apiPort)
if err != nil {
log.Fatal("Error: Couldn't create https certs.")
}
}
srv := &http.Server{
Handler: router,
Addr: ":" + apiPort,
// Good practice: enforce timeouts for servers
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
//namespace all api calls with base of <host>:<port>/api/v1
sub := router.PathPrefix("/api/v1").Subrouter()
//API Endpoints
sub.Methods("GET").Path("/hello").HandlerFunc(handlers.GetHello)
sub.Methods("POST").Path("/command").HandlerFunc(handlers.RunCommand)
sub.Methods("POST").Path("/ls").HandlerFunc(handlers.LsCmd)
log.Println("Listening on:", apiPort)
log.Fatal(srv.ListenAndServeTLS(cert, key))
}
func readConfig(filename string, defaults map[string]interface{}) (*viper.Viper, error) {
v := viper.New()
for key, value := range defaults {
v.SetDefault(key, value)
}
v.SetConfigName(filename)
v.AddConfigPath(".")
v.AutomaticEnv()
err := v.ReadInConfig()
return v, err
}