go for it
This commit is contained in:
parent
3767be9f67
commit
c107d94b11
5 changed files with 137 additions and 1 deletions
30
server/handler.go
Normal file
30
server/handler.go
Normal file
|
@ -0,0 +1,30 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
)
|
||||
|
||||
func handleConnection(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
reader := bufio.NewReader(conn)
|
||||
request, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
fmt.Println("read request error:", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("request:", request)
|
||||
|
||||
response := "HTTP/1.1 200 OK\r\n" +
|
||||
"Content-Length: 13\r\n" +
|
||||
"Content-Type: text/plain\r\n\r\n" +
|
||||
"Hello, world!"
|
||||
|
||||
conn.Write([]byte(response))
|
||||
}
|
33
server/server.go
Normal file
33
server/server.go
Normal file
|
@ -0,0 +1,33 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
addr string
|
||||
}
|
||||
|
||||
func NewServer(addr string) *Server {
|
||||
return &Server{addr: addr}
|
||||
}
|
||||
|
||||
func (s *Server) ListenAndServe() {
|
||||
listener, err := net.Listen("tcp", s.addr)
|
||||
if err != nil {
|
||||
fmt.Println("Error binding to address:", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
|
||||
fmt.Printf("Server listening on %s\n", s.addr)
|
||||
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
fmt.Println("Error accepting connection:", err)
|
||||
continue
|
||||
}
|
||||
go handleConnection(conn)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue