One place for hosting & domains

      Format

      How To Format Strings in Go


      As strings are often made up of written text, there are many instances when we may want to have greater control over how strings look to make them more readable for humans through punctuation, line breaks, and indentation.

      In this tutorial, we’ll go over some of the ways we can work with Go strings to make sure that all output text is formatted correctly.

      String Literals

      Let’s first differentiate between a string literal and a string value. A string literal is what we see in the source code of a computer program, including the quotation marks. A string value is what we see when we call the fmt.Println function and run the program.

      In the “Hello, World!” program, the string literal is "Hello, World!" while the string value is Hello, World! without the quotation marks. The string value is what we see as the output in a terminal window when we run a Go program.

      But some string values may need to include quotation marks, like when we are quoting a source. Because string literals and string values are not equivalent, it is often necessary to add additional formatting to string literals to ensure that string values are displayed the way in which we intend.

      Quotes

      Because we can use back quotes (`) or double quotes (") within Go, it is simple to embed quotes within a string by using double quotes within a string enclosed by back quotes:

      `Sammy says, "Hello!"`
      

      Or, to use a back quote, you can enclose the string in double quotes:

      "Sammy likes the `fmt` package for formatting strings.."
      

      In the way we combine back quotes and double quotes, we can control the display of quotation marks and back quotes within our strings.

      It’s important to remember that using back quotes in Go creates a raw string literal, and using double quotes creates an interpreted string literal. To learn more about the difference, read the An Introduction to Working with Strings in Go tutorial.

      Escape Characters

      Another way to format strings is to use an escape character. Escape characters are used to tell the code that the following character has a special meaning. Escape characters all start with the backslash key () combined with another character within a string to format the given string a certain way.

      Here is a list of several of the common escape characters:

      Escape CharacterHow it formats
      \Backslash
      Double Quote
      nLine Break
      tTab (horizontal indentation)

      Let’s use an escape character to add the quotation marks to the example on quotation marks above, but this time we’ll use double quotes to denote the string:

      fmt.Println("Sammy says, "Hello!"")
      

      Output

      Sammy says, "Hello!"

      By using the escape character " we are able to use double quotes to enclose a string that includes text quoted between double quotes.

      We can use the n escape character to break lines without hitting the enter or return key:

      fmt.Println("This stringnspans multiplenlines.")
      

      Output

      This string spans multiple lines.

      We can combine escape characters, too. Let’s print a multi-line string and include tab spacing for an itemized list, for example:

      fmt.Println("1.tSharkn2.tShrimpn10.tSquid")
      

      Output

      1. Shark 2. Shrimp 10. Squid

      The horizontal indentation provided with the t escape character ensures alignment within the second column in the preceding example, making the output extremely readable for humans.

      Escape characters are used to add additional formatting to strings that may be difficult or impossible to achieve. Without escape characters, you would not be able to construct the string Sammy says, "I like to use the `fmt` package".

      Multiple Lines

      Printing strings on multiple lines can make text more readable to humans. With multiple lines, strings can be grouped into clean and orderly text, formatted as a letter, or used to maintain the linebreaks of a poem or song lyrics.

      To create strings that span multiple lines, back quotes are used to enclose the string. Keep in mind that while this will preserve the line returns, it is also creating a raw string literal.

      `
      This string is on 
      multiple lines
      within three single 
      quotes on either side.
      `
      

      You will notice if you print this that there is a leading and trailing return:

      Output

      This string is on multiple lines within three single quotes on either side.

      To avoid this, you need to put the first line immediately following the back quote and end the last with the back quote.

      `This string is on 
      multiple lines
      within three single 
      quotes on either side.`
      

      If you need to create an interpreted string literal, this can be done with double quotes and the + operator, but you will need to insert your own line breaks.

      "This string is onn" +
      "multiple linesn" +
      "within three singlen" +
      "quotes on either side."
      

      While back quotes can make it easier to print and read lengthy text, if you need an interpreted string literal, you will need to use double quotes.

      Raw String Literals

      What if we don’t want special formatting within our strings? For example, we may need to compare or evaluate strings of computer code that use the backslash on purpose, so we won’t want Go to use it as an escape character.

      A raw string literal tells Go to ignore all formatting within a string, including escape characters.

      We create a raw string by using back quotes around the string:

      fmt.Println(`Sammy says,"The balloon's color is red."`)
      

      Output

      Sammy says,"The balloon's color is red."

      By constructing a raw string by using back quotes around a given string, we can retain backslashes and other characters that are used as escape characters.

      Conclusion

      This tutorial went over several ways to format text in Go through working with strings. By using techniques such as escape characters or raw strings, we are able to ensure that the strings of our program are rendered correctly on-screen so that the end user is able to easily read all of the output text.



      Source link

      How to Create a DigitalOcean Droplet from an Ubuntu ISO Format Image


      Introduction

      DigitalOcean’s Custom Images feature allows you to bring your virtual disk images from an on-premise environment or another cloud platform to DigitalOcean and use them to start DigitalOcean Droplets.

      As described in the Custom Images documentation, the following image types are supported natively by the Custom Images upload tool:

      ISO is another popular image format which you may want to use with Custom Images. ISO images are frequently provided by Linux distributions as a convenient method for installing Linux. Unfortunately, ISO images aren’t currently supported by the upload tool, although support is planned for the end of 2018.

      In this tutorial, we’ll demonstrate how to use the free and open-source VirtualBox virtualization tool to create a DigitalOcean-compatible VDI image (VirtualBox Disk Image) from an Ubuntu 18.04 ISO. The steps in this guide can be adapted to work with your preferred distribution’s ISO images.

      Prerequisites

      Before you begin, you’ll need the following available to you:

      If you’re adapting these steps for another distribution’s ISO and your image does not have cloud-init installed and configured, you must install and configure it manually after installing the OS.

      Once you have these prerequisites available to you, you’re ready to begin with this guide.

      Step 1 — Installing VirtualBox and Creating a Virtual Machine

      The tool we’ll use to convert the ISO-format image in this guide is VirtualBox, a free and open-source virtualizer for x86 hardware. By default, VirtualBox uses a GUI, which we’ll use to create the VDI image in this guide.

      To begin, download and install VirtualBox from the downloads page. Follow the appropriate link in the VirtualBox 5.2.20 platform packages section depending on your host operating system. In this guide, we’ll be using an OSX system, so we’ll download and install VirtualBox using the provided DMG.

      Once you’ve installed VirtualBox, open the application.

      You should see the following welcome screen:

      VirtualBox Welcome Screen

      Click on New to begin creating your Ubuntu virtual machine.

      The following window should pop up, allowing you to name your virtual machine (VM) and select its OS:

      Name Virtual Machine Window

      In this tutorial, we’ll name our VM Ubuntu 18.04, but feel free to give the VM a more descriptive name.

      For Type, select Linux, and for Version, select Ubuntu (64-bit). Then, hit Continue.

      The following screen should appear, allowing you to specify how much memory to allocate to your virtual machine:

      Allocate Memory Window

      Unless you have a more complex use case, 1024 MB should be enough memory for your virtual machine. If you need to adjust memory size, enter the amount of memory to be allocated to the VM, then hit Continue.

      You should see the following screen:

      Create Hard Disk Window

      This window allows you to create a virtual hard disk for your VM. This virtual hard disk is the image that you’ll upload to DigitalOcean in a later step. The Ubuntu operating system will be installed from the ISO you downloaded to this virtual hard disk. Make sure Create a virtual hard disk now is selected, and hit Create.

      The following Hard disk file type window should appear, allowing you to select the format you’d like to use for your image:

      Select Hard Disk Type Window

      All three types are supported by DigitalOcean Custom Images, so unless you have a strong preference, select VDI (VirtualBox Disk Image). Hit Continue.

      You should then see the following window:

      Hard Disk Options

      This window allows you to choose between a Dynamically allocated or Fixed size hard disk file. We’ll use the default Dynamically allocated option and allow the file to grow as we install the Ubuntu OS and packages. Hit Continue.

      The next window allows you to name your hard disk file (as well as choose the path to which it will be saved), and specify its maximum size:

      Hard Disk Size

      Be sure to give yourself enough disk space to install the operating system as well as additional packages you may need. The default 10 GB should be fine for most purposes, but if you anticipate installing a large number of packages or storing a lot of data in the image, you should bump this up to your anticipated disk usage.

      Once you’ve selected the size of the virtual hard disk, hit Create.

      At this point, you’ll be returned to the initial welcome screen, where you’ll see the virtual machine you just created:

      VM Welcome Screen

      We can now begin installing Ubuntu onto the virtual machine.

      Step 2 — Installing Ubuntu 18.04 onto the Virtual Machine

      In this step we’ll install and configure the Ubuntu operating system onto our virtual machine.

      To begin, from the VirtualBox welcome screen, select your virtual machine, and hit the Start button in the toolbar.

      You should see the following virtual machine window, prompting you to select the ISO file from which you’ll boot the system:

      Select ISO

      Select the Ubuntu 18.04 Server ISO you downloaded, and hit Start.

      In the VM, the Ubuntu installer will begin booting from the ISO, and you should be brought to the following menu:

      Ubuntu Select Language

      Choose your preferred language using the arrow keys, and hit ENTER to continue.

      You should then see the following Keyboard configuration screen:

      Ubuntu Keyboard Config

      Choose your preferred keyboard configuration, select Done, and hit ENTER.

      Next, you’ll be brought to the following installer selection screen:

      Ubuntu Installer Selection

      Select Install Ubuntu, and hit ENTER.

      The following Network connections screen should appear:

      Ubuntu Network connections

      This screen allows you to configure the network interfaces for your Ubuntu server. Since we’re performing the installation on a virtual machine, we’ll just use the default option as the configured interface will be overwritten when we launch the image on the DigitalOcean platform.

      Select Done and hit ENTER.

      You’ll then be brought to the following Configure proxy screen:

      Ubuntu Configure Proxy

      If you require a proxy, enter it here. Then, select Done, and hit ENTER.

      The next screen will allow you to choose an Ubuntu archive mirror:

      Ubuntu Archive Mirror

      Unless you require a specific mirror, the default should be fine here. Select Done and hit ENTER.

      Next, you’ll be prompted to partition your virtual disk:

      Ubuntu Partition Disk

      Unless you’d like to set up Logical Volume Manager (LVM) or manually partition the virtual disk, select Use An Entire Disk to use the entire attached virtual disk, and hit ENTER.

      The following screen allows you to select the virtual disk that will be partitioned:

      Ubuntu Filesystem setup

      As described in the prompt text, the installer will create a partition for the bootloader, and use the remaining virtual disk space to create an ext4 partition to which the Ubuntu OS will be installed.

      Select the attached virtual disk and hit ENTER.

      The following screen displays a summary of the filesystem installer options before partitioning:

      Ubuntu Filesystem Summary

      The ext4 partition will be mounted to /, and a second partition (1 MB) will be created for the GRUB bootloader. Once you’ve gone over and confirmed the partitioning scheme for your virtual disk, select Done and hit ENTER.

      In the confirmation screen that appears, select Continue and hit ENTER.

      The next screen will allow you to configure the system hostname, as well as an Ubuntu user:

      Ubuntu Create User

      Note that as you fill out this screen, the installer will continue copying files to the virtual disk in the background.

      In this tutorial, we’ll create a user named sammy and call our server ubuntu. The server name will likely be overwritten when this image is run on the DigitalOcean platform, so feel free to give it a temporary name here.

      You can upload your SSH keys to DigitalOcean and automatically embed them into created Droplets, so for now we won’t Import SSH identity. To learn how to upload your SSH keys to DigitalOcean, consult the Droplet Product Documentation.

      Once you’ve filled in all the required fields, the prompt should look something like this:

      Ubuntu Profile Complete

      Select Done and hit ENTER.

      The next screen will prompt you to select popular snaps for your Ubuntu server. Snaps are prepackaged bundles of software that contain an application, its dependencies, and configuration. To learn more about snaps, consult the Snap Documentation.

      Ubuntu Select Snaps

      In this guide we won’t install any snaps and will manually install packages in a later step. If you’d like to install a snap, select or deselect it using SPACE and scroll down to Done. Then, hit ENTER.

      Regardless of your selection in the snap screen, you’ll then be brought to an installation progress and summary screen:

      Ubuntu Install Progress

      Once the installation completes, select Reboot Now and hit ENTER.

      The installer will shut down and prompt you to remove the installation medium (in this case this is the ISO image we selected earlier). In most cases, the ISO will be detached automatically upon reboot, so you can simply hit ENTER.

      To double check, in the VirtualBox GUI menu, navigate to Devices, and then Optical Drives. If the Remove disk from virtual drive option is available to you, click on it to detach the ISO from the virtual machine. Then, back in the virtual machine window, hit ENTER.

      The system will reboot in the virtual machine, this time from the virtual disk to which we installed Ubuntu.

      Since cloud-init is installed by default on Ubuntu 18.04 Server, the first time Ubuntu boots, cloud-init will run and configure itself. In the virtual machine window, you should see some cloud-init log items and have a prompt available to you. Hit ENTER.

      You can then log in to your Ubuntu server using the user you created in the installer.

      Enter your username and hit ENTER, then enter your password and hit ENTER.

      You should now have access to a command prompt, indicating that you’ve successfully completed the Ubuntu 18.04 installation, and are now logged in as the user you created previously.

      In the next step of this guide, we’ll reconfigure cloud-init and set it up to run when the Ubuntu image is launched as a Droplet on the DigitalOcean platform.

      Step 3 — Reconfiguring cloud-init

      Now that we’ve installed Ubuntu 18.04 to a virtual disk and have the system up and running, we need to reconfigure cloud-init to use the appropriate datasource for the DigitalOcean platform. A cloud-init datasource is a source of config data for cloud-init that typically consists of userdata (like shell scripts) or server metadata, like hostname, instance-id, etc. To learn more about cloud-init datasources, consult the official cloud-init docs.

      By default, on Ubuntu 18.04, cloud-init configures itself to use the DataSourceNoCloud datasource. This will cause problems when running the image on DigitalOcean, so we need to reconfigure cloud-init to use the ConfigDrive datasource and ensure that cloud-init reruns when the image is launched on DigitalOcean.

      To begin, ensure that you’ve started your Ubuntu 18.04 virtual machine and have logged in as the user you created earlier.

      From the command line, navigate to the /etc/cloud/cloud.cfg.d directory:

      • cd /etc/cloud/cloud.cfg.d

      Use the ls command to list the cloud-init config files present in the directory:

      Output

      05_logging.cfg 50-curtin-networking.cfg 90_dpkg.cfg curtin-preserve-sources.cfg README

      First, delete the 50-curtin-networking.cfg file, which configures networking interfaces for your Ubuntu server. When the image is launched on DigitalOcean, cloud-init will run and reconfigure these interfaces automatically. If this file is not deleted, the DigitalOcean Droplet created from this Ubuntu image will have its interfaces misconfigured and won't be accessible from the internet.

      • sudo rm 50-curtin-networking.cfg

      Next, we'll run dpkg-reconfigure cloud-init to remove the NoCloud datasource, ensuring that cloud-init searches for and finds the ConfigDrive datasource used on DigitalOcean:

      • sudo dpkg-reconfigure cloud-init

      You should see the following graphical menu:

      Cloud Init dpkg Menu

      The NoCloud datasource is initially highlighted. Press SPACE to unselect it, then hit ENTER.

      Finally, navigate to /etc/netplan:

      Remove the 50-cloud-init.yaml file (this was generated from the cloud-init networking file we removed earlier):

      • sudo rm 50-cloud-init.yaml

      The final step is ensuring that we clean up configuration from the initial cloud-init run so that it reruns when the image is launched on DigitalOcean.

      To do this, run cloud-init clean:

      At this point, your image is ready to be launched on the DigitalOcean platform. You can install additional packages and software into your image. Once you're done, shutdown your virtual machine:

      We can now move on to uploading and launching this custom image on the DigitalOcean platform.

      Step 4 — Uploading Custom Image and Creating Droplet

      Now that we've created an Ubuntu 18.04 VDI image and configured it for use on DigitalOcean, we can upload it using the Custom Images upload tool.

      On macOS, the Ubuntu virtual disk image we created and configured will be located by default at ~/VirtualBox VMs/your_VM_name/your_virtual_disk_name.vdi. This path may vary slightly depending on the OS you're using with VirtualBox.

      Before we upload the image, we'll compress it to speed up the file transfer to DigitalOcean.

      On your host OS (not inside the virtual machine), navigate to the directory containing your VDI image file:

      • cd ~/VirtualBox VMs/Ubuntu 18.04/

      Now, use gzip to compress the file:

      • gzip < Ubuntu 18.04.vdi > Ubuntu 18.04.gz

      In this command we pipe the source Ubuntu 18.04.vdi file into gzip, specifying as output the Ubuntu 18.04.gz compressed file.

      Once gzip finishes compressing your file, upload the .gz file to DigitalOcean, following instructions in the Custom Images Quickstart.

      You should now be able to create and use Droplets from your custom Ubuntu 18.04 Server image.

      Conclusion

      In this tutorial, we learned how to create a custom VDI image from a vanilla Ubuntu 18.04 ISO using the VirtualBox virtualization tool. We adjusted cloud-init so it can properly configure Droplet networking on DigitalOcean, and finally compressed and uploaded the image using the Custom Images upload tool.

      You can adjust the steps in this tutorial to work with your preferred Linux distribution’s ISO images. Ensure that you have an SSH server installed and configured to start on boot, and that cloud-init has been installed and properly configured to use the ConfigDrive datasource. Finally, ensure that any stale networking configuration files have been purged.

      You may also wish to use a tool like Packer to automate the creation of your machine images.

      To learn more about DigitalOcean Custom Images, consult the Custom Images product docs and launch blog post.



      Source link