forked from spencerkinney/go-url-shortener
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
50 lines (40 loc) · 1.11 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
package main
import (
"log"
"os"
handlers "go-url-shortener/handlers"
"github.com/valyala/fasthttp"
)
func main() {
requestHandler := func(ctx *fasthttp.RequestCtx) {
// Set CORS headers
setCORSHeaders(ctx)
// Handle preflight requests
if string(ctx.Method()) == "OPTIONS" {
// Preflight request only needs headers
ctx.SetStatusCode(fasthttp.StatusOK)
return
}
path := string(ctx.Path())
switch path {
case "/shorten":
handlers.ShortenHandler(ctx)
default:
handlers.HomeOrRedirectHandler(ctx)
}
}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Println("listening on port", port)
if err := fasthttp.ListenAndServe(":"+port, requestHandler); err != nil {
log.Fatalf("Error in ListenAndServe: %v", err)
}
}
func setCORSHeaders(ctx *fasthttp.RequestCtx) {
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
ctx.Response.Header.Set("Access-Control-Allow-Credentials", "true")
ctx.Response.Header.Set("Access-Control-Allow-Headers", "Authorization, Accept, Content-Type")
ctx.Response.Header.Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
}