-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
93 lines (76 loc) · 2.51 KB
/
main.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
package main
import (
"flag"
"github.com/isnandar1471/url_shortener/src/api"
"github.com/joho/godotenv"
"log"
"math/rand"
"net/http"
"os"
"strconv"
)
// Initialize in init function
var Port *int
var Host *string
func init() {
// Load environment variable
_ = godotenv.Load()
envPort, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
envPort = 5555
}
envHost := os.Getenv("HOST")
if envHost == "" {
envHost = "0.0.0.0"
}
envJwtKey := os.Getenv("JWT_KEY")
if envJwtKey == "" {
envJwtKey = randSeq(10)
}
Port = flag.Int("port", envPort, "The port that used to run the app")
Host = flag.String("host", envHost, "The host that used to run the app")
JwtKey := flag.String("jwt-key", envJwtKey, "The JWT Key that used to run the app")
flag.Parse()
_ = os.Setenv("JWT_KEY", *JwtKey)
}
func main() {
mux := http.NewServeMux()
//region Add api handler in this section
mux.HandleFunc("POST /api/register", enableCors(api.HandlePostRegister))
mux.HandleFunc("POST /api/login", enableCors(api.HandlePostLogin))
mux.HandleFunc("POST /api/check-user", enableCors(api.HandleGetCheckUserExist))
mux.HandleFunc("GET /api/shorts", enableCors(api.HandleGetShorts))
mux.HandleFunc("POST /api/short", enableCors(api.HandlePostShort))
mux.HandleFunc("PATCH /api/short/{short_code}", enableCors(api.HandlePatchShortByCode))
mux.HandleFunc("DELETE /api/short/{short_code}", enableCors(api.HandleDeleteShortByCode))
mux.HandleFunc("GET /api/short_clicks/{short_code}", enableCors(api.HandleGetShortClickByCode))
mux.HandleFunc("GET /{short_code}", enableCors(api.HandleGetGo))
// Sepertinya ini untuk mengatasi cors secara global. Perlu mencoba untuk yang secara spesifik
mux.HandleFunc("OPTIONS /", enableCors(func(w http.ResponseWriter, r *http.Request) {}))
//endregion
address := *Host + ":" + strconv.Itoa(*Port)
println("Server starting...", address)
server := http.Server{
Addr: address,
Handler: mux,
}
log.Fatal(server.ListenAndServe())
}
func randSeq(n int) string {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func enableCors(handler http.HandlerFunc) http.HandlerFunc {
println("enableCors otw")
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
println("enableCors jalan")
handler(w, r)
}
}