2021-03-09 08:05:07 +00:00
|
|
|
package website
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
2021-03-11 03:19:39 +00:00
|
|
|
"git.handmade.network/hmn/hmn/config"
|
2021-03-09 08:05:07 +00:00
|
|
|
"git.handmade.network/hmn/hmn/db"
|
2021-03-11 03:19:39 +00:00
|
|
|
"git.handmade.network/hmn/hmn/logging"
|
2021-03-09 08:05:07 +00:00
|
|
|
"github.com/julienschmidt/httprouter"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
|
|
|
var WebsiteCommand = &cobra.Command{
|
|
|
|
Short: "Run the HMN website",
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
2021-03-11 03:19:39 +00:00
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
if err, ok := r.(error); ok {
|
|
|
|
logging.Error().Err(err).Msg("recovered from panic")
|
|
|
|
} else {
|
|
|
|
logging.Error().Interface("recovered", r).Msg("recovered from panic")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
logging.Info().Msg("Hello, HMN!")
|
2021-03-09 08:05:07 +00:00
|
|
|
|
|
|
|
conn := db.NewConnPool(4, 8)
|
|
|
|
|
|
|
|
router := httprouter.New()
|
|
|
|
router.GET("/", func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
|
|
|
rw.Write([]byte("Hello, HMN!"))
|
|
|
|
})
|
|
|
|
router.GET("/project/:id", func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
|
|
|
id := p.ByName("id")
|
|
|
|
row := conn.QueryRow(context.Background(), "SELECT name FROM handmade_project WHERE id = $1", p.ByName("id"))
|
|
|
|
var name string
|
|
|
|
err := row.Scan(&name)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
rw.Write([]byte(fmt.Sprintf("(%s) %s\n", id, name)))
|
|
|
|
})
|
2021-03-11 03:19:39 +00:00
|
|
|
logging.Info().Str("addr", config.Config.Addr).Msg("Serving the website")
|
|
|
|
http.ListenAndServe(config.Config.Addr, router)
|
2021-03-09 08:05:07 +00:00
|
|
|
},
|
|
|
|
}
|