Go Systems Programming by Tsoukalos Mihalis

Go Systems Programming by Tsoukalos Mihalis

Author:Tsoukalos, Mihalis [Tsoukalos, Mihalis]
Language: eng
Format: azw3
Tags: COM051230 - COMPUTERS / Software Development and Engineering / General, COM051000 - COMPUTERS / Programming / General, COM046070 - COMPUTERS / Operating Systems / Linux
Publisher: Packt Publishing
Published: 2017-11-04T04:00:00+00:00


Logging in Go

The log package provides a general way to log information on your Unix machine, whereas the log/syslog Go package allows you to send information to the system logging service using the logging level and the logging facility you want. Also, the time package can help you work with dates and times.

Putting data at the end of a file

As discussed in Chapter 6, File Input and Output, in this chapter, we will talk about opening a file for writing without destroying its existing data.

The Go program that will illustrate the technique, appendData.go, will accept two command-line arguments: the message you want to append and the name of the file that will store the text. This program will be presented in three parts.

The first part of appendData.go contains the following Go code:

package main import ( "fmt" "os" "path/filepath" )

As expected, the first part of the program contains the Go packages that will be used in the program.

The second part is the following:

func main() { arguments := os.Args if len(arguments) != 3 { fmt.Printf("usage: %s message filename\n", filepath.Base(arguments[0])) os.Exit(1) } message := arguments[1] filename := arguments[2] f, err := os.OpenFile(filename, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660)

The desired task is done by the os.O_APPEND flag of the os.OpenFile() function that tells Go to write at the end of the file. Additionally, the os.O_CREATE flag will make os.OpenFile() to create the file if it does not exist, which is pretty handy because it saves you from having to write Go code that tests whether the file is already there or not.

The last part of the program is the following:

if err != nil { fmt.Println(err) os.Exit(-1) } defer f.Close() fmt.Fprintf(f, "%s\n", message) }

The fmt.Fprintf() function is used here in order to write the message to the file as plain text. As you can see, appendData.go is a relatively small Go program that does not contain any surprises.

Executing appendData.go will create no output, but it will do its job, as you can see from the output of the cat(1) utility before and after the execution of appendData.go:

$ cat test [test]: test : test $ go run appendData.go test test $ cat test [test]: test : test test



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.