74 lines
1.3 KiB
Go
74 lines
1.3 KiB
Go
// TODO: READ, UNDERSTAND AND ALTER
|
|
|
|
package main
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
func main() {
|
|
connectDB()
|
|
|
|
r := chi.NewRouter()
|
|
|
|
// routes
|
|
r.Get("/quotes", getQuotes)
|
|
r.Post("/quotes", createQuote)
|
|
|
|
port := os.Getenv("PORT")
|
|
if port == "" {
|
|
port = "8080"
|
|
}
|
|
|
|
http.ListenAndServe(":"+port, r)
|
|
}
|
|
|
|
/*package main
|
|
|
|
import (
|
|
"fmt"
|
|
"encoding/json"
|
|
"net/http"
|
|
)
|
|
|
|
type Message struct {
|
|
Text string `json:"text"`
|
|
}
|
|
|
|
type User struct {
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
// POST method handler
|
|
func createUserHandler(w http.ResponseWriter, r *http.Request) {
|
|
var user User
|
|
// decode json from request body
|
|
err := json.NewDecoder(r.Body).Decode(&user)
|
|
if err != nil {
|
|
http.Error(w, "invalid JSON", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
response := Message{Text: "User created: " + user.Name}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(response)
|
|
}
|
|
|
|
// handler function
|
|
func helloHandler(w http.ResponseWriter, r *http.Request) {
|
|
response := Message{Text: "Hellow from Go API!"}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(response)
|
|
}
|
|
|
|
func main() {
|
|
http.HandleFunc("/hello", helloHandler)
|
|
http.HandleFunc("/createUser", createUserHandler)
|
|
fmt.Println("server running on http://localhost:8080")
|
|
http.ListenAndServe(":8080", nil)
|
|
}*/
|