knowledgebase/journals/2023_11_29.md

2.8 KiB

  • Documentazione del package di logging strutturato slog #golang
  • Esercizi di calcolo algebrico #teaching
    • image.png{:height 491, :width 748}
  • Webinar per docenti tutor
  • Server #golang sviluppato con #llm Phind come prototipo per il server #Probo
  • import (
        "encoding/json"  
        "net/http"  
        "os"  
        "io/ioutil"  
        "math/rand"  
        "strconv"  
        "time"  
      )  
    
      type Payload struct {  
        Name string `json:"name"`  
        Email string `json:"email"`  
      }  
    
      func generateRandomID() string {  
        rand.Seed(time.Now().UnixNano())  
        id := ""  
        for i := 0; i < 6; i++ {  
            id += strconv.Itoa(rand.Intn(9) + 1)  
        }  
        return id  
      }  
    
      func createHandler(w http.ResponseWriter, r *http.Request) {  
        var p Payload  
        err := json.NewDecoder(r.Body).Decode(&p)  
        if err != nil {  
            http.Error(w, err.Error(), http.StatusBadRequest)  
            return  
        }  
        id := generateRandomID()  
        err = os.Mkdir(id, os.ModePerm)  
        if err != nil {  
            http.Error(w, err.Error(), http.StatusInternalServerError)  
            return  
        }  
        file, err := os.Create(id + "/payload.json")  
        if err != nil {  
            http.Error(w, err.Error(), http.StatusInternalServerError)  
            return  
        }  
        defer file.Close()  
        err = json.NewEncoder(file).Encode(p)  
        if err != nil {  
            http.Error(w, err.Error(), http.StatusInternalServerError)  
            return  
        }  
        response := map[string]string{"id": id}  
        json.NewEncoder(w).Encode(response)  
      }  
    
      func idHandler(w http.ResponseWriter, r *http.Request) {  
        id := r.URL.Path[1:]  
        file, err := ioutil.ReadFile(id + "/payload.json")  
        if err != nil {  
            http.Error(w, err.Error(), http.StatusInternalServerError)  
            return  
        }  
        w.Header().Set("Content-Type", "application/json")  
        w.Write(file)  
      }  
    
      func main() {  
        mux := http.NewServeMux()  
        mux.HandleFunc("/create", createHandler)  
        mux.HandleFunc("/", idHandler)  
        http.ListenAndServe(":8080", mux)  
      }