One place for hosting & domains

      Beginner039s

      A Beginner's Guide to SELinux on CentOS 8


      Updated by Linode

      Contributed by
      Linode

      SELinux is a Mandatory Access Control (MAC) system, developed by the NSA. SELinux was developed as a replacement for Discretionary Access Control (DAC) that ships with most Linux distributions.

      The difference between DAC and MAC is how users and applications gain access to machines. Traditionally, the command sudo gives a user the ability to heighten permissions to root-level. Root access on a DAC system gives the person or program access to all programs and files on a system.

      A person with root access should be a trusted party. But if security has been compromised, so too has the system. SELinux and MACs resolve this issue by both confining privileged processes and automating security policy creation.

      SELinux defaults to denying anything that is not explicitly allowed. SELinux has two global modes, permissive and enforcing. Permissive mode allows the system to function like a DAC system, while logging every violation to SELinux. The enforcing mode applies a strict denial of access to anything that isn’t explicitly allowed. To explicitly allow certain behavior on a machine, you, as the system administrator, have to write policies that allow it. This guide provides a brief and basic introduction to commonly used commands and practices for SELinux system administration.

      Before You Begin

      1. Ensure that you have followed the Getting Started and Securing Your Server guides.

        Note

        This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, you can check our Users and Groups guide.
      2. Update your system:

        sudo yum update
        

        Note

        The Linode kernel does not support SELinux by default. However, all new Linodes running CentOS 8 use the distribution provided kernel, which has SELinux enabled by default.

        If your system is running a Linode kernel, you will need to change to an upstream kernel in order to use SELinux. See the How to Change Your Linode’s Kernel for more steps. Once you’re kernel is set to the upstream kernel, continue on with the steps in this guide.

      Install Supporting SELinux Packages

      In this section, you will install various SELinux packages that will help you when creating, managing, and analyzing SELinux policies.

      1. Verify which SELinux packages are installed on your system:

        sudo rpm -aq | grep selinux
        

        A newly deployed CentOS 8 Linode should have the following packages installed:

          
        libselinux-2.5-14.1.el7.x86_64
        selinux-policy-3.13.1-252.el7_7.6.noarch
        selinux-policy-targeted-3.13.1-252.el7_7.6.noarch
        libselinux-utils-2.5-14.1.el7.x86_64
        libselinux-python-2.5-14.1.el7.x86_64
            
        
      2. Install the following packages and their associated dependencies:

        sudo yum install policycoreutils policycoreutils-python setools setools-console setroubleshoot
        
        • policycoreuitls and policyoreutils-python contain several management tools to administer your SELinux environment and policies.
        • setools provides command line tools for working with SELinux policies. Some of these tools include, sediff which you can use to view differences between policies, seinfo a tool to view information about the components that make up SELinux policies, and sesearch used to search through your SELinux policies. setools-console consists of sediff, seinfo, and sesearch. You can issue the --help option after any of the listed tools in order to view more information about each one.
        • setroubleshoot suite of tools help you determine why a script or file may be blocked by SELinux.

        Optionally, install setroubleshoot-server and mctrans. The setroubleshoot-server allows, among many other things, for email notifications to be sent from the server to notify you of any policy violations. The mctrans daemon translates SELinux’s output to human readable text.

      SELinux States and Modes

      SELinux States

      When SELinux is installed on your system, it can be either enabled or disabled. By default, the CentOS 8 image provided by Linode has SELinux in an enabled state.

      • To disable SELinux, update your SELinux configuration file using the text editor of your choice. Set the SELINUX directive to disabled as shown in the example.

        /etc/selinux/config
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        
        # This file controls the state of SELinux on the system.
        # SELINUX= can take one of these three values:
        #     enforcing - SELinux security policy is enforced.
        #     permissive - SELinux prints warnings instead of enforcing.
        #     disabled - No SELinux policy is loaded.
        SELINUX=disabled
        # SELINUXTYPE= can take one of three values:
        #     targeted - Targeted processes are protected,
        #     minimum - Modification of targeted policy. Only selected processes are protected.
        #     mls - Multi Level Security protection.
        SELINUXTYPE=targeted
              

        Note

        You can update the SELINUX directive with any of the available SELinux states or modes.
      • Reboot your Linode for the changes to take effect:

        sudo reboot
        
      • Connect to your Linode via SSH (replace 192.0.2.0 with your own Linode’s IP address) and verify your SELinux installation’s status:

        ssh [email protected]
        sudo sestatus
        

        Its output should display disabled

          
        SELinux status:                 disabled
            
        

      SELinux Modes

      When SELinux is enabled, it can run in either enforcing or permissive modes.

      Note

      If SELinux is currently disabled, update your SELinux configuration file with the SELINUX directive set to enabled, then reboot your system, and SSH back into your Linode. These steps are outlined in the SELinux States section of the guide.
      • In enforcing mode, SELinux enforces its policies on your system and denies access based on those policies. Use the following command to view SELinux policy modules currently loaded into memory:

        sudo semodule -l
        
      • Permissive mode does not enforce any of your SELinux policies, instead, it logs any actions that would have been denied to your /var/log/audit/audit.log file.

      • You can check which mode your system is running by issuing the following command:

        sudo getenforce
        
      • To place SELinux in permissive mode, use the following command:

        sudo setenforce 0
        

        Permissive mode is useful when configuring your system, because you and your system’s components can interact with your files, scripts, and programs without restriction. However, you can use audit logs and system messages to understand what would be restricted in enforcing mode. This will help you better construct the necessary policies for your system’s user’s and programs.

      • Use the sealert utility to generate a report from your audit log. The log will include information about what SELinux is preventing and how to allow the action, if desired.

        sudo sealert -a /var/log/audit/audit.log
        

        The output will resemble the example, however, it varies depending on the programs and configurations on your system. The example was generated using a Linode running the Apache webserver with a virtual hosts configuration.

          
        SELinux is preventing /usr/sbin/httpd from write access on the directory logs.
        
        *****  Plugin httpd_write_content (92.2 confidence) suggests   ***************
        
        If you want to allow httpd to have write access on the logs directory
        Then you need to change the label on 'logs'
        Do
        # semanage fcontext -a -t httpd_sys_rw_content_t 'logs'
        # restorecon -v 'logs'
            
        
      • To allow /usr/sbin/httpd write access to the directory logs, as shown by the output, you can execute the suggested commands, semanage fcontext -a -t httpd_sys_rw_content_t 'logs' and restorecon -v 'logs'.

      SELinux Context

      SELinux marks every single object on a machine with a context. Every file, user, and process has a context. The context is broken into three parts: user, role, and type. An SELinux policy controls which users can get which roles. Each specific role places a constraint on what type of files that user can access. When a user logs in to a system, a role is assigned to the user as seen in the ls -Z example, the output unconfined_u is a user role.

      1. Create a directory in your home folder:

        mkdir ~/example_dir
        
      2. Print the SELinux security context of your home folder’s directories and files :

        ls -Z ~/
        

        The output is similar to:

          
        drwxrwxr-x. example_user example_user unconfined_u:object_r:user_home_t:s0 example_dir
            
        

        The SELinux specific information is contained in the unconfined_u:object_r:user_home_t:s0 portion, which follows the following syntax: user:role:type:level. To learn more about users, roles, and related access control, see the CentOS SELinux documentation.

      SELinux Boolean

      An SELinux Boolean is a variable that can be toggled on and off without needing to reload or recompile an SELinux policy.

      1. You can view the list of boolean variables using the getsebool -a command. Pipe the command through grep to narrow down your results.

        sudo getsebool -a | grep "httpd_can"
        

        You will see a similar output:

          
        httpd_can_check_spam --> off
        httpd_can_connect_ftp --> off
        httpd_can_connect_ldap --> off
        httpd_can_connect_mythtv --> off
        httpd_can_connect_zabbix --> off
        httpd_can_network_connect --> off
        httpd_can_network_connect_cobbler --> off
        httpd_can_network_connect_db --> off
        httpd_can_network_memcache --> off
        httpd_can_network_relay --> off
        httpd_can_sendmail --> off
            
        

        You can change the value of any variable using the setsebool command. If you set the -P flag, the setting will persist through reboots. If, for example, you want to allow HTTPD scripts and modules to connect to the network, update the corresponding boolean variable

        sudo setsebool -P httpd_can_network_connect ON
        

        When viewing a list of your boolean variables, you should now see that it is set to ON.

        sudo getsebool -a | grep "httpd_can"
        
          
        httpd_can_check_spam --> off
        httpd_can_connect_ftp --> off
        httpd_can_connect_ldap --> off
        httpd_can_connect_mythtv --> off
        httpd_can_connect_zabbix --> off
        httpd_can_network_connect --> on
        httpd_can_network_connect_cobbler --> off
        httpd_can_network_connect_db --> off
        httpd_can_network_memcache --> off
        httpd_can_network_relay --> off
        httpd_can_sendmail --> off
              
        

      Next Steps

      This guide provides a brief and basic introduction to SELinux administration. You can now take a deeper dive into SELinux by consulting some of the resources include in the More Information section of this guide.

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      This guide is published under a CC BY-ND 4.0 license.



      Source link

      A Beginner's Guide to SELinux on CentOS 7


      Updated by Linode

      Written by Angel Guarisma

      Getting Started with SELinux

      SELinux is a Mandatory Access Control (MAC) system, developed by the NSA. SELinux was developed as a replacement for Discretionary Access Control (DAC) that ships with most Linux distributions.

      The difference between DAC and MAC is how users and applications gain access to machines. Traditionally, the command sudo gives a user the ability to heighten permissions to root-level. Root access on a DAC system gives the person or program access to all programs and files on a system.

      A person with root access should be a trusted party. But if security has been compromised, so too has the system. SELinux and MACs resolve this issue by both confining privileged processes and automating security policy creation.

      SELinux defaults to denying anything that is not explicitly allowed. SELinux has two global modes, permissive and enforcing. Permissive mode allows the system to function like a DAC system, while logging every violation to SELinux. The enforcing mode applies a strict denial of access to anything that isn’t explicitly allowed. To explicitly allow certain behavior on a machine, you, as the system administrator, have to write policies that allow it. This guide provides a brief and basic introduction to commonly used commands and practices for SELinux system administration.

      Before You Begin

      1. Ensure that you have followed the Getting Started and Securing Your Server guides.

        Note

        This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, you can check our Users and Groups guide.
      2. Update your system:

        sudo yum update
        

        Note

        The Linode kernel does not support SELinux by default. However, all new Linodes running CentOS 7 use the distribution provided kernel, which has SELinux enabled by default.

        If your system is running a Linode kernel, you will need to change to an upstream kernel in order to use SELinux. See the How to Change Your Linode’s Kernel for more steps. Once you’re kernel is set to the upstream kernel, continue on with the steps in this guide.

      Install Supporting SELinux Packages

      In this section, you will install various SELinux packages that will help you when creating, managing, and analyzing SELinux policies.

      1. Verify which SELinux packages are installed on your system:

        sudo rpm -aq | grep selinux
        

        A newly deployed CentOS 7 Linode should have the following packages installed:

          
        libselinux-2.5-14.1.el7.x86_64
        selinux-policy-3.13.1-252.el7_7.6.noarch
        selinux-policy-targeted-3.13.1-252.el7_7.6.noarch
        libselinux-utils-2.5-14.1.el7.x86_64
        libselinux-python-2.5-14.1.el7.x86_64
            
        
      2. Install the following packages and their associated dependencies:

        sudo yum install policycoreutils policycoreutils-python setools setools-console setroubleshoot
        
        • policycoreuitls and policyoreutils-python contain several management tools to administer your SELinux environment and policies.
        • setools provides command line tools for working with SELinux policies. Some of these tools include, sediff which you can use to view differences between policies, seinfo a tool to view information about the components that make up SELinux policies, and sesearch used to search through your SELinux policies. setools-console consists of sediff, seinfo, and sesearch. You can issue the --help option after any of the listed tools in order to view more information about each one.
        • setroubleshoot suite of tools help you determine why a script or file may be blocked by SELinux.

        Optionally, install setroubleshoot-server and mctrans. The setroubleshoot-server allows, among many other things, for email notifications to be sent from the server to notify you of any policy violations. The mctrans daemon translates SELinux’s output to human readable text.

      SELinux States and Modes

      SELinux States

      When SELinux is installed on your system, it can be either enabled or disabled. By default, the CentOS 7 image provided by Linode has SELinux in an enabled state.

      • To disable SELinux, update your SELinux configuration file using the text editor of your choice. Set the SELINUX directive to disabled as shown in the example.

        /etc/selinux/config
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        
        # This file controls the state of SELinux on the system.
        # SELINUX= can take one of these three values:
        #     enforcing - SELinux security policy is enforced.
        #     permissive - SELinux prints warnings instead of enforcing.
        #     disabled - No SELinux policy is loaded.
        SELINUX=disabled
        # SELINUXTYPE= can take one of three values:
        #     targeted - Targeted processes are protected,
        #     minimum - Modification of targeted policy. Only selected processes are protected.
        #     mls - Multi Level Security protection.
        SELINUXTYPE=targeted
              

        Note

        You can update the SELINUX directive with any of the available SELinux states or modes.
      • Reboot your Linode for the changes to take effect:

        sudo reboot
        
      • Connect to your Linode via SSH (replace 192.0.2.0 with your own Linode’s IP address) and verify your SELinux installation’s status:

        ssh [email protected]
        sudo sestatus
        

        Its output should display disabled

          
        SELinux status:                 disabled
            
        

      SELinux Modes

      When SELinux is enabled, it can run in either enforcing or permissive modes.

      Note

      If SELinux is currently disabled, update your SELinux configuration file with the SELINUX directive set to enabled, then reboot your system, and SSH back into your Linode. These steps are outlined in the SELinux States section of the guide.
      • In enforcing mode, SELinux enforces its policies on your system and denies access based on those policies. Use the following command to view SELinux policy modules currently loaded into memory:

        sudo semodule -l
        
      • Permissive mode does not enforce any of your SELinux policies, instead, it logs any actions that would have been denied to your /var/log/audit/audit.log file.

      • You can check which mode your system is running by issuing the following command:

        sudo getenforce
        
      • To place SELinux in permissive mode, use the following command:

        sudo setenforce 0
        

        Permissive mode is useful when configuring your system, because you and your system’s components can interact with your files, scripts, and programs without restriction. However, you can use audit logs and system messages to understand what would be restricted in enforcing mode. This will help you better construct the necessary policies for your system’s user’s and programs.

      • Use the sealert utility to generate a report from your audit log. The log will include information about what SELinux is preventing and how to allow the action, if desired.

        sudo sealert -a /var/log/audit/audit.log
        

        The output resembles the example, however, it varies depending on the programs and configurations on your system. The example was generated using a Linode running the Apache webserver with a virtual hosts configuration.

          
        SELinux is preventing /usr/sbin/httpd from write access on the directory logs.
        
        *****  Plugin httpd_write_content (92.2 confidence) suggests   ***************
        
        If you want to allow httpd to have write access on the logs directory
        Then you need to change the label on 'logs'
        Do
        # semanage fcontext -a -t httpd_sys_rw_content_t 'logs'
        # restorecon -v 'logs'
            
        
      • To allow /usr/sbin/httpd write access to the directory logs, as shown in the output, you can execute the suggested commands, semanage fcontext -a -t httpd_sys_rw_content_t 'logs' and restorecon -v 'logs'.

      SELinux Context

      SELinux marks every single object on a machine with a context. Every file, user, and process has a context. The context is broken into three parts: user, role, and type. An SELinux policy controls which users can get which roles. Each specific role places a constraint on what type of files that user can access. When a user logs in to a system, a role is assigned to the user as seen in the ls -Z example, the output unconfined_u is a user role.

      1. Create a directory in your home folder:

        mkdir ~/example_dir
        
      2. Print the SELinux security context of your home folder’s directories and files:

        ls -Z ~/
        

        The output is similar to:

          
        drwxrwxr-x. example_user example_user unconfined_u:object_r:user_home_t:s0 example_dir
            
        

        The SELinux specific information is contained in the unconfined_u:object_r:user_home_t:s0 portion, which follows the following syntax: user:role:type:level. To learn more about users, roles, and related access control, see the CentOS SELinux documentation.

      SELinux Boolean

      An SELinux Boolean is a variable that can be toggled on and off without needing to reload or recompile an SELinux policy.

      1. You can view the list of boolean variables using the getsebool -a command. Pipe the command through grep to narrow down your results.

        sudo getsebool -a | grep "httpd_can"
        

        You will see a similar output:

          
        httpd_can_check_spam --> off
        httpd_can_connect_ftp --> off
        httpd_can_connect_ldap --> off
        httpd_can_connect_mythtv --> off
        httpd_can_connect_zabbix --> off
        httpd_can_network_connect --> off
        httpd_can_network_connect_cobbler --> off
        httpd_can_network_connect_db --> off
        httpd_can_network_memcache --> off
        httpd_can_network_relay --> off
        httpd_can_sendmail --> off
            
        

        You can change the value of any variable using the setsebool command. If you set the -P flag, the setting will persist through reboots. If, for example, you want to allow HTTPD scripts and modules to connect to the network, update the corresponding boolean variable.

        sudo setsebool -P httpd_can_network_connect ON
        

        When viewing a list of your boolean variables, you should now see that it is set to ON.

        sudo getsebool -a | grep "httpd_can"
        
          
        httpd_can_check_spam --> off
        httpd_can_connect_ftp --> off
        httpd_can_connect_ldap --> off
        httpd_can_connect_mythtv --> off
        httpd_can_connect_zabbix --> off
        httpd_can_network_connect --> on
        httpd_can_network_connect_cobbler --> off
        httpd_can_network_connect_db --> off
        httpd_can_network_memcache --> off
        httpd_can_network_relay --> off
        httpd_can_sendmail --> off
              
        

      Next Steps

      This guide provides a brief and basic introduction to SELinux administration. You can now take a deeper dive into SELinux by consulting some of the resources include in the More Information section of this guide.

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      This guide is published under a CC BY-ND 4.0 license.



      Source link

      A Beginner's Guide to Go


      Updated by Linode Contributed by Mihalis Tsoukalos

      Introduction

      Go is a modern, open source, and general-purpose programming language that began as an internal Google project and was officially announced at the end of 2009. Go was inspired by many other programming languages including C, Pascal, Alef, and Oberon. Its spiritual fathers were Robert Griesemer, Ken Thomson, and Rob Pike, who all designed Go as a language for professional programmers that want to build reliable, robust, and efficient software. Apart from its syntax and its standard functions, Go comes with a rich standard library.

      In this guide you’ll learn how to:

      The Advantages of Go

      Although Go is not perfect, it has many advantages, including the following:

      • It is a modern programming language that was made by experienced developers for developers.
      • The code is easy to read.
      • Go keeps concepts orthogonal, or simple, because a few orthogonal features work better than many overlapping ones.
      • The compiler prints practical warnings and error messages that help you solve the actual problem.
      • It has support for procedural, concurrent, and distributed programming.
      • Go supports garbage collection so you do not have to deal with memory allocation and deallocation.
      • Go can be used to build web applications and it provides a simple web server for testing purposes.
      • The standard Go library offers many packages that simplify the work of the developer.
      • It uses static linking by default, which means that the produced binary files can be easily transferred to other machines with the same OS and architecture. As a consequence, once a Go program is compiled successfully and the executable file is generated, the developer does not need to worry about dependencies and library versions.
      • The code is portable, especially among UNIX machines.
      • Go can be used for writing UNIX systems software.
      • It supports Unicode by default, which means that you do not need any extra code for printing characters from multiple human languages or symbols.

      Before You Begin

      To run the examples in this guide, your workstation or server will need to have Go installed, and the go CLI will need to be set in your terminal’s PATH:

      If you prefer to experiment with Go without installing it first, you can run the examples found in this guide using the Go Playground.

      Note

      This guide was written with Go version 1.13.

      Executing Go Code

      There are two kinds of Go programs: autonomous programs that are executable, and Go libraries. This section will describe how to format and run autonomous programs.

      A Simple Go Program

      This is the Go version of the Hello World program:

      helloworld.go
      1
      2
      3
      4
      5
      6
      7
      8
      9
      
      package main
      
      import (
          "fmt"
      )
      
      func main() {
          fmt.Println("Hello World!")
      }
      • All Go code is delivered within Go packages. For executable programs, the package name should be main. Package declarations begin with the package keyword.

      • Executable programs should have a function named main() without any function parameters. You cannot have multiple main() functions in the files of a single project. Function definitions begin with the func keyword.

        Note

      • Go packages might include import statements for importing other Go packages. However, Go demands that you use some functionality from each one of the packages that you import. There is a way to bypass this rule, however, it is considered a bad practice to do this.

        The helloworld.go file above imports the fmt package and uses the fmt.Println() function from that package.

        Note

        All exported package functions begin with an uppercase letter. This follows the Go rule: if you export something outside the current package, it should begin with an uppercase letter. This rule applies even if the field of the Go structure or the global variable is included in a Go package.

        For example, if the print function used in the above example was instead named println(), it would not be accessible to this program.

      • Go statements do not need to end with a semicolon, as the Go compiler will automatically insert semicolons where they are expected. You are free to use semicolons if you wish. For example, if you want to put two separate statements on a single line, a semicolon is needed between them.

      • Go has specific rules for how opening curly braces are formatted.

      Running the Program

      1. Now that you better understand the helloworld.go program, execute it with the go run command:

        go run helloworld.go
        

        You will see the following output:

          
        Hello World!
        
        

        This is the simplest of two ways that you can execute Go code. The go run command compiles the code and creates a temporary executable file that is automatically executed, and then it deletes that temporary executable file. This is similar to using a scripting programming language.

      2. The second method to execute Go code is to use the build command. Run the following command to use this method:

        go build helloworld.go
        

        The result of that command is a binary executable file that you have to manually execute. This method is similar to the way you execute C code on a UNIX machine. The executable file is named after the Go source filename, which means that in this case the result will be an executable file named helloworld. Go creates statically linked executable files that have no dependencies to external libraries.

      3. Execute the helloworld file:

        ./helloworld
        

        You will see the following output:

          
        Hello World!
        
        

        Note

        The go run command is usually used while experimenting and developing new Go projects. However, if you need to transfer an executable file to another system with the same architecture, you should use go build.

      Formatting Curly Braces

      The following version of the “Hello World” program will not compile:

      curly.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      
      package main
      
      import (
          "fmt"
      )
      
      func main()
      {
          fmt.Println("Hello World!")
      }

      If you execute the program above, the following error message is generated by the compiler:

      go run curly.go
      
        
      # command-line-arguments
      ./curly.go:7:6: missing function body
      ./curly.go:8:1: syntax error: unexpected semicolon or newline before {
      
      
      • This error message is generated because Go requires the use of semicolons as statement terminators in many contexts, and the compiler automatically inserts the required semicolons when it thinks that they are necessary. Putting the opening curly brace ({) on its own line makes the Go compiler look for a semicolon at the end of the previous line (func main()), which is the cause of the error message.

      • There is only one way to format curly braces in Go: the opening curly brace must not appear on its own line. Additionally, you must use curly braces even if a code block contains a single Go statement, like in the body of a for loop. You can see an example of this in the first version of the helloworld.go program.

      Variable Declarations

      Go supports assignment (=) operators and short variable declarations (:=), demonstrated in this example:

      variables.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      
      package main
      
      import (
          "fmt"
      )
      
      func main() {
          myFirstVariable := 10
          myFirstVariable = 5
          var mySecondVariable int = 10
      
          fmt.Println(myFirstVariable)
          fmt.Println(mySecondVariable)
      }
      • With := you can declare a variable and assign a value to it at the same time, without also listing the type of the variable. The type of the variable is inferred from the given value.

      • You can use = in two cases:

        • To assign a new value to an existing variable

        • To declare a new variable, provided that you also specify its type.

        For example, myFirstVariable := 10 and var mySecondVariable int = 10 will both create variables of type int with the value 10.

      • When you specifically want to control a variable’s type, it is safer to declare the variable and its type using var and then assign a value to it using =.

      Naming Conventions

      The common naming convention for variables in Go is camel case (though it is not required by the compiler), e.g.: myVariableName.

      Every variable whose name begins with a capital letter is exported from the package that it belongs to, e.g.: MyExportedVariableName. This style is enforced by the compiler.

      Uninitialized Variables

      Variables that are declared and not assigned a value will have the zero value for its type. For example, this program shows that the zero value for an int is 0:

      uninitialized.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      
      package main
      
      import (
          "fmt"
      )
      
      func main() {
          var aVariable int
          fmt.Println(aVariable)
      }

      The output from this program is:

      go run uninitialized.go
      
        
      0
      
      

      Note

      The zero value for a string variable is an empty string.

      Value Semantics

      If a new variable is declared by assigning another variable to it, then the new variable will be a copy of the first variable. This means that changing the value of either of these variables will not affect the other, as illustrated in this example:

      values.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      
      package main
      
      import (
          "fmt"
      )
      
      func main() {
          myFirstVariable := 10
          mySecondVariable := myFirstVariable
          myFirstVariable = 5
          fmt.Println(myFirstVariable)
          fmt.Println(mySecondVariable)
      }

      The output from this program is:

      go run values.go
      
        
      5
      10
      
      

      If you want to manipulate the value of an existing variable, you can use pointers instead.

      Working with Command Line Arguments

      This section will illustrate how you can work with command line arguments in Go. The presented program finds out the minimum and the maximum integer of the given command line arguments.

      cla.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      
      package main
      
      import (
          "fmt"
          "os"
          "strconv"
      )
      
      func main() {
          if len(os.Args) == 1 {
              fmt.Println("Please give one or more integers.")
              return
          }
      
          var min, max int
      
          arguments := os.Args
          temp, err := strconv.Atoi(arguments[1])
          if err != nil {
              fmt.Println("Error encountered, exiting:")
              fmt.Println(err)
              return
          } else {
              min = temp
              max = temp
          }
      
          for i := 2; i < len(arguments); i++ {
              n, err := strconv.Atoi(arguments[i])
              if err != nil {
                  fmt.Println("Error encountered, exiting:")
                  fmt.Println(err)
                  return
              }
      
              if n < min {
                  min = n
              }
              if n > max {
                  max = n
              }
          }
      
          fmt.Println("Min:", min)
          fmt.Println("Max:", max)
      }

      If you need to work with the command line arguments of a Go program you will need to import the os package. All command line arguments are kept in the os.Args slice, which you will have to process on your own. As it also happens with C, the first element of os.Args is the name of the executable, which in this case should not be processed. The len() function, used on line 10, returns the length of a slice or an array.

      If the first command line argument of the program is a valid integer, then both min and max are initialized to its value in lines 18-26. Otherwise, the script will exit. Afterwards, the script iterates through any remaining arguments in lines 28-42. This loop compares the remaining arguments’ values to the previous values found and updates min and max accordingly.

      The output of cla.go will resemble the following:

      go run cla.go -1 2 3
      
        
      Min: -1
      Max: 3
      
      

      Next Steps

      The next guide in our Go language series is our Go Functions, Loops, and Errors tutorial. More advanced guides are listed in the Go section index.

      The Standard Go Library

      In addition to reading through our guides, you might also want to review Go’s rich, well-tested and handy standard library. The list of the most important Go packages includes the following:

      Package name Description
      io Used for performing primitive I/O operations.
      bufio Used for executing buffered I/O.
      os The package offers a platform-independent interface to OS functionality.
      os/signal Used for working with OS signals.
      net The package provides a portable interface for network I/O.
      net/http The package offers HTTP client and server implementations.
      errors Used for manipulating errors.
      flag Used for working with command line arguments and flags.
      log Used for logging.
      log/syslog Used for communicating with the system log service.
      math Provides mathematical constants and functions.
      strconv Used for converting strings to other basic Go data types and vice versa.
      strings Used for manipulating Unicode strings.
      sync This package offers basic synchronization primitives. Mainly used in concurrent programming.
      testing Used for creating automated testing of Go packages.
      time This package offers functions for working with time.

      You can find the full list of the packages of the Go standard library here.

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      This guide is published under a CC BY-ND 4.0 license.



      Source link