This repository has been archived by the owner on Jun 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
91 lines (84 loc) · 1.57 KB
/
server.go
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
package main
import (
"net"
"log"
"os"
"strings"
"io"
)
const (
IndexPage = "index.html"
)
type Server struct {
Port string
WebRoot string
Workers int
}
func NewServer(port, webRoot string, workers int) *Server {
return &Server{
Port: port,
WebRoot: webRoot,
Workers: workers,
}
}
func (s *Server) ListenAndServe() {
ln, err := net.Listen("tcp", s.Port)
if err != nil {
log.Fatalln("server start error:", err)
}
dispatcher := NewDispatcher(s.Workers)
dispatcher.Run()
log.Println("server started on port:", s.Port)
for {
conn, err := ln.Accept()
if err != nil {
log.Fatalln("accept connection error:", err)
}
job := Job{
Conn: conn,
WorkerFunc: s.serve,
}
JobQueue <- job
}
}
func (s *Server) serve(conn net.Conn) {
defer conn.Close()
req, resp := new(Request), &Response{
Code: StatusOk,
Description: "OK",
}
err := req.Parse(conn)
if err != nil {
if err == io.EOF {
resp.WriteCommonHeaders(conn)
return
}
resp.BuildErrResp(err)
resp.WriteCommonHeaders(conn)
return
}
var isIndex = strings.HasSuffix(req.AbsPath, "/")
if isIndex {
req.AbsPath += IndexPage
}
f, err := os.Open(s.WebRoot + req.AbsPath)
defer f.Close()
if err != nil {
if isIndex {
resp.BuildErrResp(ErrForbidden)
} else {
resp.BuildErrResp(ErrNotFound)
}
resp.WriteCommonHeaders(conn)
return
}
s.serveMethod(req.Method, resp, conn, f)
}
func (s *Server) serveMethod(method string, resp *Response, conn net.Conn, f *os.File) {
switch method {
case Get:
resp.WriteBody(conn, f)
case Head:
resp.Write(conn, f)
}
}