Skip to content

Commit a7e23cb

Browse files
committed
first commit
1 parent 9b93fa1 commit a7e23cb

25 files changed

+1142
-0
lines changed

config.json

Whitespace-only changes.

go.mod

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module github.com/xueyuanjun/chitchat
2+
3+
go 1.13
4+
5+
require (
6+
github.com/go-sql-driver/mysql v1.5.0
7+
github.com/gorilla/mux v1.7.4
8+
)

go.sum

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
2+
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
3+
github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc=
4+
github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=

handlers/index.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package handlers
2+
3+
import (
4+
"github.com/xueyuanjun/chitchat/models"
5+
"html/template"
6+
"net/http"
7+
)
8+
9+
func Index(w http.ResponseWriter, r *http.Request) {
10+
files := []string{"views/layout.html", "views/navbar.html", "views/index.html",}
11+
templates := template.Must(template.ParseFiles(files...))
12+
threads, err := models.Threads();
13+
if err == nil {
14+
templates.ExecuteTemplate(w, "layout", threads)
15+
}
16+
}

main.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package main
2+
3+
import (
4+
. "github.com/xueyuanjun/chitchat/routes"
5+
"log"
6+
"net/http"
7+
)
8+
9+
func main() {
10+
startWebServer("8080")
11+
}
12+
13+
// 通过指定端口启动 Web 服务器
14+
func startWebServer(port string) {
15+
r := NewRouter() // 通过 router.go 中定义的路由器来分发请求
16+
17+
// 处理静态资源文件
18+
assets := http.FileServer(http.Dir("public"))
19+
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", assets))
20+
21+
http.Handle("/", r)
22+
23+
log.Println("Starting HTTP service at " + port)
24+
err := http.ListenAndServe(":" + port, nil) // 启动协程监听请求
25+
26+
if err != nil {
27+
log.Println("An error occured starting HTTP listener at port " + port)
28+
log.Println("Error: " + err.Error())
29+
}
30+
}

models/db.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package models
2+
3+
import (
4+
"crypto/rand"
5+
"crypto/sha1"
6+
"database/sql"
7+
"fmt"
8+
_ "github.com/go-sql-driver/mysql"
9+
"log"
10+
)
11+
12+
var Db *sql.DB
13+
14+
func init() {
15+
var err error
16+
Db, err = sql.Open("mysql", "root:root@/chitchat?charset=utf8&parseTime=true")
17+
if err != nil {
18+
log.Fatal(err)
19+
}
20+
return
21+
}
22+
23+
// create a random UUID with from RFC 4122
24+
// adapted from http://github.com/nu7hatch/gouuid
25+
func createUUID() (uuid string) {
26+
u := new([16]byte)
27+
_, err := rand.Read(u[:])
28+
if err != nil {
29+
log.Fatalln("Cannot generate UUID", err)
30+
}
31+
32+
// 0x40 is reserved variant from RFC 4122
33+
u[8] = (u[8] | 0x40) & 0x7F
34+
// Set the four most significant bits (bits 12 through 15) of the
35+
// time_hi_and_version field to the 4-bit version number.
36+
u[6] = (u[6] & 0xF) | (0x4 << 4)
37+
uuid = fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
38+
return
39+
}
40+
41+
// hash plaintext with SHA-1
42+
func Encrypt(plaintext string) (cryptext string) {
43+
cryptext = fmt.Sprintf("%x", sha1.Sum([]byte(plaintext)))
44+
return
45+
}

models/post.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package models
2+
3+
import "time"
4+
5+
type Post struct {
6+
Id int
7+
Uuid string
8+
Body string
9+
UserId int
10+
ThreadId int
11+
CreatedAt time.Time
12+
}
13+
14+
func (post *Post) CreatedAtDate() string {
15+
return post.CreatedAt.Format("Jan 2, 2006 at 3:04pm")
16+
}
17+
18+
// Get the user who wrote the post
19+
func (post *Post) User() (user User) {
20+
user = User{}
21+
Db.QueryRow("SELECT id, uuid, name, email, created_at FROM users WHERE id = ?", post.UserId).
22+
Scan(&user.Id, &user.Uuid, &user.Name, &user.Email, &user.CreatedAt)
23+
return
24+
}
25+

models/session.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package models
2+
3+
import "time"
4+
5+
type Session struct {
6+
Id int
7+
Uuid string
8+
Email string
9+
UserId int
10+
CreatedAt time.Time
11+
}
12+
13+
// Check if session is valid in the database
14+
func (session *Session) Check() (valid bool, err error) {
15+
err = Db.QueryRow("SELECT id, uuid, email, user_id, created_at FROM sessions WHERE uuid = ?", session.Uuid).
16+
Scan(&session.Id, &session.Uuid, &session.Email, &session.UserId, &session.CreatedAt)
17+
if err != nil {
18+
valid = false
19+
return
20+
}
21+
if session.Id != 0 {
22+
valid = true
23+
}
24+
return
25+
}
26+
27+
// Delete session from database
28+
func (session *Session) DeleteByUUID() (err error) {
29+
statement := "delete from sessions where uuid = ?"
30+
stmt, err := Db.Prepare(statement)
31+
if err != nil {
32+
return
33+
}
34+
defer stmt.Close()
35+
36+
_, err = stmt.Exec(session.Uuid)
37+
return
38+
}
39+
40+
// Get the user from the session
41+
func (session *Session) User() (user User, err error) {
42+
user = User{}
43+
err = Db.QueryRow("SELECT id, uuid, name, email, created_at FROM users WHERE id = ?", session.UserId).
44+
Scan(&user.Id, &user.Uuid, &user.Name, &user.Email, &user.CreatedAt)
45+
return
46+
}
47+
48+
// Delete all sessions from database
49+
func SessionDeleteAll() (err error) {
50+
statement := "delete from sessions"
51+
_, err = Db.Exec(statement)
52+
return
53+
}

models/thread.go

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package models
2+
3+
import "time"
4+
5+
type Thread struct {
6+
Id int
7+
Uuid string
8+
Topic string
9+
UserId int
10+
CreatedAt time.Time
11+
}
12+
13+
// format the CreatedAt date to display nicely on the screen
14+
func (thread *Thread) CreatedAtDate() string {
15+
return thread.CreatedAt.Format("Jan 2, 2006 at 3:04pm")
16+
}
17+
18+
// get the number of posts in a thread
19+
func (thread *Thread) NumReplies() (count int) {
20+
rows, err := Db.Query("SELECT count(*) FROM posts where thread_id = ?", thread.Id)
21+
if err != nil {
22+
return
23+
}
24+
for rows.Next() {
25+
if err = rows.Scan(&count); err != nil {
26+
return
27+
}
28+
}
29+
rows.Close()
30+
return
31+
}
32+
33+
// get posts to a thread
34+
func (thread *Thread) Posts() (posts []Post, err error) {
35+
rows, err := Db.Query("SELECT id, uuid, body, user_id, thread_id, created_at FROM posts where thread_id = ?", thread.Id)
36+
if err != nil {
37+
return
38+
}
39+
for rows.Next() {
40+
post := Post{}
41+
if err = rows.Scan(&post.Id, &post.Uuid, &post.Body, &post.UserId, &post.ThreadId, &post.CreatedAt); err != nil {
42+
return
43+
}
44+
posts = append(posts, post)
45+
}
46+
rows.Close()
47+
return
48+
}
49+
50+
// Get all threads in the database and returns it
51+
func Threads() (threads []Thread, err error) {
52+
rows, err := Db.Query("SELECT id, uuid, topic, user_id, created_at FROM threads ORDER BY created_at DESC")
53+
if err != nil {
54+
return
55+
}
56+
for rows.Next() {
57+
conv := Thread{}
58+
if err = rows.Scan(&conv.Id, &conv.Uuid, &conv.Topic, &conv.UserId, &conv.CreatedAt); err != nil {
59+
return
60+
}
61+
threads = append(threads, conv)
62+
}
63+
rows.Close()
64+
return
65+
}
66+
67+
// Get a thread by the UUID
68+
func ThreadByUUID(uuid string) (conv Thread, err error) {
69+
conv = Thread{}
70+
err = Db.QueryRow("SELECT id, uuid, topic, user_id, created_at FROM threads WHERE uuid = ?", uuid).
71+
Scan(&conv.Id, &conv.Uuid, &conv.Topic, &conv.UserId, &conv.CreatedAt)
72+
return
73+
}
74+
75+
// Get the user who started this thread
76+
func (thread *Thread) User() (user User) {
77+
user = User{}
78+
Db.QueryRow("SELECT id, uuid, name, email, created_at FROM users WHERE id = ?", thread.UserId).
79+
Scan(&user.Id, &user.Uuid, &user.Name, &user.Email, &user.CreatedAt)
80+
return
81+
}

0 commit comments

Comments
 (0)