CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Serving and Deploying Websites
- What is A Server
- A server is a program that listens for requests for data, processes those requests, and responds with data.
- We will be working with file servers. These servers will receive requsets for html files and send them to your browser.
- How to Serve Files
- Running the following files or commands from a directory with html files in it will create a file server that is able to serve files from that directory.
-
This is a simple file server written in Python.
import http.server import socketserver PORT = 3000 handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), handler) as httpd: print("serving at port", PORT) httpd.serve_forever()
This is a simple file server written in Go.package main import ( "fmt" "net/http" ) func main() { PORT := "3000" http.Handle("/", http.FileServer(http.Dir("."))) fmt.Println("serving at port", PORT) http.ListenAndServe(":"+PORT, nil) }- And this is a line you can run in your Terminal to start a server:
python3 -m http.server 3000
- URL To Directory Mapping
Say we runpython3 -m http.server 3000
from a directory with the following file structure:
|-index.html |-page2.html |-dir1 |---index.html |---page3.htmlVisitinghttp://localhost:3000/
will bring us to "index.html". When there is no html file specified after a path, the server automatically looks for "index.html".
Visitinghttp://localhost:3000/page2.html
will bring us to "page2.html"
Visitinghttp://localhost:3000/dir1
will bring us to "dir1/index.html"
Finally, visitinghttp://localhost:3000/dir1/page3.html
will bring us to "dir1/page3.html"
We can create relative links between pages. For example, the tag<a href="page2.html">link</a>
in "index.html" would link to page2.html.