Commit de472b06 authored by Lukas Böhm's avatar Lukas Böhm 🎱
Browse files

add the go code

parent 446019a1
package main
import (
"encoding/json"
"fmt"
"github.com/google/uuid"
"github.com/gorilla/mux"
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
)
/////////////////////////////////
//////////// routes /////////////
/////////////////////////////////
func allShares(w http.ResponseWriter, r *http.Request) {
db := getDatabase()
var shares []Share
db.Where("is_public = ?", 1).Find(&shares)
sendJSON(w, shares)
}
func getShare(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
db := getDatabase()
var share Share
db.Where("ID = ?", vars["id"]).Find(&share)
fmt.Println(share)
sendJSON(w, share)
}
func addShare(w http.ResponseWriter, r *http.Request) {
db := getDatabase()
var newShare Share
json.NewDecoder(r.Body).Decode(&newShare)
db.Create(newShare)
sendJSON(w, nil)
}
func allAttachments(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
db := getDatabase()
var att Attachment
db.Where("share_id = ?", vars["id"]).Find(&att)
sendJSON(w, att)
}
func getAttachment(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
db := getDatabase()
var att Attachment
db.Where("share_id = ?", vars["id"]).Where("id = ?", vars["att"]).Find(&att)
sendJSON(w, att)
}
func addAttachment(w http.ResponseWriter, r *http.Request) {
db := getDatabase()
fmt.Fprintf(w, "Uploading File")
r.ParseMultipartForm(10 << 20) // Maximum 10 MB in RAM
file, handler, err := r.FormFile("myFile")
if err != nil {
fmt.Println("Error Retrieving the File")
fmt.Println(err)
return
}
defer file.Close()
vars := mux.Vars(r)
shareId, err := uuid.Parse(vars["id"])
if err != nil {
fmt.Println(err)
}
// create attachment in db
db.Create(&Attachment{
Filename: handler.Filename,
Filesize: handler.Size,
ShareID: shareId,
})
// save file
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)
}
err = ioutil.WriteFile(filepath.Join("media", vars["id"], handler.Filename), fileBytes, 0777)
if err != nil {
fmt.Println(err)
}
fmt.Fprintf(w, "Successfully Uploaded File\n")
}
/////////////////////////////////
////////// functions ////////////
/////////////////////////////////
func test(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL)
fmt.Println("Hallo Welt")
sendJSON(w, nil)
}
func configureRoutes() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", test)
router.HandleFunc("/shares", allShares).Methods("GET")
router.HandleFunc("/shares", addShare).Methods("POST")
router.HandleFunc("/share/{id}", getShare).Methods("GET")
router.HandleFunc("/share/{id}/attachments", allAttachments).Methods("GET")
router.HandleFunc("/share/{id}/attachments", addAttachment).Methods("POST")
router.HandleFunc("/share/{id}/attachment/{att}", getAttachment).Methods("GET")
log.Fatal(http.ListenAndServe(":6969", router))
}
func getDatabase()(db *gorm.DB) {
dsn := os.Getenv("DATABASE_URI")
db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
return
}
func sendJSON(w http.ResponseWriter, res interface{}) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
json.NewEncoder(w).Encode(res)
}
package main
import (
"time"
"github.com/google/uuid"
)
type Share struct {
ID uuid.UUID `gorm:"unique; not null"` //`gorm:"type:uuid;default:uuid_generate_v4()"`
Name string
Expires time.Time
DownloadLimit int
IsPublic bool `gorm:"not null; default:false; index"`
Password string
IsZipped bool `gorm:"not null; default:false"`
Attachments []Attachment `gorm:"foreignKey:ShareID; constraint:OnDelete:CASCADE"`
}
type Attachment struct {
ID uint `gorm:"primaryKey; unique; autoincrement; not null"`
Filename string `gorm:"not null"`
Filesize int64 `gorm:"not null; default:0"`
ShareID uuid.UUID `gorm:"not null"`
}
module chiefsend-api
go 1.16
require (
github.com/google/uuid v1.2.0
github.com/gorilla/mux v1.8.0
gorm.io/driver/sqlserver v1.0.6
gorm.io/gorm v1.21.2
)
github.com/denisenkom/go-mssqldb v0.0.0-20200428022330-06a60b6afbbc/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
gorm.io/driver/sqlserver v1.0.6/go.mod h1:+DhmnmNftPZOMOTkyLcs+WU5l6Q82TlTDy8skoKb5V8=
gorm.io/gorm v1.20.11/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.21.2/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
package main
import "fmt"
func main() {
db := getDatabase()
// Migrate the schema
db.AutoMigrate(&Attachment{})
db.AutoMigrate(&Share{})
fmt.Println("Let's go!!!")
configureRoutes()
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment