Building Basic Backend Servers with Dart's Core Library - Dart Tutorial Part 4

Tensor Programming · Beginner ·🛠️ AI Tools & Apps ·8y ago

Key Takeaways

Shows how to build a basic backend server using Dart's core library

Full Transcript

hey guys my name is tensor welcome to another dart tutorial today we're going to be taking a look at how we can use the core libraries of dart to build back-end servers dart is very much a batteries included style language this means that there are all kinds of different features that are built directly into the core library that you can use to build out very practical and scalable applications dart also features some very nice frameworks to help facilitate this process for instance there's a framework called aqueduct which makes use of the dart isolate pattern to allow you to scale out your web application infinitely today we're just going to be looking at how we can build a basic back-end server using the core dart libraries and then later we'll talk about building client based applications and looking at frameworks and stuff like that so for this application we want to bring in dart async and dart IO we need dart async because a lot of the functions and objects that we're going to be running return futures and streams and we want dart IO because this is where all of the input-output functionality for dart resides this includes functions that allow us to erect TCP and UDP style servers as well as basic HTTP style servers let's start by instantiating a new HTTP server object so here we can create a server object by awaiting on HTTP server dot bind this is a constructor that allows us to specify an address and a port that we want this server to bind to in here I'm just going to use 127 0 dot 0 dot 1 this is just localhost and then I'm going to specify port 8080 for the port for this server also notice that this is an asynchronous constructor so it returns a future HTTP server so we need to await on it so that we can properly get back this server type when we execute this server we want to be able to basically tell the user that they've the server so we can create a simple little print statement that says listening on localhost and then we can get the port by calling server dot port inside of the string so this will just say listening on localhost port 8080 now the server object is essentially just a stream it's a stream of HTTP request objects that are being passed back and forth through the server each of these requests also has a response built onto it as well and we can use these requests to decide how the server will react based on various different parameters of how the user is reacting with the server so for instance if we wanted to make it so that on a get request we get a specific piece of information we could do that for now we're just going to say for all of the requests write a response where we write a bit of text that just says this is some text and then we close the stream which is the response so the server itself is also a stream as I mentioned before and that's why we can just listen on it the response is also a stream and that's why we close it like this so now we can launch the application you can see here we get our print statement it says listening on localhost 8080 if I open a browser in localhost 8080 we get back this is some text from our string which we've just pushed to this response it's also important to note that no matter what path we add to this localhost 8080 address we will still get back this same response because we've said for all requests send this single response all right so with this we're able to write a string back to the client that's reading this information but we can't really do much else if we try to say insert HTML tags into the string they'll just get pushed out without being parsed so for instance if I just put in some h1 tags around this the text itself will come out with those h1 tags around it on the document and you can see that here so it says h1 it doesn't parse it because it knows that this is just a plain text response let's adjust this server so that we can actually serve a file to the user so I'll create a new file up here and we'll just use the file object to create this file and our file will be called index.html and it will get this from the root of our project so from outside of this bin folder inside of here so we want to create that file now if we say new file index.html and we'll just create a simple HTML document using Emmet so I'll just create the document here I'll name it something like Dart example and inside of the actual body of this document we'll create a div then an h1 that just says hello there then we'll have another div inside of the day of where we just say here is some text will have a line break and then it'll say here is a link and we'll surround the link with an A element with an H ref that just points towards the pound sign so now let's change how we're listening on the server we can use a listener like we're doing here or we can just use the awake for loop so we can say oh wait for VAR request inside of server so for each request inside of this server we want to do something then inside of this wait for loop we'll just check to see if our file exists and the file exists function returns at future so we need to await on it if our file does exist we can print out that we're serving this file and we'll print out the files path then we want to take our request and take the response that's attached to this request and change the content type which is in the headers of this response to content type HTML so that the client knows that it's being served a piece of HTML and then after changing the content type headers we want to open our file with the open read method and then we'll pipe the data from the file into our request response stream that way it gets streamed to the client and then the client will be able to display the file so now if we run our application you can see we get this listening on localhost 8080 like before and then if we open up the actual address inside of a browser it will say serving index.html and so inside the browser it will look like this I would say hello there and then it'll say here are some text and then we'll have our little link which we can click on and it does nothing and like before we're making it so that any request sends back the same response so no matter the route that we put in here we're still going to get this same piece of HTML let's add some error handling to this application so we'll surround the server itself in a try block so first we need to create the server variable outside of this block because it's lexically scoped if we don't create it outside of the block then we can't access it outside of the block so we create our server variable here and then we can say try HTTP server bind so we try to bind it on the address and if this fails then we get back an exception which we can then print out so in here we can say something along the lines of failed to start server with the exception and then we can call exit negative one which will force the application to quit with the error code of negative one then down inside of where we're reading through all of the requests in our server where we're opening the file or we surround this in a try-catch block and we want to say okay try opening the file when we have a request and if the file can't be read then we'll just print out couldn't read file and then of course we'll also exit with negative one now outside of our if statement we can add an else clause and this will happen if the file doesn't exist so here we can print out that we can't open the file because it doesn't exist and then for each of the requests we'll respond by changing the status code to status not found which is a 404 status code and then we'll close the stream so if I go in here and I delete our index.html when we run the application and if we try to actually get the file inside of the browser we'll get back this can't open file statement because the file doesn't exist anymore thus far all of our server examples have made it so that we serve one specific thing for all of the requests that the client makes so now let's make something that's more dynamic specifically we'll make it so that our server serves the files based on what the user is requesting with the route that they're requesting in the browser so here we have the basic server template that we've been using thus far we just have the try loop and we're binding it to the localhost and the port 8080 and then we have this little catch block just in case and then we have a little print statement to tell it that it's actually running properly and then we have our await for loop in here we can print out request URI path segments and last what this does is it takes the path that the user is requesting the URI that the user is requesting and splits it up into strings and then pushes that into a list and the list is this path segments variable we're able to then get the last item inside of that list by calling this last method on top of it so when we run this application if I go to index.html it will automatically pull out that string and then we can use it to name a new file if I make another path that's maybe a little bit more complicated so here we're saying localhost 8080 then we just got a bunch of gibberish in here and then we've got test.txt you'll see that we just get the final part of that URI so first let's a leus our response into an HTTP response by binding the request response stream to this response variable then we want to make sure that all of the methods for the requests they sent into this server our get methods before we serve the files so here we can say if the request method equals capital get as a string then we can do various things let's get our file name so we call request dot your ride path segments don't last to get the file name we put this into a string and then let's check to see if our file name contains dot HTML at the end if it doesn't contain dot HTML at the end so we can say file name equals filename concatenated with dot HTML and this will make it so that all of the files that the user requests from the server will come back as HTML documents now we can actually create the dynamic file by saying file file equals new file with the file name inside of it then we want to check to see if the file exists if it does exist then we can just open and read it to our response otherwise we want to be able to make a new file and then serve it to the user so inside of this first if statement we can just say file open read and then pipe it into the response and then inside of our else statement we can say file open write we can set the mode to file mode right so that we're actually writing into the file and then we can write something like h1 this is a new file and then close the h1 then let's open the file with open read and then we can pipe it into the response stream like we're doing up here all right so now let's run this application so inside of the browser if I go to index.html you can see that we get our string back but it's not actually formatting it with the HTML so it's creating a new file called index.html based on the path that I've put in here and it's reading in the string that we wrote inside of this server but the browser doesn't know to read this as HTML so to fix this all we have to do is set the content type of the response to be content type EML so up we're we're a Lia Singh our response to the response variable we can just add a cascade operator get the headers and the content type and then set it to content type dot HTML so now if I rerun this server you can see this now reads as HTML and now I can just type in random files so let's just type in a random name and this will read out as a new piece of HTML and you can see here that that piece of HTML actually gets created here and we can come in here and we can edit this piece of HTML if we want to as well let's put say an h2 tag in here and then we can add some stuff to it and if we request it it will grab that HTML file and read from it all right guys well I hope this tutorial give you a good feel of how to write a server inside of Dart one of the coolest parts about how dart treats its servers is the fact that everything is a stream and this kind of feels a bit like how elixir treats servers where you have this stream and then you just augment it with various different plugs if you guys enjoyed this tutorial feel free to like and subscribe if you have any questions or comments feel free to leave them in the comment box below and if you dislike this video then by all means download it as much as you like have a good night

Original Description

In this tutorial, we look at how we can make some simple backend servers using dart's core library. Source Code: https://github.com/tensor-programming/dart_http_tutorial Feel free to donate: Patreon: https://www.patreon.com/tensor_programming ETH: 0x03247265dd5242605bD2FA3c40fb3b70d9e3D685
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Tensor Programming · Tensor Programming · 0 of 60

← Previous Next →
1 NodeJs, Text editors and IDEs
NodeJs, Text editors and IDEs
Tensor Programming
2 Vanilla JS todo App
Vanilla JS todo App
Tensor Programming
3 Elm Tutorial part 1
Elm Tutorial part 1
Tensor Programming
4 Elm Lang Tutorial, Part 2
Elm Lang Tutorial, Part 2
Tensor Programming
5 Elm Tutorial Part 3
Elm Tutorial Part 3
Tensor Programming
6 Elm Tutorial Part 4 -- Analog Clock App
Elm Tutorial Part 4 -- Analog Clock App
Tensor Programming
7 Elm Tutorial part 5 -- Snake Game
Elm Tutorial part 5 -- Snake Game
Tensor Programming
8 Elm Tutorial part 6 -- Calculator
Elm Tutorial part 6 -- Calculator
Tensor Programming
9 Go Tutorial part 1 -- Hello World and Static File Server
Go Tutorial part 1 -- Hello World and Static File Server
Tensor Programming
10 Go Tutorial part 2 -- Web Crawler
Go Tutorial part 2 -- Web Crawler
Tensor Programming
11 Go Tutorial Part 3 (Web App part 1)
Go Tutorial Part 3 (Web App part 1)
Tensor Programming
12 Go tutorial Part 4 (Web tutorial part 2) - Using templates
Go tutorial Part 4 (Web tutorial part 2) - Using templates
Tensor Programming
13 Go tutorial part 5 (web app part 3)
Go tutorial part 5 (web app part 3)
Tensor Programming
14 Go tutorial part 6 (webapp part 4)
Go tutorial part 6 (webapp part 4)
Tensor Programming
15 Go tutorial part 7 (web app part 5)
Go tutorial part 7 (web app part 5)
Tensor Programming
16 Go tutorial part 8 (Web app part 6)
Go tutorial part 8 (Web app part 6)
Tensor Programming
17 Go tutorial Part 9 (web tutorial part 7)
Go tutorial Part 9 (web tutorial part 7)
Tensor Programming
18 Go tutorial Part 10 (web app part 8)
Go tutorial Part 10 (web app part 8)
Tensor Programming
19 Go tutorial Part 11 (Web app Part 9)
Go tutorial Part 11 (Web app Part 9)
Tensor Programming
20 Go Tutorial Part 12 (Web app Part 10)
Go Tutorial Part 12 (Web app Part 10)
Tensor Programming
21 Go Tutorial Part 13 (Web app Part 11)
Go Tutorial Part 13 (Web app Part 11)
Tensor Programming
22 Looking at Elm 0.18
Looking at Elm 0.18
Tensor Programming
23 Go tutorial Part 14 (Web tutorial part 12)
Go tutorial Part 14 (Web tutorial part 12)
Tensor Programming
24 Go tutorial Part 15 (Web tutorial part 13)
Go tutorial Part 15 (Web tutorial part 13)
Tensor Programming
25 Go tutorial part 16 (web app part 14)
Go tutorial part 16 (web app part 14)
Tensor Programming
26 Elm Tutorial Part 7 (SPA part 1)
Elm Tutorial Part 7 (SPA part 1)
Tensor Programming
27 Elm Tutorial Part 8 (SPA Part 2)
Elm Tutorial Part 8 (SPA Part 2)
Tensor Programming
28 Electron Elm Tutorial
Electron Elm Tutorial
Tensor Programming
29 Go tutorial part 17 (web app part 15)
Go tutorial part 17 (web app part 15)
Tensor Programming
30 Up and Coming Programming Languages and Technologies for 2017
Up and Coming Programming Languages and Technologies for 2017
Tensor Programming
31 elixir tutorial part 1
elixir tutorial part 1
Tensor Programming
32 elixir tutorial part 2
elixir tutorial part 2
Tensor Programming
33 Elixir tutorial Part 3 (GenServer and Supervisor)
Elixir tutorial Part 3 (GenServer and Supervisor)
Tensor Programming
34 Elixir Tutorial Part 4 (GenStage)
Elixir Tutorial Part 4 (GenStage)
Tensor Programming
35 Elixir Tutorial Part 5 (Plug and Cowboy)
Elixir Tutorial Part 5 (Plug and Cowboy)
Tensor Programming
36 Phoenix Framework Tutorial Part 1 (elixir part 6)
Phoenix Framework Tutorial Part 1 (elixir part 6)
Tensor Programming
37 Phoenix Framework Tutorial Part 2  (elixir part 7)
Phoenix Framework Tutorial Part 2 (elixir part 7)
Tensor Programming
38 Phoenix Framework Tutorial Part 3 (elixir part 8)
Phoenix Framework Tutorial Part 3 (elixir part 8)
Tensor Programming
39 A Intro to Clojure and Clojure Syntax
A Intro to Clojure and Clojure Syntax
Tensor Programming
40 An Update about the channel
An Update about the channel
Tensor Programming
41 Intro to Rustlang (Setup and Primitives)
Intro to Rustlang (Setup and Primitives)
Tensor Programming
42 Intro to Rustlang (Strings, Tuples, Arrays, Slices and Pretty Printing)
Intro to Rustlang (Strings, Tuples, Arrays, Slices and Pretty Printing)
Tensor Programming
43 Intro to Rustlang (Ownership and Borrowing)
Intro to Rustlang (Ownership and Borrowing)
Tensor Programming
44 Intro to Rustlang (Structs, Methods, Functions, Related Functions and the Display/Debug Traits)
Intro to Rustlang (Structs, Methods, Functions, Related Functions and the Display/Debug Traits)
Tensor Programming
45 Intro to Rustlang (Control Flow, Conditionals and Pattern Matching)
Intro to Rustlang (Control Flow, Conditionals and Pattern Matching)
Tensor Programming
46 Intro to RustLang (Enums and Options)
Intro to RustLang (Enums and Options)
Tensor Programming
47 Intro to Rustlang (Vectors, HashMaps, Casting, If-Let, While-Let, and the Result Enum)
Intro to Rustlang (Vectors, HashMaps, Casting, If-Let, While-Let, and the Result Enum)
Tensor Programming
48 Rustlang Project: Snake Game
Rustlang Project: Snake Game
Tensor Programming
49 Intro to Rustlang (Traits and Generic Types)
Intro to Rustlang (Traits and Generic Types)
Tensor Programming
50 Intro to Rust-lang (Closures, the Box Pointer and Iterators)
Intro to Rust-lang (Closures, the Box Pointer and Iterators)
Tensor Programming
51 Intro to Rust-lang (Modules and Lifetimes)
Intro to Rust-lang (Modules and Lifetimes)
Tensor Programming
52 Intro to Rust-lang (Macros and Metaprogramming)
Intro to Rust-lang (Macros and Metaprogramming)
Tensor Programming
53 Intro to Rust-lang (Error Handling)
Intro to Rust-lang (Error Handling)
Tensor Programming
54 Intro to Rust-lang (Concurrency, Threads, Channels, Mutex and Arc)
Intro to Rust-lang (Concurrency, Threads, Channels, Mutex and Arc)
Tensor Programming
55 Intro to Rust-lang (Tests, Attributes, Configuration and Conditional compilation)
Intro to Rust-lang (Tests, Attributes, Configuration and Conditional compilation)
Tensor Programming
56 Rustlang Project: Port Sniffer CLI
Rustlang Project: Port Sniffer CLI
Tensor Programming
57 Rustlang Project: Chat Application
Rustlang Project: Chat Application
Tensor Programming
58 Rustlang Project: CLI Toy Blockchain
Rustlang Project: CLI Toy Blockchain
Tensor Programming
59 Intro to Rust-lang (Setting up a Development Environment)
Intro to Rust-lang (Setting up a Development Environment)
Tensor Programming
60 Intro to Rust-lang (Building a Web API with Iron)
Intro to Rust-lang (Building a Web API with Iron)
Tensor Programming

Related Reads

📰
Three Token-2022 Mints in One Week: Fees, Yield, and Soulbound
Learn how to build three different Token-2022 mints on Solana devnet in one week, including fee-bearing, interest-accruing, and soulbound tokens
Dev.to · atharv shukla
📰
Maximize Google Workspace AI Power: Safeguard Data and Boost Performance in 2026
Maximize Google Workspace AI power by safeguarding data and boosting performance to stay ahead in 2026
Dev.to AI
📰
What is Gemini Spark, and what can it actually do for you?
Gemini Spark integrates AI into daily Google apps to enhance productivity, learn how to leverage it
TechCabal
📰
How I use python to save hours every week
Learn how to use Python to automate tasks and save hours every week, with practical steps for beginners and experienced users alike.
Dev.to AI
Up next
Implement Microsoft Entra ID Auth with Delegated Graph API Calls in ASP.NET Core Web App Razor Pages
Dewiride Technologies
Watch →