-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (74 loc) · 1.98 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
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/csepulveda/http_to_s3_test/common"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/gorilla/mux"
"github.com/spf13/viper"
)
func main() {
viper.AutomaticEnv()
viper.SetDefault("ListeningAddr", "0.0.0.0:8080")
viper.SetDefault("BucketName", "mybucketr2")
handleRequests(viper.GetString("ListeningAddr"), viper.GetString("BucketName"))
}
func handleRequests(ListeningAddr, BucketName string) {
r := mux.NewRouter().StrictSlash(true)
r.HandleFunc("/putfile", putfile(BucketName)).Methods("POST")
server := &http.Server{
Addr: ListeningAddr,
ReadHeaderTimeout: 3 * time.Second,
Handler: r,
}
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}
func putfile(b string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
sess, err := createSession()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, "err: unable to create session\n")
return
}
content, err := common.ParseBody(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, "err: unable to parse content\n")
return
}
content.Bucket = b
result, err := common.CreateFile(content, sess)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, "err: unable to create file\n")
return
}
err = json.NewEncoder(w).Encode(result)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, "err: unable to parse result\n")
return
}
}
}
func createSession() (*session.Session, error) {
viper.AutomaticEnv()
viper.SetDefault("AWSRegion", "us-west-2")
sess, err := session.NewSession(&aws.Config{
Region: aws.String(viper.GetString("AWSRegion"))},
)
if err != nil {
fmt.Printf("Unable create session, %v", err)
return nil, err
}
return sess, nil
}