aboutsummaryrefslogtreecommitdiffstats
path: root/cmd/serve.go
blob: 51fc0045e8ce47d1347d383e2a4e0a8c1b14c13b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/* guestbook - Standalone guestbook server for static websites
 * Copyright (C) 2025  Vidhu Kant Sharma <vidhukant@vidhukant.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package cmd

import (
	"fmt"
	"log"
	"net/http"

	"vidhukant.com/guestbook/db"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var serveCmd = &cobra.Command{
	Use:   "serve",
	Short: "Start the guestbook server",
	Long:  "Start the guestbook server",
	Run: func(cmd *cobra.Command, args []string) {
		guestbookName, err := cmd.Flags().GetString("guestbook")
		if err != nil {
			log.Fatal(err)
		}

		port := viper.GetString(guestbookName + ".port")
		validationString := viper.GetString(guestbookName + ".validation_string")

		path := viper.GetString(guestbookName + ".path")
		if path == "/" {
			log.Fatalf("Setting %s.path to / is not allowed as it may cause issues.", guestbookName)
		}

		successRedirect := viper.GetString(guestbookName + ".success_redirect")
		if successRedirect == "" {
			log.Fatalf("%s.success_redirect cannot be blank.", guestbookName)
		}

		errorRedirect := viper.GetString(guestbookName + ".error_redirect")
		if errorRedirect == "" {
			log.Fatalf("%s.error_redirect cannot be blank.", guestbookName)
		}


		conn := db.Connect()
		defer conn.Close()

		_, err = conn.Exec(
			fmt.Sprintf(
				"CREATE TABLE IF NOT EXISTS %s (" +
				"id INT AUTO_INCREMENT PRIMARY KEY," +
				"name TEXT," +
				"website TEXT," +
				"message TEXT" +
				");",
				guestbookName,
			),
		)
		if err != nil {
			log.Fatalf("Error while creating table: %v\n", err)
		}

		http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
			if r.Method != http.MethodPost {
			    http.Redirect(w, r, errorRedirect, http.StatusSeeOther)
				return
			}

			var data db.GuestbookEntry
			err := r.ParseForm()
			data.Name = r.FormValue("name")
			data.Website = r.FormValue("website")
			data.Message = r.FormValue("message")
			data.Validation = r.FormValue("validation")

			if err != nil {
				log.Printf("Error occurred while decoding data: %v")
			    http.Redirect(w, r, errorRedirect, http.StatusSeeOther)
				return
			}

			if data.Validation != validationString || data.Name == "" || data.Message == "" {
			    http.Redirect(w, r, errorRedirect, http.StatusSeeOther)
				return
			}

			stmt, err := conn.Prepare(fmt.Sprintf("INSERT INTO %s (name, website, message) VALUES (?, ?, ?)", guestbookName))
			if err != nil {
				log.Printf("Error occurred while preparing statement data: %v\n")
			    http.Redirect(w, r, errorRedirect, http.StatusSeeOther)
				return
			}
			defer stmt.Close()

			_, err = stmt.Exec(data.Name, data.Website, data.Message)
			if err != nil {
				log.Printf("Error occurred while saving data: %v\n")
			    http.Redirect(w, r, errorRedirect, http.StatusSeeOther)
				return
			}

			http.Redirect(w, r, successRedirect, http.StatusSeeOther)
		})

		log.Printf("Guestbook %s listening to POST %s on PORT %s.\n", guestbookName, path, port)
		log.Fatal(http.ListenAndServe(":" + port, nil))
	},
}

func init() {
	rootCmd.AddCommand(serveCmd)

	serveCmd.Flags().StringP("guestbook", "g", "my_guestbook", "Guestbook name (defined in /etc/guestbook.toml)")
}