Skip to content

Commit

Permalink
Added basic file writing
Browse files Browse the repository at this point in the history
  • Loading branch information
sean-callahan committed Apr 21, 2016
1 parent c84ba9b commit 868206c
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
31 changes: 31 additions & 0 deletions file.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package nginxconf

import "os"

// File represents a nginx config file.
// It wraps os.File
type File struct {
*os.File
}

// OpenFile opens a nginx config file for writing only.
// If the file does not exist at that path, it is created
// with the permissions 0666.
func OpenFile(path string) (*File, error) {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return nil, err
}
return &File{f}, nil
}

// WriteDirective writes one directive to the file.
// Call this function for each directive to write.
func (f *File) WriteDirective(d *Directive) error {
b := []byte(d.String() + "\n")
_, err := f.Write(b)
if err != nil {
return err
}
return nil
}
50 changes: 50 additions & 0 deletions file_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package nginxconf

import (
"fmt"
"io/ioutil"
"os"
"testing"
)

func TestOpenFile(t *testing.T) {
f, err := OpenFile("example.conf")
if err != nil {
panic(err)
}

listen := NewDirective("listen", "80")
err = f.WriteDirective(listen)
if err != nil {
panic(err)
}

sname := NewDirective("server_name", "example.com", "www.example.com")
err = f.WriteDirective(sname)
if err != nil {
panic(err)
}

f.Close()

rf, err := os.OpenFile("example.conf", os.O_RDONLY, 0666)
if err != nil {
panic(err)
}

b, err := ioutil.ReadAll(rf)
if err != nil {
panic(err)
}

expected := fmt.Sprintf("%s\n%s\n", listen, sname)

if string(b) != expected {
t.Fail()
}

err = os.Remove("example.conf")
if err != nil {
panic(err)
}
}

0 comments on commit 868206c

Please sign in to comment.