Routes, methods and status codes

Knowledge Videos

Short animated explainers, organised by subject.

Routes, methods and status codes

A route connects a path and a method to a handler. GET, POST and DELETE, the status codes 200, 201, 400, 404 and 500, and how Go answers 404.

Try it

Transcript

A route connects a path to a handler. Slash goes to one handler, slash about to another, and slash time to a third. Each path gets its own small function.

A request also has a method. GET asks for data. POST sends new data. DELETE removes something. In Go, you can write the method in the route, like GET, space, slash api slash pets.

The response has a status code, a number that says how it went. Two hundred means okay. Two hundred one means created. Four hundred means the request was bad. Four hundred four means not found. Five hundred means the server had a problem.

Four hundred four is the one you already know: a path with no route. In Go, http dot NotFound writes it for you.

Remember: a route is a method and a path. Two hundred is okay, four hundred is a bad request, four hundred four is not found, and five hundred is a server problem.

More in this series

1:23

40How a web server works

A web server waits on a port for requests and sends responses. Handlers, http.HandleFunc and ListenAndServe, and seeing the request in the browser.

Goserverporthandlerhttpbeginner
1:19

42A JSON API in Go

An API returns data instead of pages. A Go struct becomes JSON with struct tags, a handler writes it with json.NewEncoder, and the page loads it with fetch.

GoAPIJSONstruct tagfetchbeginner
1:21

43POST and saving data

A POST request carries data in its body. Decode the JSON into a struct, keep it in a slice (lost on restart), and protect the shared slice with a mutex.

GoPOSTrequest bodymutexJSONbeginner
1:17

44What is a database?

A database keeps data in tables of rows and columns, like a strict spreadsheet. Primary keys, why data in a file survives a restart, and asking questions with SQL.

databasetablerowprimary keySQLbeginner
1:01

45SQL basics

SQL is the language for asking a database: CREATE TABLE, INSERT INTO, SELECT with WHERE and ORDER BY, then UPDATE and DELETE (always with WHERE).

SQLSELECTINSERTWHEREdatabasebeginner
1:14

46Go and databases

Go talks to a SQLite database with database/sql and a driver. Exec changes data, Query reads rows into structs, and ? placeholders pass values safely.

Godatabase/sqlSQLiteQueryExecplaceholderbeginner
1:20

47Input, validation and safety

Never trust a request: validate empty and too-long values and answer 400, why ? placeholders stop SQL injection, and keep secrets and database files out of Git.

GovalidationSQL injectionsafetygitignorebeginner