Skip to content

Latest commit

 

History

History
61 lines (47 loc) · 1.33 KB

File metadata and controls

61 lines (47 loc) · 1.33 KB

From TCP to HTTP

Implementation from TCP of a simple HTTP/1.1 server

To test it

To modify the default behavior

Here is the implementation of the default behavior

func main() {
 server, err := server.Serve(port,
func()
 {
  if req.RequestLine.RequestTarget == "/yourproblem" {
   w.WriteStatusLine(response.BadRequest)
   w.WriteBody(response.BadRequestBody)
   return
  }

  if req.RequestLine.RequestTarget == "/myproblem" {
   w.WriteStatusLine(response.InternalServerError)
   w.WriteBody(response.InternalErrorBody)
   return
  }

  w.WriteBody(response.OkBody)
 })
 if err != nil {
  log.Fatalf("Error starting server: %v", err)
 }
 defer server.Close()
 log.Println("Server started on port", port)

 sigChan := make(chan os.Signal, 1)
 signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
 <-sigChan
 log.Println("Server gracefully stopped")
}

Simply modify the function passed in paramater of Serve with a signature of

func(w *response.Writer, req *request.Request)